mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
feat(agents): open conversations in separate windows (#4790)
Open in New Window moves an agent conversation to a lightweight editor window while its task and agent process keep running. The agent manager now keeps one event sink per window instead of a single one, lightweight windows keep their launch across webview reloads, and the project window keeps the task list, notifications and a copy of the unsent draft; closing the window brings the conversation and its draft back. Co-authored-by: YannABC <9603157+YannABC@users.noreply.github.com>
This commit is contained in:
@@ -141,7 +141,7 @@ struct Shared {
|
||||
paths: AgentPaths,
|
||||
runtime: tokio::runtime::Handle,
|
||||
connector: Connector,
|
||||
sink: RwLock<Option<AgentSink>>,
|
||||
sinks: RwLock<HashMap<String, AgentSink>>,
|
||||
security: RwLock<Option<SecurityHook>>,
|
||||
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
|
||||
known: Arc<Mutex<HashMap<String, Known>>>,
|
||||
@@ -213,10 +213,12 @@ impl Shared {
|
||||
}
|
||||
|
||||
fn emit(&self, event: AgentEvent) {
|
||||
let sink = self.sink.read().clone();
|
||||
if let Some(sink) = sink {
|
||||
sink(event);
|
||||
let mut sinks: Vec<_> = self.sinks.read().values().cloned().collect();
|
||||
let Some(last) = sinks.pop() else { return };
|
||||
for sink in sinks {
|
||||
sink(event.clone());
|
||||
}
|
||||
last(event);
|
||||
}
|
||||
|
||||
/// The MCP servers passed to a session, and the names of the ones off for it.
|
||||
@@ -561,7 +563,7 @@ impl AgentManager {
|
||||
paths,
|
||||
runtime,
|
||||
connector,
|
||||
sink: RwLock::new(None),
|
||||
sinks: RwLock::new(HashMap::new()),
|
||||
security: RwLock::new(None),
|
||||
new_task_approvals: RwLock::new(None),
|
||||
known,
|
||||
@@ -604,12 +606,22 @@ impl AgentManager {
|
||||
|
||||
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
|
||||
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
|
||||
*self.shared.sink.write() = Some(sink);
|
||||
self.subscribe_as("", sink)
|
||||
}
|
||||
|
||||
/// Routes events to `sink` too, replacing only the sink `subscriber` (a view of the project) had.
|
||||
pub fn subscribe_as(&self, subscriber: &str, sink: AgentSink) -> Vec<AgentTask> {
|
||||
self.shared.sinks.write().insert(subscriber.to_owned(), sink);
|
||||
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().snapshot()).collect();
|
||||
tasks.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
tasks
|
||||
}
|
||||
|
||||
/// A closed view releases its sink, never the task or its agent process.
|
||||
pub fn unsubscribe(&self, subscriber: &str) {
|
||||
self.shared.sinks.write().remove(subscriber);
|
||||
}
|
||||
|
||||
/// Sets the callback used to read the active command execution security policy.
|
||||
pub fn set_security_hook(&self, hook: SecurityHook) {
|
||||
*self.shared.security.write() = Some(hook);
|
||||
@@ -2000,7 +2012,7 @@ impl AgentManager {
|
||||
// What arrived after the last save (a subagent's late updates).
|
||||
task.persist();
|
||||
}
|
||||
*self.shared.sink.write() = None;
|
||||
self.shared.sinks.write().clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -452,6 +452,35 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
manager_at(dir, &dir.join("models.json"), agent)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subscribers_do_not_replace_or_close_each_other() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let main = Arc::new(Mutex::new(Vec::new()));
|
||||
let child = Arc::new(Mutex::new(Vec::new()));
|
||||
let subscribe = |window: &str, events: &Arc<Mutex<Vec<AgentEvent>>>| {
|
||||
let events = events.clone();
|
||||
mgr.subscribe_as(window, Arc::new(move |event| events.lock().push(event)));
|
||||
};
|
||||
subscribe("main", &main);
|
||||
subscribe("editor-main-1", &child);
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(main.lock().len(), 1);
|
||||
assert_eq!(child.lock().len(), 1);
|
||||
// A reloaded webview replaces only its own old channel.
|
||||
let reloaded = Arc::new(Mutex::new(Vec::new()));
|
||||
subscribe("editor-main-1", &reloaded);
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(main.lock().len(), 2);
|
||||
assert_eq!(child.lock().len(), 1);
|
||||
assert_eq!(reloaded.lock().len(), 1);
|
||||
mgr.unsubscribe("editor-main-1");
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(main.lock().len(), 3);
|
||||
assert_eq!(reloaded.lock().len(), 1);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
// These tests speak to FakeAgent, never an installed CLI, including after a provider reload.
|
||||
let agents = dir.join("agents");
|
||||
|
||||
@@ -17,12 +17,28 @@ use ide_tools::InstallEvent;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Streams the project's agent events to this window; returns every task.
|
||||
/// Streams the project's agent events to `subscriber`, one of the project's windows (a remote
|
||||
/// host sees them all as one `window`); returns every task.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_subscribe(host: &Host, window: &str, on_event: Channel<AgentEvent>) -> IdeResult<Vec<AgentTask>> {
|
||||
Ok(host.project(window)?.agents.subscribe(std::sync::Arc::new(move |e| {
|
||||
let _ = on_event.send(e);
|
||||
})))
|
||||
pub fn agent_subscribe(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
on_event: Channel<AgentEvent>,
|
||||
subscriber: String,
|
||||
) -> IdeResult<Vec<AgentTask>> {
|
||||
Ok(host.project(window)?.agents.subscribe_as(
|
||||
&subscriber,
|
||||
std::sync::Arc::new(move |e| {
|
||||
let _ = on_event.send(e);
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Stops the events of a window that closed.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.unsubscribe(&subscriber);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -1125,4 +1141,5 @@ ide_command::domain!(
|
||||
agent_subscribe,
|
||||
agent_unarchive,
|
||||
agent_unqueue,
|
||||
agent_unsubscribe,
|
||||
);
|
||||
|
||||
@@ -288,6 +288,12 @@ pub fn run() {
|
||||
window_groups::frame_changed(window.app_handle(), window.label());
|
||||
}
|
||||
tauri::WindowEvent::Destroyed => {
|
||||
// Also release a view that failed during startup, before the parent could watch it.
|
||||
if let Some(state) = window.try_state::<AppState>()
|
||||
&& let Ok(project) = state.host.project(window.label())
|
||||
{
|
||||
project.agents.unsubscribe(window.label());
|
||||
}
|
||||
window_zoom::forget(window.label());
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
|
||||
@@ -84,11 +84,16 @@ pub struct Launch {
|
||||
pub editor: Option<Box<EditorLaunch>>,
|
||||
}
|
||||
|
||||
/// A file opened in a lightweight editor window, with optional caret / selection (0-based).
|
||||
/// What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
/// the tab of another editor kind.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EditorLaunch {
|
||||
pub path: ide_core::IpcPath,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<ide_core::IpcPath>,
|
||||
/// The tab's editor input, as JSON.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub input: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub line: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -355,6 +360,12 @@ impl WindowsState {
|
||||
|
||||
pub fn take_launch(&self, label: &str) -> Option<Launch> {
|
||||
let mut launches = self.launches.lock();
|
||||
// Lightweight windows need their launch again when their webview reloads.
|
||||
if let Some(launch) = launches.get(label)
|
||||
&& launch.editor.is_some()
|
||||
{
|
||||
return Some(launch.clone());
|
||||
}
|
||||
let launch = launches.remove(label)?;
|
||||
if launch.project.is_some() || launch.remote.is_some() || !launch.files.is_empty() || launch.diff.is_some() {
|
||||
self.opening.lock().insert(label.to_owned(), launch.clone());
|
||||
@@ -2755,6 +2766,27 @@ mod tests {
|
||||
assert_eq!(st.take_launch("project-1"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_launch_survives_webview_reload_until_window_closes() {
|
||||
let st = WindowsState::default();
|
||||
let launch = Launch {
|
||||
editor: Some(Box::new(EditorLaunch {
|
||||
path: None,
|
||||
input: Some(r#"{"kind":"agent-session","key":"agent:running-task"}"#.into()),
|
||||
line: None,
|
||||
column: None,
|
||||
end_line: None,
|
||||
end_column: None,
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
st.set_launch("editor-main-3", launch.clone());
|
||||
assert_eq!(st.take_launch("editor-main-3"), Some(launch.clone()));
|
||||
assert_eq!(st.take_launch("editor-main-3"), Some(launch));
|
||||
st.forget("editor-main-3");
|
||||
assert!(st.take_launch("editor-main-3").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taken_launch_owns_its_window_until_completion() {
|
||||
for launch in [
|
||||
|
||||
@@ -49,6 +49,7 @@ agent_stop_background always project_host bin
|
||||
agent_subscribe always project_host bindings sync
|
||||
agent_unarchive always project_host bindings sync
|
||||
agent_unqueue always project_host bindings sync
|
||||
agent_unsubscribe always project_host bindings sync
|
||||
analysis_locate_duplicates always project_host bindings async
|
||||
android_devices trusted desktop bindings async
|
||||
android_logcat trusted desktop bindings async
|
||||
|
||||
+25
-7
@@ -146,11 +146,16 @@ export const commands = {
|
||||
agentShell: (task: string, command: string, request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("agent_shell", { task, command, request })),
|
||||
/** Stops one of the task's background tasks. */
|
||||
agentStopBackground: (task: string, background: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_stop_background", { task, background })),
|
||||
/** Streams the project's agent events to this window; returns every task. */
|
||||
agentSubscribe: (onEvent: Channel<AgentEvent_Deserialize>) => typedError<AgentTask_Serialize[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
|
||||
/**
|
||||
* Streams the project's agent events to `subscriber`, one of the project's windows (a remote
|
||||
* host sees them all as one `window`); returns every task.
|
||||
*/
|
||||
agentSubscribe: (onEvent: Channel<AgentEvent_Deserialize>, subscriber: string) => typedError<AgentTask_Serialize[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent, subscriber })),
|
||||
agentUnarchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_unarchive", { task })),
|
||||
/** Drops a queued message and returns it (to edit it). */
|
||||
agentUnqueue: (task: string, queued: string) => typedError<AgentQueued, IdeError>(__TAURI_INVOKE("agent_unqueue", { task, queued })),
|
||||
/** Stops the events of a window that closed. */
|
||||
agentUnsubscribe: (subscriber: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_unsubscribe", { subscriber })),
|
||||
/** Locate Duplicates over the files of `scope`. */
|
||||
analysisLocateDuplicates: (request: RequestId, scope: SearchScope, options: DuplicateOptions) => typedError<DuplicatesReport, IdeError>(__TAURI_INVOKE("analysis_locate_duplicates", { request, scope, options })),
|
||||
/** Devices `adb` knows about, online ones first. */
|
||||
@@ -5610,21 +5615,34 @@ export type EditorGeneralSettings = {
|
||||
richTextCopy?: boolean,
|
||||
};
|
||||
|
||||
/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */
|
||||
/**
|
||||
* What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
* the tab of another editor kind.
|
||||
*/
|
||||
export type EditorLaunch = EditorLaunch_Serialize | EditorLaunch_Deserialize;
|
||||
|
||||
/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */
|
||||
/**
|
||||
* What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
* the tab of another editor kind.
|
||||
*/
|
||||
export type EditorLaunch_Deserialize = {
|
||||
path: IpcPath,
|
||||
path?: IpcPath | null,
|
||||
/** The tab's editor input, as JSON. */
|
||||
input?: string | null,
|
||||
line?: number | null,
|
||||
column?: number | null,
|
||||
endLine?: number | null,
|
||||
endColumn?: number | null,
|
||||
};
|
||||
|
||||
/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */
|
||||
/**
|
||||
* What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
* the tab of another editor kind.
|
||||
*/
|
||||
export type EditorLaunch_Serialize = {
|
||||
path: IpcPath,
|
||||
path?: IpcPath | null,
|
||||
/** The tab's editor input, as JSON. */
|
||||
input?: string | null,
|
||||
line?: number | null,
|
||||
column?: number | null,
|
||||
endLine?: number | null,
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
import { activateEditorWindow } from "./EditorWindow";
|
||||
|
||||
const boot = vi.hoisted(() => ({
|
||||
emit: vi.fn(async () => {}),
|
||||
prepare: vi.fn(async (input: EditorInput) => input),
|
||||
openInput: vi.fn(async (_input: EditorInput, _options: unknown) => {}),
|
||||
openFile: vi.fn(async () => {}),
|
||||
setProject: vi.fn(),
|
||||
takeLaunch: vi.fn(),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/event", () => ({ emitTo: boot.emit }));
|
||||
vi.mock("@tauri-apps/api/window", () => ({
|
||||
getCurrentWindow: () => ({
|
||||
label: "editor-main-3",
|
||||
onCloseRequested: async () => () => {},
|
||||
setTitle: async () => {},
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
commands: {
|
||||
windowTakeLaunch: boot.takeLaunch,
|
||||
projectCurrent: async () => ({ name: "Project", root: "/project", settings: {} }),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/platform/context", () => ({ setContext: vi.fn() }));
|
||||
vi.mock("@/platform/project", () => ({ basename: (path: string) => path, useProject: { setState: boot.setProject } }));
|
||||
vi.mock("@/platform/remote", () => ({ restoreRemote: async () => {} }));
|
||||
vi.mock("@/platform/platformInfo", () => ({ usePlatform: vi.fn() }));
|
||||
vi.mock("@/ui", () => ({ Spinner: () => null, T: () => null, isPopupOpen: () => false }));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
editorService: () => ({ openInput: boot.openInput, openFile: boot.openFile }),
|
||||
notifications: () => ({ notify: vi.fn() }),
|
||||
useContributions: {
|
||||
getState: () => ({ editorKinds: new Map([["agent-session", { prepareWindowInput: boot.prepare }]]) }),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/workbench/EditorArea", () => ({ EditorArea: () => null }));
|
||||
vi.mock("@/workbench/OverlayHost", () => ({ OverlayHost: () => null }));
|
||||
vi.mock("@/workbench/TitleBar", () => ({ TitleBar: () => null }));
|
||||
vi.mock("@/workbench/WindowResizeHandles", () => ({ WindowResizeHandles: () => null }));
|
||||
vi.mock("@/workbench/theme", () => ({ useApplyTheme: () => {} }));
|
||||
vi.mock("@/workbench/messages", () => ({ ask: vi.fn() }));
|
||||
vi.mock("./controller", () => ({ editorController: vi.fn(), tabTitle: () => "Conversation" }));
|
||||
|
||||
let stop: (() => void) | undefined;
|
||||
const input: EditorInput = { kind: "agent-session", key: "agent:one", data: { task: "one" } };
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
boot.takeLaunch.mockResolvedValue({ editor: { input: JSON.stringify(input) } });
|
||||
});
|
||||
afterEach(() => stop?.());
|
||||
|
||||
describe("lightweight window handoff", () => {
|
||||
it("opens and reports ready only after its kind prepared the input", async () => {
|
||||
let ready!: (input: EditorInput) => void;
|
||||
boot.prepare.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
ready = resolve;
|
||||
}),
|
||||
);
|
||||
stop = activateEditorWindow("main");
|
||||
await vi.waitFor(() => expect(boot.prepare).toHaveBeenCalledWith(input));
|
||||
expect(boot.openInput).not.toHaveBeenCalled();
|
||||
expect(boot.emit).not.toHaveBeenCalled();
|
||||
const recovered = { ...input, data: { task: "one", draft: { text: "Latest draft" } } };
|
||||
ready(recovered);
|
||||
await vi.waitFor(() =>
|
||||
expect(boot.emit).toHaveBeenCalledWith("main", "openidea://editor/ready", {
|
||||
label: "editor-main-3",
|
||||
path: input.key,
|
||||
ok: true,
|
||||
}),
|
||||
);
|
||||
expect(boot.openInput).toHaveBeenCalledWith(recovered, { focus: true });
|
||||
});
|
||||
|
||||
it("reports failure without opening a broken conversation", async () => {
|
||||
boot.prepare.mockRejectedValueOnce(new Error("Cannot load conversation"));
|
||||
stop = activateEditorWindow("main");
|
||||
await vi.waitFor(() =>
|
||||
expect(boot.emit).toHaveBeenCalledWith("main", "openidea://editor/ready", {
|
||||
label: "editor-main-3",
|
||||
path: input.key,
|
||||
ok: false,
|
||||
error: "Error: Cannot load conversation",
|
||||
}),
|
||||
);
|
||||
expect(boot.openInput).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Lightweight editor window (`editor-<parent>-<n>`): one project file in a window of its own
|
||||
* ("Open in New Window" without a second workbench).
|
||||
* Lightweight editor window (`editor-<parent>-<n>`): one project file, or one tab of another
|
||||
* editor kind, in a window of its own ("Open in New Window" without a second workbench).
|
||||
*/
|
||||
import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
@@ -15,14 +15,14 @@ import { basename, useProject } from "@/platform/project";
|
||||
import { restoreRemote } from "@/platform/remote";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { Spinner, T, isPopupOpen } from "@/ui";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { editorService, notifications, useContributions, type EditorInput } from "@/workbench/contributions";
|
||||
import { EditorArea } from "@/workbench/EditorArea";
|
||||
import { OverlayHost } from "@/workbench/OverlayHost";
|
||||
import { TitleBar } from "@/workbench/TitleBar";
|
||||
import { WindowResizeHandles } from "@/workbench/WindowResizeHandles";
|
||||
import { useApplyTheme } from "@/workbench/theme";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { editorController } from "./controller";
|
||||
import { editorController, tabTitle } from "./controller";
|
||||
import type { DocModel } from "./model/document";
|
||||
import styles from "./EditorWindow.module.css";
|
||||
|
||||
@@ -71,7 +71,7 @@ async function settleUnsaved(models: DocModel[], project: string | null): Promis
|
||||
return answer.button === "save" || answer.button === "discard";
|
||||
}
|
||||
|
||||
/** Loads the launch's file into this window's editor. */
|
||||
/** Loads the launch's file or tab into this window's editor. */
|
||||
export function activateEditorWindow(parent: string): () => void {
|
||||
let projectName: string | null = null;
|
||||
const native = getCurrentWindow();
|
||||
@@ -131,14 +131,20 @@ export function activateEditorWindow(parent: string): () => void {
|
||||
try {
|
||||
await restoreRemote();
|
||||
const launch = (await commands.windowTakeLaunch())?.editor as EditorLaunch | null | undefined;
|
||||
if (!launch?.path) throw new Error(tx("Missing editor request"));
|
||||
path = launch.path;
|
||||
let input = launch?.input ? (JSON.parse(launch.input) as EditorInput) : null;
|
||||
path = launch?.path ?? input?.key ?? "";
|
||||
if (!launch || !path) throw new Error(tx("Missing editor request"));
|
||||
const project = await commands.projectCurrent();
|
||||
if (!project) throw new Error(tx("The editor’s project is no longer open"));
|
||||
projectName = project.name;
|
||||
// Settings only: restoring the project's editor session here would overwrite the main window's tabs.
|
||||
useProject.setState({ settings: project.settings });
|
||||
// Other editor kinds read the project; the controller leaves its saved tabs to the main window.
|
||||
useProject.setState(input ? { project, settings: project.settings } : { settings: project.settings });
|
||||
setContext("projectOpen", true);
|
||||
if (input) {
|
||||
const prepare = useContributions.getState().editorKinds.get(input.kind)?.prepareWindowInput;
|
||||
if (prepare) input = await prepare(input);
|
||||
}
|
||||
if (disposed) return;
|
||||
const selection =
|
||||
launch.line != null && launch.column != null
|
||||
? {
|
||||
@@ -147,9 +153,11 @@ export function activateEditorWindow(parent: string): () => void {
|
||||
...(launch.endLine != null ? { endLine: launch.endLine, endCol: launch.endColumn ?? 0 } : {}),
|
||||
}
|
||||
: undefined;
|
||||
await editorService().openFile(path, { focus: true, selection });
|
||||
if (input) await editorService().openInput(input, { focus: true });
|
||||
else await editorService().openFile(path, { focus: true, selection });
|
||||
useEditorWindow.setState({ path });
|
||||
showCaption(`${project.name} — ${basename(path)}`);
|
||||
const title = input ? tabTitle(input, useContributions.getState().editorKinds) : basename(path);
|
||||
showCaption(`${project.name} — ${title}`);
|
||||
await reportReady(parent, { path, ok: true });
|
||||
} catch (error) {
|
||||
const message = String(error);
|
||||
@@ -171,7 +179,7 @@ export function EditorWindow() {
|
||||
const ownTitleBar = usePlatform((s) => s.overlayTitleBar || s.framelessTitleBar);
|
||||
return (
|
||||
<main className={clsx(styles.window, os === "linux" && styles.edge)}>
|
||||
{ownTitleBar && <TitleBar minimal dialog title={title} />}
|
||||
{ownTitleBar && <TitleBar minimal title={title} />}
|
||||
{error ? (
|
||||
<div className={styles.error} role="alert">
|
||||
{error}
|
||||
|
||||
@@ -54,6 +54,7 @@ import { hoverActionsAt } from "@/platform/hoverActions";
|
||||
import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog";
|
||||
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
|
||||
import {
|
||||
@@ -663,6 +664,8 @@ export class EditorController implements SlotHost {
|
||||
|
||||
/** Reopens the tabs, splits and carets saved for `root` (after the project opened). */
|
||||
async restoreSession(root: string) {
|
||||
// The project window owns the saved layout; a lightweight window shows what it was opened for.
|
||||
if (auxiliaryWindow()) return;
|
||||
this.sessionRoot = root;
|
||||
// A window close dropped this session: the next open starts from the tabs opened now.
|
||||
if (this.forgottenSessions.delete(root)) return;
|
||||
@@ -1913,6 +1916,8 @@ export class EditorController implements SlotHost {
|
||||
/** Open a lightweight aux editor (or a full window outside the project), then remove the original tab. */
|
||||
async detachTab(paneId: string, tabId: string): Promise<boolean> {
|
||||
const tab = useTabs.getState().panes[paneId]?.tabs.find((t) => t.id === tabId);
|
||||
const moves = tab && useContributions.getState().editorKinds.get(tab.input.kind)?.openInWindow;
|
||||
if (moves) return moves(tab.input);
|
||||
const path = tab?.input.path;
|
||||
if (
|
||||
!tab ||
|
||||
@@ -1981,6 +1986,11 @@ export class EditorController implements SlotHost {
|
||||
},
|
||||
});
|
||||
}
|
||||
/** Shows `input` in a lightweight window of this project; resolves to the window's label once it is shown. */
|
||||
openInWindow(input: EditorInput): Promise<string> {
|
||||
if (!isTauri() || isRemoteWindow()) return Promise.reject(new Error(t("app.window.desktopOnly")));
|
||||
return openLightweightEditor({ input: JSON.stringify(input) }, windowBackgroundHex(), input.key);
|
||||
}
|
||||
/** IDEA "Open in Opposite Group": the tab stays and a copy opens next door (or in a new split). */
|
||||
openInOpposite(paneId: string, tabId: string) {
|
||||
const s = useTabs.getState();
|
||||
@@ -2294,8 +2304,9 @@ export class EditorController implements SlotHost {
|
||||
{ label: "Unsplit All", run: () => void this.unsplitAll(paneId) },
|
||||
] as MenuItem[])
|
||||
: []),
|
||||
...(tab.input.path &&
|
||||
(tab.input.kind === "file" || documentLifecycle(tab.input, useContributions.getState().editorKinds))
|
||||
...(useContributions.getState().editorKinds.get(tab.input.kind)?.openInWindow ||
|
||||
(tab.input.path &&
|
||||
(tab.input.kind === "file" || documentLifecycle(tab.input, useContributions.getState().editorKinds)))
|
||||
? ([{ label: "Open in New Window", run: () => void this.detachTab(paneId, tab.id) }] as MenuItem[])
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
|
||||
@@ -39,7 +39,7 @@ beforeEach(() => {
|
||||
status: "ok",
|
||||
data: { kind: "opened", label: "second" },
|
||||
});
|
||||
vi.spyOn(light, "openLightweightEditor").mockResolvedValue();
|
||||
vi.spyOn(light, "openLightweightEditor").mockResolvedValue("editor-main-1");
|
||||
});
|
||||
afterEach(() => {
|
||||
ctrl?.stop();
|
||||
@@ -51,6 +51,24 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("detachTab", () => {
|
||||
it("leaves the move to an editor kind that moves its own tabs", async () => {
|
||||
const openInWindow = vi.fn(async () => true);
|
||||
unregister = registerEditorKind({ kind: "chat", component: () => null, title: () => "Chat", openInWindow });
|
||||
ctrl = new EditorController(createMemoryBackend({}));
|
||||
ctrl.start();
|
||||
await ctrl.openInput({ kind: "chat", key: "chat:1", data: { id: 1 } }, { focus: false });
|
||||
const [pane, id] = current();
|
||||
expect(await ctrl.detachTab(pane, id)).toBe(true);
|
||||
expect(openInWindow).toHaveBeenCalledWith(expect.objectContaining({ key: "chat:1", data: { id: 1 } }));
|
||||
expect(light.openLightweightEditor).not.toHaveBeenCalled();
|
||||
await ctrl.openInWindow({ kind: "chat", key: "chat:1", data: { id: 1 } });
|
||||
expect(light.openLightweightEditor).toHaveBeenCalledWith(
|
||||
{ input: JSON.stringify({ kind: "chat", key: "chat:1", data: { id: 1 } }) },
|
||||
null,
|
||||
"chat:1",
|
||||
);
|
||||
});
|
||||
|
||||
it("moves a project file to a lightweight editor without saving first", async () => {
|
||||
useProject.setState({
|
||||
project: { root: "/p", workspace: { projects: ["/p"] } } as never,
|
||||
|
||||
@@ -45,6 +45,7 @@ export function activate(): void | (() => void) {
|
||||
provideEditorService({
|
||||
openFile: (path, options) => ctrl.openFile(path, options),
|
||||
openInput: (input, options) => ctrl.openInput(input, options),
|
||||
openInWindow: (input) => ctrl.openInWindow(input),
|
||||
openUntitled: (options) => ctrl.openUntitled(options),
|
||||
activePath: () => ctrl.activePath(),
|
||||
activeCursor: () => ctrl.activeCursor(),
|
||||
|
||||
@@ -5,18 +5,23 @@ import { call, commands, type EditorLaunch } from "@/platform/ipc";
|
||||
|
||||
const READY_MS = 30_000;
|
||||
|
||||
/** Opens a project-file aux editor and resolves once it has taken over the document. */
|
||||
export async function openLightweightEditor(launch: EditorLaunch, background: string | null): Promise<void> {
|
||||
/** Opens a lightweight editor window; resolves to its label once it shows the file or tab. */
|
||||
export async function openLightweightEditor(
|
||||
launch: EditorLaunch,
|
||||
background: string | null,
|
||||
/** What the window reports as shown: the file, or the key of the launch's tab. */
|
||||
target = launch.path,
|
||||
): Promise<string> {
|
||||
const parent = getCurrentWindow();
|
||||
let off: (() => void) | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
return await new Promise<string>((resolve, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(tx("Timed out opening the editor window"))), READY_MS);
|
||||
void parent
|
||||
.listen<EditorReadyResult>(EDITOR_READY, ({ payload }) => {
|
||||
if (payload.path && payload.path !== launch.path) return;
|
||||
if (payload.ok) resolve();
|
||||
if (payload.path && payload.path !== target) return;
|
||||
if (payload.ok) resolve(payload.label);
|
||||
else reject(new Error(payload.error || tx("Could not open the editor window")));
|
||||
})
|
||||
.then((unlisten) => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { activate as editor } from "./editor/core";
|
||||
import { activate as agents } from "./features/agents";
|
||||
import { activateEditorWindow, EditorWindow } from "./editor/core/EditorWindow";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { installMenuBridge } from "./features/app/menuBridge";
|
||||
@@ -8,8 +9,8 @@ import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Lightweight editor window of project window `parent`: one file, sharing the
|
||||
* parent's documents and language servers, with no workbench chrome.
|
||||
* Lightweight editor window of project window `parent`: one file or agent conversation, sharing
|
||||
* the parent's documents, language servers and agents, with no workbench chrome.
|
||||
*/
|
||||
export function bootEditorWindow(parent: string): ComponentType {
|
||||
activateList("editor window", [
|
||||
@@ -17,6 +18,7 @@ export function bootEditorWindow(parent: string): ComponentType {
|
||||
["settings", trackRuntimeSettings],
|
||||
["menu", installMenuBridge],
|
||||
["editor", editor],
|
||||
["agents", agents],
|
||||
["editorWindow", () => activateEditorWindow(parent)],
|
||||
]);
|
||||
installKeyboardDispatcher();
|
||||
|
||||
@@ -42,11 +42,14 @@ import {
|
||||
refreshProviders,
|
||||
refreshTaskModels,
|
||||
releaseClosedTaskCache,
|
||||
trackPromptHistory,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
import { TaskStatusMark } from "./TaskStatusMark";
|
||||
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
|
||||
import { replyActions } from "./replyActions";
|
||||
import { activateTaskWindows, moveTaskToWindow, prepareTaskWindowInput, taskTabClosed } from "./taskWindows";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
|
||||
export { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
@@ -62,6 +65,9 @@ function trackAgentButtonSetting(): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
/** A lightweight editor window has agents only once it shows a conversation. */
|
||||
const agentsHere = () => !auxiliaryWindow() || useAgents.getState().loaded;
|
||||
|
||||
export function activate(): () => void {
|
||||
const sync = (root: string | null | undefined) => {
|
||||
disconnect();
|
||||
@@ -69,6 +75,8 @@ export function activate(): () => void {
|
||||
};
|
||||
sync(useProject.getState().project?.root);
|
||||
const disposers = [
|
||||
activateTaskWindows(),
|
||||
trackPromptHistory(),
|
||||
activateSettingsPages(),
|
||||
trackEditorCopies(),
|
||||
registerAgentContextSource({
|
||||
@@ -143,10 +151,16 @@ export function activate(): () => void {
|
||||
// Tabs of tasks deleted meanwhile are closed when the tasks load (`connect`).
|
||||
restorable: true,
|
||||
onTabClose: (tabId) => clearAgentTabFontZoom(tabId),
|
||||
prepareWindowInput: prepareTaskWindowInput,
|
||||
onClose: (input) => {
|
||||
const task = (input.data as { task?: string } | undefined)?.task;
|
||||
if (task) releaseClosedTaskCache(task);
|
||||
if (!task) return;
|
||||
releaseClosedTaskCache(task);
|
||||
taskTabClosed(task);
|
||||
},
|
||||
...(auxiliaryWindow()
|
||||
? {}
|
||||
: { openInWindow: (input) => moveTaskToWindow((input.data as { task: string }).task) }),
|
||||
// Rebuilding a long conversation on every switch back is slow.
|
||||
keepAlive: true,
|
||||
}),
|
||||
@@ -182,7 +196,7 @@ export function activate(): () => void {
|
||||
menus: ["editor", "projectView"],
|
||||
order: 80,
|
||||
items: (menu, { paths, dirs }) =>
|
||||
paths.length && !paths.some(isVirtualUri)
|
||||
paths.length && !paths.some(isVirtualUri) && agentsHere()
|
||||
? [
|
||||
{
|
||||
kind: "action",
|
||||
@@ -193,6 +207,27 @@ export function activate(): () => void {
|
||||
: [],
|
||||
}),
|
||||
registerActions([
|
||||
{
|
||||
id: "agents.moveToNewWindow",
|
||||
title: "Open in New Window",
|
||||
category: "Agents",
|
||||
when: "projectOpen",
|
||||
enabled: ({ arg }) =>
|
||||
!auxiliaryWindow() &&
|
||||
(typeof arg === "string" ||
|
||||
maybeEditorService()?.activeInput?.()?.kind === SESSION_KIND ||
|
||||
!!useAgents.getState().docked),
|
||||
run: async ({ arg }) => {
|
||||
const input = maybeEditorService()?.activeInput?.();
|
||||
const task =
|
||||
typeof arg === "string"
|
||||
? arg
|
||||
: input?.kind === SESSION_KIND
|
||||
? (input.data as { task: string }).task
|
||||
: useAgents.getState().docked;
|
||||
if (task) await moveTaskToWindow(task);
|
||||
},
|
||||
},
|
||||
...taskActions,
|
||||
...replyActions,
|
||||
{
|
||||
@@ -303,6 +338,7 @@ export function activate(): () => void {
|
||||
icon: "toolwindow-agents",
|
||||
when: "projectOpen",
|
||||
keywords: ["agent", "chat", "context", "reference", "selection"],
|
||||
enabled: agentsHere,
|
||||
run: ({ arg }) => {
|
||||
if (Array.isArray(arg)) sendPaths(arg.filter((p): p is string => typeof p === "string"));
|
||||
else sendSelection();
|
||||
|
||||
@@ -4,6 +4,9 @@ import type { AgentTask, ProjectInfo } from "@/bindings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { sendPaths, sendSelection } from "./references";
|
||||
import { HOME, composerDraft, useAgents } from "./store";
|
||||
import { installTaskWindowRouting } from "./taskWindowRouting";
|
||||
import type { ComposerDraft } from "./composerModel";
|
||||
import { diagnoseTestFailure } from "./testFailure";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ notify: vi.fn(), editor: null as unknown }));
|
||||
vi.mock("@/editor/api", async (original) => ({
|
||||
@@ -51,6 +54,32 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("Send to Agent from the Project view", () => {
|
||||
it("appends references and failed-test context to the draft being edited in another window", () => {
|
||||
setup({ task: task(BACK, BACK, "local") });
|
||||
useAgents.setState({ composers: new Map([["t", { text: "Stale parent draft", files: [], images: [] }]]) });
|
||||
let remote: ComposerDraft = { text: "Typed in the child", files: [], images: [] };
|
||||
const update = vi.fn((key: string, patch: Partial<ComposerDraft>) => {
|
||||
if (key !== "t") return false;
|
||||
remote = { ...remote, ...patch };
|
||||
return true;
|
||||
});
|
||||
const stop = installTaskWindowRouting(() => true, undefined, {
|
||||
read: (key) => (key === "t" ? remote : undefined),
|
||||
update,
|
||||
});
|
||||
try {
|
||||
expect(sendPaths([`${BACK}/pom.xml`])).toBe(true);
|
||||
expect(remote.text).toBe("Typed in the child @pom.xml ");
|
||||
expect(remote.files).toEqual([{ path: `${BACK}/pom.xml`, rel: "pom.xml" }]);
|
||||
diagnoseTestFailure({ name: "example", output: ["Expected success"] });
|
||||
expect(remote.text).toContain("Typed in the child @pom.xml\n\nThe test example failed.");
|
||||
expect(update).toHaveBeenCalledTimes(2);
|
||||
expect(useAgents.getState().composers.get("t")?.text).toBe("Stale parent draft");
|
||||
} finally {
|
||||
stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("single project: files and folders as before", () => {
|
||||
setup({});
|
||||
expect(sendPaths([`${BACK}/pom.xml`, `${BACK}/src/`])).toBe(true);
|
||||
|
||||
@@ -22,6 +22,8 @@ import type {
|
||||
RequestId,
|
||||
} from "@/bindings";
|
||||
import { useChangesOptions } from "./changesOptions";
|
||||
import { auxiliaryWindow, windowLabel } from "@/platform/auxWindow";
|
||||
import { routeToWindow, taskWindowDraft, taskWindowFocused, updateTaskWindowDraft } from "./taskWindowRouting";
|
||||
import { clearAgentTaskFontZoom, resetAllAgentFontZoom } from "./fontZoom";
|
||||
import { clearDismissedAssets } from "./sessionAssetsModel";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
@@ -321,9 +323,14 @@ export function setDraftOption(id: string, value: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export const composerDraft = (key: string) => useAgents.getState().composers.get(key) ?? emptyDraft();
|
||||
export const composerDraft = (key: string) =>
|
||||
taskWindowDraft(key) ?? useAgents.getState().composers.get(key) ?? emptyDraft();
|
||||
|
||||
export function updateComposer(key: string, patch: Partial<ComposerDraft>) {
|
||||
if (updateTaskWindowDraft(key, patch)) {
|
||||
useAgents.setState({ lastComposer: key });
|
||||
return;
|
||||
}
|
||||
useAgents.setState((s) => ({
|
||||
composers: new Map(s.composers).set(key, {
|
||||
...(s.composers.get(key) ?? emptyDraft()),
|
||||
@@ -345,7 +352,7 @@ function clearSubmittedComposer(key: string, submitted: ComposerDraft, started:
|
||||
/** Session tabs on screen; a task can be shown in more than one split. */
|
||||
const visible = new Map<string, number>();
|
||||
const windowFocused = () => document.visibilityState !== "hidden" && document.hasFocus();
|
||||
const viewing = (task: string) => visible.has(task) && windowFocused();
|
||||
const viewing = (task: string) => (visible.has(task) && windowFocused()) || taskWindowFocused(task);
|
||||
|
||||
function setUnread(task: string, value: boolean) {
|
||||
const s = useAgents.getState();
|
||||
@@ -527,7 +534,7 @@ export async function connect(): Promise<void> {
|
||||
let tasks: AgentTask[], providers: AgentProvider[];
|
||||
try {
|
||||
[tasks, providers] = await Promise.all([
|
||||
call(commands.agentSubscribe(channel)),
|
||||
call(commands.agentSubscribe(channel, windowLabel())),
|
||||
useProject.getState().project?.trusted === false
|
||||
? Promise.resolve([] as AgentProvider[])
|
||||
: call(commands.agentProviders()),
|
||||
@@ -778,7 +785,8 @@ function onEvent(e: AgentEvent) {
|
||||
unread.delete(e.id);
|
||||
// A deleted task leaves its group and the pinned area.
|
||||
const organize = pruneOrganize(s.organize, tasks.values());
|
||||
if (organize !== s.organize) saveOrganize(s.organizeRoot, organize);
|
||||
// The project window saves it: a lightweight window's copy may be older.
|
||||
if (organize !== s.organize && !auxiliaryWindow()) saveOrganize(s.organizeRoot, organize);
|
||||
useAgents.setState({
|
||||
tasks,
|
||||
composers,
|
||||
@@ -845,6 +853,8 @@ function onEvent(e: AgentEvent) {
|
||||
|
||||
/** In-app balloon for an Attention event; OS delivery goes through the general balloon path. */
|
||||
function notifyAttention(taskId: string, reason: "finished" | "input" | "failed") {
|
||||
// The project window remains responsible for task notifications.
|
||||
if (auxiliaryWindow()) return;
|
||||
if (viewing(taskId) || quietTasks.has(taskId)) return;
|
||||
const task = useAgents.getState().tasks.get(taskId);
|
||||
const title = task?.title ?? "Agent";
|
||||
@@ -1047,6 +1057,7 @@ export function useAgentCommands(
|
||||
}
|
||||
|
||||
export function openTask(task: string) {
|
||||
if (routeToWindow(task)) return;
|
||||
forgetClosed(task);
|
||||
if (useAgents.getState().sessionLocation === "toolWindow") {
|
||||
showDockedTask(task);
|
||||
@@ -1150,6 +1161,7 @@ export async function closeAndNewTask() {
|
||||
|
||||
/** Opens the New Task page; `prompt` pre-fills it. */
|
||||
export function openHome(prompt?: string) {
|
||||
if (routeToWindow(null, prompt)) return;
|
||||
const project = useProject.getState().project;
|
||||
useAgents.setState({ lastComposer: HOME });
|
||||
if (project?.workspace) {
|
||||
@@ -1360,6 +1372,15 @@ function remember(text: string) {
|
||||
save(HISTORY_KEY, history);
|
||||
}
|
||||
|
||||
/** Prompts sent from the project's other windows join this window's history. */
|
||||
export function trackPromptHistory(): () => void {
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === HISTORY_KEY) useAgents.setState({ history: load<string[]>(HISTORY_KEY, []) });
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => window.removeEventListener("storage", onStorage);
|
||||
}
|
||||
|
||||
/** The `!` commands running per task, so Stop ends them. */
|
||||
const shellRuns = new Map<string, Set<RequestId>>();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { confirm, showError, confirmChecked } from "@/workbench/messages";
|
||||
@@ -396,6 +397,9 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
|
||||
...(!multiple
|
||||
? ([
|
||||
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
|
||||
...(!auxiliaryWindow()
|
||||
? ([{ kind: "action", action: "agents.moveToNewWindow", arg: task.id }] satisfies MenuItem[])
|
||||
: []),
|
||||
...(hasTaskTerminal(task, projectRoot)
|
||||
? ([
|
||||
{ kind: "action", action: "terminal.openAt", label: "Terminal", icon: "terminal", arg: task.cwd },
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/** A task has one interactive conversation view, even when that view lives in another window. */
|
||||
import type { ComposerDraft } from "./composerModel";
|
||||
|
||||
type Route = (task: string | null, prompt?: string) => boolean;
|
||||
type Drafts = {
|
||||
read(task: string): ComposerDraft | undefined;
|
||||
update(task: string, patch: Partial<ComposerDraft>): boolean;
|
||||
};
|
||||
let route: Route | undefined;
|
||||
let focused: ((task: string) => boolean) | undefined;
|
||||
let drafts: Drafts | undefined;
|
||||
|
||||
export function installTaskWindowRouting(
|
||||
open: Route,
|
||||
isFocused?: (task: string) => boolean,
|
||||
composers?: Drafts,
|
||||
): () => void {
|
||||
route = open;
|
||||
focused = isFocused;
|
||||
drafts = composers;
|
||||
return () => {
|
||||
if (route === open) {
|
||||
route = undefined;
|
||||
focused = undefined;
|
||||
drafts = undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const taskWindowFocused = (task: string): boolean => focused?.(task) ?? false;
|
||||
|
||||
/** Whether another window shows `task` (New Task when null) instead of this one. */
|
||||
export const routeToWindow: Route = (task, prompt) => route?.(task, prompt) ?? false;
|
||||
export const taskWindowDraft = (task: string) => drafts?.read(task);
|
||||
export const updateTaskWindowDraft = (task: string, patch: Partial<ComposerDraft>) =>
|
||||
drafts?.update(task, patch) ?? false;
|
||||
@@ -0,0 +1,396 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { editorService, type EditorInput, type EditorService } from "@/workbench/contributions";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import {
|
||||
activateTaskWindows,
|
||||
moveTaskToWindow,
|
||||
prepareTaskWindowInput,
|
||||
TASK_WINDOW,
|
||||
type TaskWindowMessage,
|
||||
} from "./taskWindows";
|
||||
import { routeToWindow, taskWindowDraft, taskWindowFocused, updateTaskWindowDraft } from "./taskWindowRouting";
|
||||
|
||||
const CHILD = "editor-main-3";
|
||||
const backend = vi.hoisted(() => ({
|
||||
label: "main",
|
||||
serviceOverride: undefined as EditorService | undefined,
|
||||
subscribers: new Set<() => void>(),
|
||||
receive: undefined as ((event: { payload: unknown }) => void) | undefined,
|
||||
destroyed: undefined as (() => void) | undefined,
|
||||
focusChanged: undefined as ((event: { payload: boolean }) => void) | undefined,
|
||||
activeInput: undefined as ((input: EditorInput) => void) | undefined,
|
||||
draft: { text: "Unsent draft", files: [{ path: "/project/a.ts", rel: "a.ts" }], images: [] },
|
||||
state: {
|
||||
loaded: true,
|
||||
error: null as string | null,
|
||||
entries: new Map<string, unknown[]>([["running-task", []]]),
|
||||
entryLoads: new Map<string, { error: string | null }>(),
|
||||
composers: new Map(),
|
||||
tasks: new Map([["running-task", { status: "running", title: "Fix the build" }]]),
|
||||
docked: null as string | null,
|
||||
unread: new Set<string>(),
|
||||
},
|
||||
emit: vi.fn(async () => {}),
|
||||
openInWindow: vi.fn(async (_input: EditorInput) => "editor-main-3"),
|
||||
openInput: vi.fn(async (_input: EditorInput, _options?: unknown) => {}),
|
||||
openFile: vi.fn(async (_path: string, _options?: unknown) => {}),
|
||||
unsubscribe: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
focus: vi.fn(async () => {}),
|
||||
closeInput: vi.fn(async () => true),
|
||||
openTask: vi.fn(),
|
||||
openHome: vi.fn(),
|
||||
updateComposer: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
loadEntries: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
TauriEvent: { WINDOW_DESTROYED: "destroyed" },
|
||||
emitTo: backend.emit,
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/window", () => ({
|
||||
getCurrentWindow: () => ({
|
||||
label: backend.label,
|
||||
listen: async (_event: string, receive: typeof backend.receive) => {
|
||||
backend.receive = receive;
|
||||
return () => {
|
||||
backend.receive = undefined;
|
||||
};
|
||||
},
|
||||
}),
|
||||
getAllWindows: async () => [{ label: "main" }, { label: "settings-main" }, { label: "editor-main-3" }],
|
||||
Window: {
|
||||
getByLabel: async () => ({
|
||||
unminimize: async () => {},
|
||||
show: async () => {},
|
||||
setFocus: backend.focus,
|
||||
isFocused: async () => false,
|
||||
once: async (_event: string, destroyed: () => void) => {
|
||||
backend.destroyed = destroyed;
|
||||
},
|
||||
onFocusChanged: async (changed: typeof backend.focusChanged) => {
|
||||
backend.focusChanged = changed;
|
||||
return async () => {};
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
isTauri: () => true,
|
||||
call: async (result: Promise<{ data: unknown }>) => (await result).data,
|
||||
commands: { agentUnsubscribe: backend.unsubscribe },
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
editorService: () =>
|
||||
backend.serviceOverride ?? {
|
||||
openFile: backend.openFile,
|
||||
openInput: backend.openInput,
|
||||
closeInput: backend.closeInput,
|
||||
openInWindow: backend.openInWindow,
|
||||
onActiveInputChange: (listener: typeof backend.activeInput) => {
|
||||
backend.activeInput = listener;
|
||||
return () => {
|
||||
backend.activeInput = undefined;
|
||||
};
|
||||
},
|
||||
},
|
||||
provideEditorService: (service: EditorService) => {
|
||||
backend.serviceOverride = service;
|
||||
},
|
||||
provideToolWindowService: vi.fn(),
|
||||
notifications: () => ({ notify: backend.notify }),
|
||||
}));
|
||||
vi.mock("./store", () => ({
|
||||
composerDraft: () => backend.draft,
|
||||
updateComposer: backend.updateComposer,
|
||||
loadEntries: backend.loadEntries,
|
||||
openTask: backend.openTask,
|
||||
openHome: backend.openHome,
|
||||
useAgents: {
|
||||
subscribe: (fn: () => void) => {
|
||||
backend.subscribers.add(fn);
|
||||
return () => backend.subscribers.delete(fn);
|
||||
},
|
||||
getState: () => backend.state,
|
||||
setState: (patch: Partial<typeof backend.state>) => Object.assign(backend.state, patch),
|
||||
},
|
||||
}));
|
||||
|
||||
let stop: () => void;
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
backend.label = "main";
|
||||
backend.serviceOverride = undefined;
|
||||
backend.subscribers.clear();
|
||||
backend.state.loaded = true;
|
||||
backend.state.error = null;
|
||||
backend.state.entries = new Map([["running-task", []]]);
|
||||
backend.state.entryLoads = new Map();
|
||||
backend.state.docked = null;
|
||||
backend.state.unread = new Set();
|
||||
backend.destroyed = undefined;
|
||||
backend.focusChanged = undefined;
|
||||
stop = activateTaskWindows();
|
||||
await vi.waitFor(() => expect(backend.receive).toBeDefined());
|
||||
});
|
||||
afterEach(() => {
|
||||
stop();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const receive = (message: TaskWindowMessage) => backend.receive?.({ payload: message });
|
||||
|
||||
async function detach() {
|
||||
expect(await moveTaskToWindow("running-task")).toBe(true);
|
||||
await vi.waitFor(() => expect(backend.focusChanged).toBeDefined());
|
||||
}
|
||||
|
||||
describe("moving a conversation to a lightweight editor window", () => {
|
||||
it("opens the tab there with the unsent draft, then closes it here", async () => {
|
||||
backend.state.docked = "running-task";
|
||||
await detach();
|
||||
expect(backend.openInWindow).toHaveBeenCalledWith({
|
||||
kind: "agent-session",
|
||||
key: "agent:running-task",
|
||||
data: { task: "running-task", title: "Fix the build" },
|
||||
});
|
||||
expect(backend.closeInput).toHaveBeenCalledWith("agent:running-task");
|
||||
expect(backend.state.docked).toBeNull();
|
||||
expect(backend.state.tasks.has("running-task")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the conversation here when the window cannot open", async () => {
|
||||
backend.openInWindow.mockRejectedValueOnce(new Error("Timed out opening the editor window"));
|
||||
expect(await moveTaskToWindow("running-task")).toBe(false);
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
expect(backend.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ body: "Timed out opening the editor window" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("focuses the window instead of opening a second view", async () => {
|
||||
await detach();
|
||||
expect(routeToWindow("running-task")).toBe(true);
|
||||
await vi.waitFor(() => expect(backend.focus).toHaveBeenCalled());
|
||||
expect(await moveTaskToWindow("running-task")).toBe(true);
|
||||
expect(backend.openInWindow).toHaveBeenCalledOnce();
|
||||
expect(routeToWindow("another-task")).toBe(false);
|
||||
expect(routeToWindow(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("closes a tab of the conversation that Back/Forward reopened here", async () => {
|
||||
await detach();
|
||||
backend.closeInput.mockClear();
|
||||
backend.activeInput?.({ kind: "agent-session", key: "agent:running-task", data: { task: "running-task" } });
|
||||
expect(backend.closeInput).toHaveBeenCalledWith("agent:running-task");
|
||||
});
|
||||
|
||||
it("brings the conversation back with what was typed there when the window closes", async () => {
|
||||
await detach();
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Typed over there" } });
|
||||
backend.destroyed?.();
|
||||
expect(backend.updateComposer).toHaveBeenCalledWith("running-task", { ...backend.draft, text: "Typed over there" });
|
||||
expect(backend.openTask).toHaveBeenCalledWith("running-task");
|
||||
expect(backend.unsubscribe).toHaveBeenCalledWith(CHILD);
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
});
|
||||
|
||||
it("brings the conversation back when only its tab closes there", async () => {
|
||||
await detach();
|
||||
receive({ type: "closed", task: "running-task", label: "editor-main-9" });
|
||||
expect(backend.openTask).not.toHaveBeenCalled();
|
||||
receive({ type: "closed", task: "running-task", label: CHILD });
|
||||
expect(backend.openTask).toHaveBeenCalledWith("running-task");
|
||||
expect(backend.unsubscribe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("counts a conversation in a focused window as read", async () => {
|
||||
await detach();
|
||||
backend.state.unread.add("running-task");
|
||||
backend.focusChanged?.({ payload: true });
|
||||
expect(taskWindowFocused("running-task")).toBe(true);
|
||||
expect(backend.state.unread.has("running-task")).toBe(false);
|
||||
backend.focusChanged?.({ payload: false });
|
||||
expect(taskWindowFocused("running-task")).toBe(false);
|
||||
});
|
||||
|
||||
it("finds its windows again after a reload", async () => {
|
||||
expect(backend.emit).toHaveBeenCalledWith(CHILD, TASK_WINDOW, { type: "sync" });
|
||||
expect(backend.emit).toHaveBeenCalledOnce();
|
||||
receive({ type: "draft", task: "running-task", label: "editor-project-2-1", draft: backend.draft });
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: backend.draft });
|
||||
expect(routeToWindow("running-task")).toBe(true);
|
||||
expect(backend.closeInput).toHaveBeenCalledWith("agent:running-task");
|
||||
expect(backend.openInWindow).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows what a lightweight window asks for", () => {
|
||||
receive({ type: "open", task: "another-task" });
|
||||
expect(backend.openTask).toHaveBeenCalledWith("another-task");
|
||||
receive({ type: "open", task: null, prompt: "Review this" });
|
||||
expect(backend.openHome).toHaveBeenCalledWith("Review this");
|
||||
});
|
||||
|
||||
it("returns the latest mirrored draft to a reloading child", async () => {
|
||||
await detach();
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Latest draft" } });
|
||||
receive({ type: "requestDraft", task: "running-task", label: CHILD });
|
||||
expect(backend.emit).toHaveBeenLastCalledWith(CHILD, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task: "running-task",
|
||||
draft: { ...backend.draft, text: "Latest draft" },
|
||||
});
|
||||
});
|
||||
|
||||
it("routes edits made in the project to the latest draft in its child", async () => {
|
||||
await detach();
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Typed there" } });
|
||||
expect(taskWindowDraft("running-task")?.text).toBe("Typed there");
|
||||
expect(updateTaskWindowDraft("running-task", { text: "Typed there @a.ts" })).toBe(true);
|
||||
expect(backend.emit).toHaveBeenLastCalledWith(CHILD, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task: "running-task",
|
||||
draft: { ...backend.draft, text: "Typed there @a.ts" },
|
||||
});
|
||||
expect(updateTaskWindowDraft("another-task", { text: "Local draft" })).toBe(false);
|
||||
});
|
||||
|
||||
it("does not hide the original view before the child reports success", async () => {
|
||||
let finish!: (label: string) => void;
|
||||
backend.openInWindow.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const moving = moveTaskToWindow("running-task");
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Already typed there" } });
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
finish(CHILD);
|
||||
expect(await moving).toBe(true);
|
||||
await vi.waitFor(() => expect(backend.destroyed).toBeDefined());
|
||||
backend.destroyed?.();
|
||||
expect(backend.updateComposer).toHaveBeenCalledWith("running-task", {
|
||||
...backend.draft,
|
||||
text: "Already typed there",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores late draft events from a window that failed to open", async () => {
|
||||
backend.openInWindow.mockRejectedValueOnce(new Error("Cannot load task"));
|
||||
expect(await moveTaskToWindow("running-task")).toBe(false);
|
||||
receive({ type: "draft", task: "running-task", label: "editor-main-99", draft: backend.draft });
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("preparing the child's conversation", () => {
|
||||
const input: EditorInput = {
|
||||
kind: "agent-session",
|
||||
key: "agent:running-task",
|
||||
data: { task: "running-task", draft: { text: "Old launch draft" } },
|
||||
};
|
||||
async function child() {
|
||||
stop();
|
||||
await Promise.resolve();
|
||||
backend.label = CHILD;
|
||||
}
|
||||
async function reply() {
|
||||
await vi.waitFor(() =>
|
||||
expect(backend.emit).toHaveBeenCalledWith("main", TASK_WINDOW, {
|
||||
type: "requestDraft",
|
||||
task: "running-task",
|
||||
label: CHILD,
|
||||
}),
|
||||
);
|
||||
receive({ type: "draftSnapshot", task: "running-task", draft: { ...backend.draft, text: "Latest draft" } });
|
||||
}
|
||||
|
||||
it("waits for the task and uses the current draft instead of launch data", async () => {
|
||||
await child();
|
||||
backend.state.loaded = false;
|
||||
backend.emit.mockClear();
|
||||
const pending = prepareTaskWindowInput(input);
|
||||
expect(backend.emit).not.toHaveBeenCalled();
|
||||
backend.state.loaded = true;
|
||||
backend.subscribers.forEach((fn) => fn());
|
||||
await reply();
|
||||
expect(await pending).toEqual({
|
||||
...input,
|
||||
data: { task: "running-task", draft: { ...backend.draft, text: "Latest draft" } },
|
||||
});
|
||||
expect(backend.subscribers.size).toBe(0);
|
||||
});
|
||||
|
||||
it("routes files, diffs and workbench actions to the project while keeping its conversation here", async () => {
|
||||
await child();
|
||||
stop = activateTaskWindows();
|
||||
backend.activeInput?.(input);
|
||||
backend.emit.mockClear();
|
||||
await editorService().openFile("/project/a.ts", { focus: true });
|
||||
expect(backend.emit).toHaveBeenLastCalledWith("main", TASK_WINDOW, {
|
||||
type: "openFile",
|
||||
path: "/project/a.ts",
|
||||
options: { focus: true },
|
||||
});
|
||||
const diff = { kind: "diff", key: "diff:one" };
|
||||
await editorService().openInput(diff);
|
||||
expect(backend.emit).toHaveBeenLastCalledWith("main", TASK_WINDOW, {
|
||||
type: "openInput",
|
||||
input: diff,
|
||||
options: undefined,
|
||||
});
|
||||
await editorService().openInput(input);
|
||||
expect(backend.openInput).toHaveBeenCalledWith(input, undefined);
|
||||
await executeAction("file.settings", "agents");
|
||||
expect(backend.emit).toHaveBeenLastCalledWith("main", TASK_WINDOW, {
|
||||
type: "action",
|
||||
action: "file.settings",
|
||||
arg: "agents",
|
||||
});
|
||||
});
|
||||
|
||||
it("applies context appended in the project to the child composer", async () => {
|
||||
await child();
|
||||
stop = activateTaskWindows();
|
||||
backend.activeInput?.(input);
|
||||
backend.emit.mockClear();
|
||||
const draft = { ...backend.draft, text: "Typed in the child @a.ts" };
|
||||
receive({ type: "draftSnapshot", task: "running-task", draft });
|
||||
expect(backend.updateComposer).toHaveBeenCalledWith("running-task", draft);
|
||||
expect(backend.emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not complete the handoff when connecting fails", async () => {
|
||||
await child();
|
||||
backend.state.error = "Connection failed";
|
||||
backend.emit.mockClear();
|
||||
await expect(prepareTaskWindowInput(input)).rejects.toThrow("Connection failed");
|
||||
expect(backend.emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("waits for conversation entries and rejects their loading error", async () => {
|
||||
await child();
|
||||
backend.state.entries.clear();
|
||||
const pending = prepareTaskWindowInput(input);
|
||||
const rejected = expect(pending).rejects.toThrow("Cannot read conversation");
|
||||
expect(backend.loadEntries).toHaveBeenCalledWith("running-task");
|
||||
backend.state.entryLoads.set("running-task", { error: "Cannot read conversation" });
|
||||
backend.subscribers.forEach((fn) => fn());
|
||||
await rejected;
|
||||
});
|
||||
|
||||
it("times out without hiding the parent or retaining its store listener", async () => {
|
||||
await child();
|
||||
vi.useFakeTimers();
|
||||
backend.state.loaded = false;
|
||||
const rejected = expect(prepareTaskWindowInput(input)).rejects.toThrow("Loading the conversation timed out");
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
await rejected;
|
||||
expect(backend.subscribers.size).toBe(0);
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,390 @@
|
||||
/**
|
||||
* A conversation moved to a lightweight editor window. Only the view moves: the task and its
|
||||
* agent process stay in the project's backend, and the project window keeps the task list, the
|
||||
* unread marks, the notifications and a copy of the unsent draft.
|
||||
*/
|
||||
import { emitTo, TauriEvent, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { getAllWindows, getCurrentWindow, Window } from "@tauri-apps/api/window";
|
||||
import { auxiliaryWindow, windowLabel } from "@/platform/auxWindow";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import {
|
||||
editorService,
|
||||
notifications,
|
||||
provideEditorService,
|
||||
provideToolWindowService,
|
||||
toolWindowService,
|
||||
type EditorInput,
|
||||
type OpenOptions,
|
||||
} from "@/workbench/contributions";
|
||||
import type { ComposerDraft } from "./composerModel";
|
||||
import { SESSION_KIND, sessionKey } from "./model";
|
||||
import { composerDraft, loadEntries, openHome, openTask, updateComposer, useAgents } from "./store";
|
||||
import { installTaskWindowRouting } from "./taskWindowRouting";
|
||||
|
||||
export const TASK_WINDOW = "openidea://agents/window";
|
||||
|
||||
export type TaskWindowMessage =
|
||||
| { type: "requestDraft"; task: string; label: string }
|
||||
| { type: "draftSnapshot"; task: string; draft: ComposerDraft }
|
||||
| { type: "openFile"; path: string; options?: OpenOptions }
|
||||
| { type: "openInput"; input: EditorInput; options?: OpenOptions }
|
||||
| { type: "toolWindow"; id: string }
|
||||
| { type: "action"; action: string; arg?: unknown }
|
||||
/** Window `label` shows `task`; `draft` is what changed in its composer. */
|
||||
| { type: "draft"; task: string; label: string; draft: Partial<ComposerDraft> }
|
||||
/** Window `label` closed its tab of `task`. */
|
||||
| { type: "closed"; task: string; label: string }
|
||||
/** A lightweight window asks the project window to show `task`, or New Task. */
|
||||
| { type: "open"; task: string | null; prompt?: string }
|
||||
/** A project window that lost track of its windows (it reloaded) asks them to report again. */
|
||||
| { type: "sync" };
|
||||
|
||||
type TaskData = { task: string; title?: string; draft?: ComposerDraft };
|
||||
const taskInput = (data: TaskData): EditorInput => ({ kind: SESSION_KIND, key: sessionKey(data.task), data });
|
||||
const taskOf = (input: EditorInput | null) => (input?.kind === SESSION_KIND ? (input.data as TaskData).task : null);
|
||||
|
||||
type Detached = { label: string; draft: ComposerDraft; focused: boolean; stop?: UnlistenFn };
|
||||
/** Project window: the conversations shown in its lightweight windows. */
|
||||
const detached = new Map<string, Detached>();
|
||||
const opening = new Map<string, ComposerDraft>();
|
||||
/** Lightweight window: its tab of this task closed. */
|
||||
let tabClosed: ((task: string) => void) | undefined;
|
||||
export const taskTabClosed = (task: string) => tabClosed?.(task);
|
||||
|
||||
/** A reload uses the project's current draft, not the draft in the original launch. */
|
||||
export async function prepareTaskWindowInput(input: EditorInput): Promise<EditorInput> {
|
||||
const task = taskOf(input);
|
||||
const aux = auxiliaryWindow();
|
||||
if (!task || !aux) return input;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let loading = false;
|
||||
const finish = (error?: unknown) => {
|
||||
clearTimeout(timer);
|
||||
stop();
|
||||
if (error !== undefined) reject(error);
|
||||
else resolve();
|
||||
};
|
||||
const check = () => {
|
||||
const state = useAgents.getState();
|
||||
if (!state.loaded) return;
|
||||
const error = state.error || state.entryLoads.get(task)?.error;
|
||||
if (error) return finish(new Error(error));
|
||||
if (!state.tasks.has(task)) return finish(new Error(tx("Could not open the editor window")));
|
||||
if (state.entries.has(task)) return finish();
|
||||
if (!loading) {
|
||||
loading = true;
|
||||
void loadEntries(task).catch(finish);
|
||||
}
|
||||
};
|
||||
const stop = useAgents.subscribe(check);
|
||||
const timer = setTimeout(() => finish(new Error(tx("Loading the conversation timed out. Try again."))), 20_000);
|
||||
check();
|
||||
});
|
||||
const self = getCurrentWindow();
|
||||
let receive!: (draft: ComposerDraft) => void;
|
||||
const snapshot = new Promise<ComposerDraft>((resolve) => {
|
||||
receive = resolve;
|
||||
});
|
||||
const stop = await self.listen<TaskWindowMessage>(TASK_WINDOW, ({ payload }) => {
|
||||
if (payload.type === "draftSnapshot" && payload.task === task) receive(payload.draft);
|
||||
});
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const draft = await Promise.race([
|
||||
emitTo(aux.parent, TASK_WINDOW, {
|
||||
type: "requestDraft",
|
||||
task,
|
||||
label: self.label,
|
||||
} satisfies TaskWindowMessage).then(() => snapshot),
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(tx("Timed out opening the editor window"))), 5000);
|
||||
}),
|
||||
]);
|
||||
return { ...input, data: { ...(input.data as TaskData), draft } };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
stop();
|
||||
}
|
||||
}
|
||||
|
||||
async function focusWindow(label: string): Promise<void> {
|
||||
const window = await Window.getByLabel(label);
|
||||
if (!window) return;
|
||||
await window.unminimize();
|
||||
await window.show();
|
||||
await window.setFocus();
|
||||
}
|
||||
|
||||
function markRead(task: string) {
|
||||
const unread = new Set(useAgents.getState().unread);
|
||||
if (unread.delete(task)) useAgents.setState({ unread });
|
||||
}
|
||||
|
||||
async function hide(task: string) {
|
||||
if (useAgents.getState().docked === task) useAgents.setState({ docked: null });
|
||||
await editorService().closeInput?.(sessionKey(task));
|
||||
}
|
||||
|
||||
/** The conversation comes back with what was typed in its window. */
|
||||
function restore(task: string, entry: Detached) {
|
||||
if (detached.get(task) !== entry) return;
|
||||
detached.delete(task);
|
||||
void entry.stop?.();
|
||||
if (!useAgents.getState().tasks.has(task)) return;
|
||||
updateComposer(task, entry.draft);
|
||||
openTask(task);
|
||||
void focusWindow(getCurrentWindow().label);
|
||||
}
|
||||
|
||||
async function watch(task: string, entry: Detached) {
|
||||
const window = await Window.getByLabel(entry.label);
|
||||
if (!window) return restore(task, entry);
|
||||
// Not undone by `restore`: a window that closed the tab still receives agent events until it is gone.
|
||||
void window.once(TauriEvent.WINDOW_DESTROYED, () => {
|
||||
void call(commands.agentUnsubscribe(entry.label)).catch(() => {});
|
||||
restore(task, entry);
|
||||
});
|
||||
const focus = (focused: boolean) => {
|
||||
entry.focused = focused;
|
||||
if (focused) {
|
||||
markRead(task);
|
||||
useAgents.setState({ lastComposer: task });
|
||||
}
|
||||
};
|
||||
const stop = await window.onFocusChanged(({ payload }) => focus(payload));
|
||||
if (detached.get(task) !== entry) return void stop();
|
||||
entry.stop = stop;
|
||||
focus(await window.isFocused());
|
||||
}
|
||||
|
||||
function adopt(task: string, label: string, draft: Partial<ComposerDraft>) {
|
||||
let entry = detached.get(task);
|
||||
if (entry?.label !== label) {
|
||||
void entry?.stop?.();
|
||||
entry = { label, draft: composerDraft(task), focused: false };
|
||||
detached.set(task, entry);
|
||||
void watch(task, entry);
|
||||
void hide(task);
|
||||
}
|
||||
entry.draft = { ...entry.draft, ...draft };
|
||||
}
|
||||
|
||||
function activateProjectWindow(): () => void {
|
||||
const self = getCurrentWindow();
|
||||
const recovering = new Set<string>();
|
||||
const stops = [
|
||||
installTaskWindowRouting(
|
||||
(task) => {
|
||||
const entry = task ? detached.get(task) : undefined;
|
||||
if (entry) void focusWindow(entry.label);
|
||||
return !!entry;
|
||||
},
|
||||
(task) => detached.get(task)?.focused ?? false,
|
||||
{
|
||||
read: (task) => detached.get(task)?.draft,
|
||||
update: (task, patch) => {
|
||||
const entry = detached.get(task);
|
||||
if (!entry) return false;
|
||||
entry.draft = { ...entry.draft, ...patch };
|
||||
void emitTo(entry.label, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task,
|
||||
draft: entry.draft,
|
||||
} satisfies TaskWindowMessage).catch((error) => console.warn("cannot update conversation draft", error));
|
||||
return true;
|
||||
},
|
||||
},
|
||||
),
|
||||
// Back/Forward and a restored layout open tabs without going through `openTask`.
|
||||
editorService().onActiveInputChange?.((input) => {
|
||||
const task = taskOf(input);
|
||||
const entry = task ? detached.get(task) : undefined;
|
||||
if (!task || !entry) return;
|
||||
void hide(task);
|
||||
void focusWindow(entry.label);
|
||||
}),
|
||||
];
|
||||
const listening = self.listen<TaskWindowMessage>(TASK_WINDOW, ({ payload: message }) => {
|
||||
if (message.type === "requestDraft") {
|
||||
const aux = auxiliaryWindow(message.label);
|
||||
const entry = detached.get(message.task);
|
||||
if (aux?.kind === "editor" && aux.parent === self.label && (!entry || entry.label === message.label))
|
||||
void emitTo(message.label, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task: message.task,
|
||||
draft: entry?.draft ?? composerDraft(message.task),
|
||||
} satisfies TaskWindowMessage).catch((error) => console.warn("cannot restore conversation draft", error));
|
||||
} else if (message.type === "draft") {
|
||||
if (auxiliaryWindow(message.label)?.parent !== self.label) return;
|
||||
const pending = opening.get(message.task);
|
||||
if (pending) opening.set(message.task, { ...pending, ...message.draft });
|
||||
else if (detached.get(message.task)?.label === message.label || recovering.has(message.label))
|
||||
adopt(message.task, message.label, message.draft);
|
||||
} else if (message.type === "closed") {
|
||||
const entry = detached.get(message.task);
|
||||
if (entry?.label === message.label) restore(message.task, entry);
|
||||
} else if (message.type === "open") {
|
||||
if (message.task) openTask(message.task);
|
||||
else openHome(message.prompt);
|
||||
void focusWindow(self.label);
|
||||
} else if (message.type === "openFile" || message.type === "openInput") {
|
||||
const editors = editorService();
|
||||
const opened =
|
||||
message.type === "openFile"
|
||||
? editors.openFile(message.path, message.options)
|
||||
: editors.openInput(message.input, message.options);
|
||||
void opened.then(() => focusWindow(self.label)).catch(console.error);
|
||||
} else if (message.type === "toolWindow") {
|
||||
toolWindowService().show(message.id, true);
|
||||
void focusWindow(self.label);
|
||||
} else if (message.type === "action") {
|
||||
void focusWindow(self.label)
|
||||
.then(() => executeAction(message.action, message.arg))
|
||||
.catch(console.error);
|
||||
}
|
||||
});
|
||||
void listening
|
||||
.then(async () => {
|
||||
for (const { label } of await getAllWindows()) {
|
||||
const aux = auxiliaryWindow(label);
|
||||
if (aux?.kind === "editor" && aux.parent === self.label) {
|
||||
recovering.add(label);
|
||||
await emitTo(label, TASK_WINDOW, { type: "sync" } satisfies TaskWindowMessage);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((error) => console.warn("cannot look for conversation windows", error));
|
||||
return () => {
|
||||
stops.forEach((stop) => stop?.());
|
||||
void listening.then((stop) => stop()).catch(() => {});
|
||||
for (const entry of detached.values()) void entry.stop?.();
|
||||
detached.clear();
|
||||
};
|
||||
}
|
||||
|
||||
function activateLightweightWindow(parent: string): () => void {
|
||||
const self = getCurrentWindow();
|
||||
/** The conversations shown here, with what the project window last heard of their composers. */
|
||||
const shown = new Map<string, Partial<ComposerDraft>>();
|
||||
const send = (message: TaskWindowMessage) =>
|
||||
void emitTo(parent, TASK_WINDOW, message).catch((error) => console.warn("cannot reach the project window", error));
|
||||
const editors = editorService();
|
||||
// A conversation keeps its view here; its file links and workbench tools open in the project.
|
||||
provideEditorService({
|
||||
...editors,
|
||||
openFile: (path, options) =>
|
||||
shown.size
|
||||
? emitTo(parent, TASK_WINDOW, { type: "openFile", path, options } satisfies TaskWindowMessage)
|
||||
: editors.openFile(path, options),
|
||||
openInput: (input, options) =>
|
||||
shown.size && input.kind !== SESSION_KIND
|
||||
? emitTo(parent, TASK_WINDOW, { type: "openInput", input, options } satisfies TaskWindowMessage)
|
||||
: editors.openInput(input, options),
|
||||
});
|
||||
provideToolWindowService({
|
||||
show: (id) => send({ type: "toolWindow", id }),
|
||||
toggle: (id) => send({ type: "toolWindow", id }),
|
||||
hide: () => {},
|
||||
isVisible: () => false,
|
||||
});
|
||||
const report = (task: string, all = false) => {
|
||||
const draft = composerDraft(task);
|
||||
const known = all ? {} : shown.get(task)!;
|
||||
// Images are base64: only what changed travels with each keystroke.
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(draft).filter(([field, value]) => value !== known[field as keyof ComposerDraft]),
|
||||
);
|
||||
shown.set(task, draft);
|
||||
if (all || Object.keys(changed).length) send({ type: "draft", task, label: self.label, draft: changed });
|
||||
};
|
||||
const show = (input: EditorInput | null) => {
|
||||
const task = taskOf(input);
|
||||
if (!task || shown.has(task)) return;
|
||||
const { draft } = input!.data as TaskData;
|
||||
// What was being typed in the project window moves along, once.
|
||||
if (draft && !useAgents.getState().composers.has(task)) updateComposer(task, draft);
|
||||
report(task, true);
|
||||
};
|
||||
tabClosed = (task) => {
|
||||
if (!shown.delete(task)) return;
|
||||
send({ type: "closed", task, label: self.label });
|
||||
// A window opened for the conversation has nothing left to show.
|
||||
setTimeout(() => {
|
||||
if (!editorService().openTabs?.().length) void self.close();
|
||||
});
|
||||
};
|
||||
const stops = [
|
||||
registerActions(
|
||||
[
|
||||
{ id: "terminal.openAt", title: "Open in Terminal" },
|
||||
{ id: "file.settings", title: "Settings…" },
|
||||
{ id: "navigate.selectInProjectView", title: "Select in Project View" },
|
||||
].map(({ id, title }) => ({
|
||||
id,
|
||||
title,
|
||||
hidden: true,
|
||||
enabled: () => shown.size > 0,
|
||||
run: ({ arg }) => send({ type: "action", action: id, arg }),
|
||||
})),
|
||||
),
|
||||
installTaskWindowRouting((task, prompt) => {
|
||||
if (task && shown.has(task)) void editorService().openInput(taskInput({ task }), { focus: true });
|
||||
else send({ type: "open", task, prompt });
|
||||
return true;
|
||||
}),
|
||||
editorService().onActiveInputChange?.(show),
|
||||
useAgents.subscribe((state, previous) => {
|
||||
if (state.composers !== previous.composers) for (const task of shown.keys()) report(task);
|
||||
}),
|
||||
];
|
||||
const listening = self.listen<TaskWindowMessage>(TASK_WINDOW, ({ payload: message }) => {
|
||||
if (message.type === "sync") for (const task of shown.keys()) report(task, true);
|
||||
else if (message.type === "draftSnapshot" && shown.has(message.task)) {
|
||||
// This snapshot came from the project (for example, Send to Agent): do not echo it back.
|
||||
shown.set(message.task, message.draft);
|
||||
updateComposer(message.task, message.draft);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
tabClosed = undefined;
|
||||
provideEditorService(editors);
|
||||
stops.forEach((stop) => stop?.());
|
||||
void listening.then((stop) => stop()).catch(() => {});
|
||||
};
|
||||
}
|
||||
|
||||
export function activateTaskWindows(): () => void {
|
||||
if (!isTauri() || !windowLabel()) return () => {};
|
||||
const aux = auxiliaryWindow();
|
||||
return aux ? activateLightweightWindow(aux.parent) : activateProjectWindow();
|
||||
}
|
||||
|
||||
/** Moves the conversation of `task` to a window of its own; false when it stayed here. */
|
||||
export async function moveTaskToWindow(task: string): Promise<boolean> {
|
||||
const open = editorService().openInWindow;
|
||||
if (!open || auxiliaryWindow() || opening.has(task) || !useAgents.getState().tasks.has(task)) return false;
|
||||
const existing = detached.get(task);
|
||||
if (existing) {
|
||||
await focusWindow(existing.label);
|
||||
return true;
|
||||
}
|
||||
const draft = composerDraft(task);
|
||||
opening.set(task, draft);
|
||||
try {
|
||||
const title = useAgents.getState().tasks.get(task)?.title;
|
||||
const label = await open(taskInput({ task, title }));
|
||||
adopt(task, label, opening.get(task) ?? draft);
|
||||
return true;
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Could not move conversation to a new window",
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
opening.delete(task);
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,12 @@ const KINDS: readonly AuxKind[] = ["settings", "comparison", "diff", "editor", "
|
||||
/** An auxiliary window reports to its parent whether it closed, and which documents it released. */
|
||||
export const AUX_CLOSED = "openidea://auxiliary/closed";
|
||||
|
||||
/** Lightweight editor window reports that it opened (or failed to open) the moved file. */
|
||||
/** Lightweight editor window reports that it opened (or failed to open) the moved file or tab. */
|
||||
export const EDITOR_READY = "openidea://editor/ready";
|
||||
|
||||
export interface EditorReadyResult {
|
||||
label: string;
|
||||
/** The launch's file, or the key of its tab. */
|
||||
path: string;
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
@@ -33,7 +34,8 @@ export interface AuxCloseResult {
|
||||
documents: number[];
|
||||
}
|
||||
|
||||
function currentLabel(): string {
|
||||
/** This window's label ("" outside the desktop app). */
|
||||
export function windowLabel(): string {
|
||||
if (!isTauri()) return "";
|
||||
try {
|
||||
return getCurrentWindow().label;
|
||||
@@ -43,7 +45,7 @@ function currentLabel(): string {
|
||||
}
|
||||
|
||||
/** The kind and parent of an auxiliary window, or null for a project window. */
|
||||
export function auxiliaryWindow(label = currentLabel()): { kind: AuxKind; parent: string } | null {
|
||||
export function auxiliaryWindow(label = windowLabel()): { kind: AuxKind; parent: string } | null {
|
||||
for (const kind of KINDS) {
|
||||
if (!label.startsWith(`${kind}-`)) continue;
|
||||
const rest = label.slice(kind.length + 1);
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
"Memory files": "Memory files",
|
||||
"MCP tools": "MCP tools",
|
||||
"Autocompact buffer": "Autocompact buffer",
|
||||
"Open in New Window": "Open in New Window",
|
||||
"Could not move conversation to a new window": "Could not move conversation to a new window",
|
||||
"Inspection details": "Inspection details",
|
||||
"Inspection actions": "Inspection actions",
|
||||
"Resize inspection panes": "Resize inspection panes",
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"Memory files": "记忆文件",
|
||||
"MCP tools": "MCP 工具",
|
||||
"Autocompact buffer": "自动压缩预留空间",
|
||||
"Could not move conversation to a new window": "无法将会话移到新窗口",
|
||||
"Inspection details": "检查详情",
|
||||
"Inspection actions": "检查操作",
|
||||
"Resize inspection panes": "调整检查窗格大小",
|
||||
|
||||
@@ -154,6 +154,13 @@ export interface EditorKindContribution {
|
||||
onClose?(input: EditorInput): void;
|
||||
/** The input that shows this tab where it is now when Back returns to it, e.g. a diff at its caret. */
|
||||
navigationInput?(input: EditorInput): EditorInput;
|
||||
/**
|
||||
* "Open in New Window" on its tabs: moves the tab to a lightweight window of this project
|
||||
* (`EditorService.openInWindow`) with whatever state it carries. False when it stayed here.
|
||||
*/
|
||||
openInWindow?(input: EditorInput): Promise<boolean>;
|
||||
/** Loads and validates a lightweight window's input before it reports a successful handoff. */
|
||||
prepareWindowInput?(input: EditorInput): Promise<EditorInput>;
|
||||
/** Any tab of this kind closed (`tabId` is the closed `Tab.id`, even when split siblings remain). */
|
||||
onTabClose?(tabId: string, input: EditorInput): void;
|
||||
/**
|
||||
@@ -690,6 +697,11 @@ export const EDITOR_TAB_MIME = "application/x-openidea-editor-tab";
|
||||
export interface EditorService {
|
||||
openFile(path: string, options?: OpenOptions): Promise<void>;
|
||||
openInput(input: EditorInput, options?: OpenOptions): Promise<void>;
|
||||
/**
|
||||
* Shows `input` in a lightweight window of this project instead (its kind must be registered
|
||||
* there, see `editorWindowBoot`); resolves to the window's label once it is shown.
|
||||
*/
|
||||
openInWindow?(input: EditorInput): Promise<string>;
|
||||
/** File › New File: an editable untitled buffer; Save asks for a path. */
|
||||
openUntitled?(options?: OpenOptions): Promise<void>;
|
||||
/** Path of the focused text editor, if any. */
|
||||
|
||||
Reference in New Issue
Block a user