diff --git a/src/editor/core/busyClose.test.ts b/src/editor/core/busyClose.test.ts new file mode 100644 index 000000000..37dd09314 --- /dev/null +++ b/src/editor/core/busyClose.test.ts @@ -0,0 +1,168 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions"; +import { t } from "@/platform/i18n"; +import { useProject } from "@/platform/project"; +import { confirm } from "@/workbench/messages"; +import type * as Messages from "@/workbench/messages"; +import { EditorController, useTabs } from "./controller"; +import { createMemoryBackend } from "./backend"; +import { initialTabsState } from "./model/tabs"; + +vi.mock("@/workbench/messages", async (original) => ({ + ...(await original()), + confirm: vi.fn(), +})); + +let controller: EditorController | null = null; +afterEach(() => { + controller?.stop(); + controller = null; + useTabs.setState(initialTabsState(), true); + useProject.setState({ project: null, settings: null }); + vi.mocked(confirm).mockReset(); +}); + +/** A kind whose tabs answer `isBusy`; the title is the input key. */ +const busyKind = (isBusy: EditorKindContribution["isBusy"]) => + registerEditorKind({ kind: "busy-probe", title: (i) => i.key, component: () => null, isBusy }); + +const start = () => { + controller = new EditorController(createMemoryBackend({})); + controller.start(); + return controller; +}; +const pane = () => useTabs.getState().panes[useTabs.getState().activePane]!; +const keys = () => pane().tabs.map((tab) => tab.input.key); +const question = (name: string) => ({ + title: t("editor.closeBusy.title", { name }), + message: t("editor.closeBusy.message", { name }), + ok: t("editor.closeBusy.terminate"), +}); + +describe("editor kinds' isBusy on close", () => { + it("asks before closing a busy tab and keeps it on Cancel", async () => { + const dispose = busyKind(() => true); + vi.mocked(confirm).mockResolvedValue(false); + const ctrl = start(); + try { + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:1" }); + expect(await ctrl.closeTab(pane().id, pane().tabs[0]!.id)).toBe(false); + expect(confirm).toHaveBeenCalledExactlyOnceWith(question("busy-probe:1")); + expect(keys()).toEqual(["busy-probe:1"]); + } finally { + dispose(); + } + }); + + it("closes the busy tab once terminating is confirmed", async () => { + const closed = vi.fn(); + const dispose = registerEditorKind({ + kind: "busy-probe", + title: (i) => i.key, + component: () => null, + isBusy: () => true, + onClose: closed, + }); + vi.mocked(confirm).mockResolvedValue(true); + const ctrl = start(); + const input = { kind: "busy-probe", key: "busy-probe:1" }; + try { + await ctrl.openInput(input); + expect(await ctrl.closeTab(pane().id, pane().tabs[0]!.id)).toBe(true); + expect(keys()).toEqual([]); + expect(closed).toHaveBeenCalledExactlyOnceWith(input); + } finally { + dispose(); + } + }); + + it("awaits an async answer, and closes a tab that is not busy without asking", async () => { + const dispose = busyKind(async (i) => i.key === "busy-probe:1"); + vi.mocked(confirm).mockResolvedValue(false); + const ctrl = start(); + try { + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:1" }); + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:2" }); + const idle = pane().tabs.find((tab) => tab.input.key === "busy-probe:2")!; + expect(await ctrl.closeTab(pane().id, idle.id)).toBe(true); + expect(confirm).not.toHaveBeenCalled(); + expect(await ctrl.closeTab(pane().id, pane().tabs[0]!.id)).toBe(false); + expect(confirm).toHaveBeenCalledExactlyOnceWith(question("busy-probe:1")); + } finally { + dispose(); + } + }); + + it("counts a failing isBusy as not busy, so the tab still closes", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const dispose = busyKind(() => { + throw new Error("probe failed"); + }); + const ctrl = start(); + try { + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:1" }); + expect(await ctrl.closeTab(pane().id, pane().tabs[0]!.id)).toBe(true); + expect(confirm).not.toHaveBeenCalled(); + } finally { + dispose(); + warn.mockRestore(); + } + }); + + it("asks only when the last tab of a busy input closes", async () => { + const dispose = busyKind(() => true); + vi.mocked(confirm).mockResolvedValue(true); + const ctrl = start(); + const input = { kind: "busy-probe", key: "busy-probe:1" }; + try { + await ctrl.openInput(input); + ctrl.split(useTabs.getState().activePane, "row"); + const panes = Object.values(useTabs.getState().panes); + // Another pane still shows the input: nothing ends, nothing to ask. + expect(await ctrl.closeTab(panes[0]!.id, panes[0]!.tabs[0]!.id)).toBe(true); + expect(confirm).not.toHaveBeenCalled(); + expect(await ctrl.closeInput(input.key)).toBe(true); + expect(confirm).toHaveBeenCalledExactlyOnceWith(question("busy-probe:1")); + } finally { + dispose(); + } + }); +}); + +describe("editor kinds' isBusy on tab-limit eviction", () => { + const limitOne = () => + useProject.setState({ settings: { editor: { tabs: { tabLimit: 1, closingPolicy: "lru" } } } as never }); + + it.each([ + ["a sync answer", (key: string) => key === "busy-probe:1"], + ["an async answer", (key: string) => Promise.resolve(key === "busy-probe:1")], + ])("skips a busy tab without asking (%s)", async (_name, busy) => { + const dispose = busyKind((i) => busy(i.key)); + const ctrl = start(); + limitOne(); + try { + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:1" }); + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:2" }); + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:3" }); + // The least recently used tab is the busy one: it stays, the idle one makes room instead. + expect(keys()).toEqual(["busy-probe:1", "busy-probe:3"]); + expect(confirm).not.toHaveBeenCalled(); + } finally { + dispose(); + } + }); + + it("evicts the least recently used tab when none is busy", async () => { + const dispose = busyKind(() => false); + const ctrl = start(); + limitOne(); + try { + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:1" }); + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:2" }); + await ctrl.openInput({ kind: "busy-probe", key: "busy-probe:3" }); + expect(keys()).toEqual(["busy-probe:3"]); + } finally { + dispose(); + } + }); +}); diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 7618fd6c1..4b0773e36 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -41,7 +41,7 @@ import { } from "@/workbench/contributions"; import { useDistractionFree } from "@/workbench/distractionFree"; import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store"; -import { ask } from "@/workbench/messages"; +import { ask, confirm } from "@/workbench/messages"; import { t } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; import { isRemoteWindow } from "@/platform/remote"; @@ -92,6 +92,7 @@ import { documentDirty, documentLifecycle, failures, + inputBusy, inputDirty, type CustomDocument, } from "./model/customDocuments"; @@ -1226,27 +1227,40 @@ export class EditorController implements SlotHost { } } + /** + * Tabs of kinds with an `isBusy` answer are never evicted (that would end a + * running process unasked): their answers are resolved first, so the sync + * and the async ones are protected alike. + */ private enforcePaneTabLimit(paneId: string, keep?: string, liveKeys?: ReadonlySet) { - const prefs = editorPrefs().tabs; - const protect = (tab: Tab) => - !!liveKeys?.has(tab.input.key) || inputDirty(tab.input, useContributions.getState().editorKinds) === true; - return this.removeGuarded( - (current) => - current.panes[paneId] - ? enforceTabLimit( - current, - paneId, - prefs.tabLimit, - prefs.closingPolicy, - (tab) => - inputDirty(tab.input, useContributions.getState().editorKinds) ?? - !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty), - keep ?? current.panes[paneId]?.active ?? undefined, - protect, - ) - : current, - { protect }, - ); + const kinds = useContributions.getState().editorKinds; + const busyCapable = (useTabs.getState().panes[paneId]?.tabs ?? []).filter((t) => kinds.get(t.input.kind)?.isBusy); + const evict = (busy: ReadonlySet) => { + const prefs = editorPrefs().tabs; + // A tab whose kind reports a running process is never evicted: that would end it unasked. + const protect = (tab: Tab) => + busy.has(tab.input.key) || inputDirty(tab.input, kinds) === true || !!liveKeys?.has(tab.input.key); + return this.removeGuarded( + (current) => + current.panes[paneId] + ? enforceTabLimit( + current, + paneId, + prefs.tabLimit, + prefs.closingPolicy, + (tab) => + inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty), + keep ?? current.panes[paneId]?.active ?? undefined, + protect, + ) + : current, + { protect }, + ); + }; + if (!busyCapable.length) return evict(new Set()); + return Promise.all( + busyCapable.map(async (tab) => ((await inputBusy(tab.input, kinds)) ? tab.input.key : null)), + ).then((keys) => evict(new Set(keys.filter((key): key is string => key !== null)))); } activate(paneId: string, tabId: string, focus = true) { @@ -1316,6 +1330,30 @@ export class EditorController implements SlotHost { }); } + /** + * Inputs about to lose their last tab whose kind reports them busy + * (`EditorKindContribution.isBusy`): asks before ending what runs in them, + * like closing a busy terminal session. Resolves false to keep the tabs. + */ + private async confirmBusyClose(removal: (s: TabsState) => TabsState): Promise { + const kinds = useContributions.getState().editorKinds; + const current = useTabs.getState(); + const remaining = openKeys(removal(current)); + const closing = new Map(); + for (const pane of Object.values(current.panes)) + for (const tab of pane.tabs) + if (!remaining.has(tab.input.key) && kinds.get(tab.input.kind)?.isBusy) closing.set(tab.input.key, tab.input); + const busy: string[] = []; + for (const input of closing.values()) if (await inputBusy(input, kinds)) busy.push(tabTitle(input, kinds)); + if (!busy.length) return true; + const name = busy.join(", "); + return confirm({ + title: t("editor.closeBusy.title", { name }), + message: t("editor.closeBusy.message", { name }), + ok: t("editor.closeBusy.terminate"), + }); + } + /** Close exactly the originally selected tabs, evaluating references after every await. */ private removeGuarded( select: (s: TabsState) => TabsState, @@ -1389,6 +1427,8 @@ export class EditorController implements SlotHost { } authorized.add(d.input.key); } + if (!(await this.confirmBusyClose(currentRemoval))) return false; + if (generation !== this.projectGeneration) return false; if (options.beforeRemove && !(await options.beforeRemove())) return false; // Commit only the original target ids against the latest tab state. if (generation !== this.projectGeneration) return false; diff --git a/src/editor/core/model/customDocuments.ts b/src/editor/core/model/customDocuments.ts index 4d6e09fb5..b82b1dd9b 100644 --- a/src/editor/core/model/customDocuments.ts +++ b/src/editor/core/model/customDocuments.ts @@ -52,6 +52,19 @@ export function inputDirty(input: EditorInput, kinds: Kinds): boolean | null { return lifecycle ? documentDirty({ input, lifecycle }) : null; } +/** + * Whether the input's editor kind reports it busy (`EditorKindContribution.isBusy`). + * A failing check counts as not busy, so a broken kind cannot make its tabs unclosable. + */ +export async function inputBusy(input: EditorInput, kinds: Kinds): Promise { + try { + return (await kinds.get(input.kind)?.isBusy?.(input)) === true; + } catch (e) { + console.warn(`editor input ${input.key}: isBusy failed`, e); + return false; + } +} + /** The rejection reasons of `results` (an AggregateError contributes each of its errors). */ export function failures(results: readonly PromiseSettledResult[]): unknown[] { return results.flatMap((r) => diff --git a/src/features/terminal/Cli.module.css b/src/features/terminal/Cli.module.css new file mode 100644 index 000000000..e96551324 --- /dev/null +++ b/src/features/terminal/Cli.module.css @@ -0,0 +1,115 @@ +.start { + flex: 1; + min-height: 0; + overflow: auto; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 10px; + padding: 24px; +} + +.startInner { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + max-width: 560px; +} + +.heading { + margin: 0; + font-size: 18px; + font-weight: 600; + color: var(--fg-strong); +} + +.command { + margin: 0; + padding: 8px 12px; + max-width: 100%; + overflow-wrap: anywhere; + font-family: var(--font-mono); + font-size: var(--fs-code); + color: var(--fg); + background: var(--bg-island); + border: 1px solid var(--border); + border-radius: var(--radius-small); +} + +.note { + margin: 0; + font-size: var(--fs-small); + color: var(--fg-subtle); + text-align: center; +} + +.cards { + display: flex; + flex-direction: column; + gap: 6px; + width: 100%; +} + +.card { + position: relative; + display: flex; + min-width: 0; +} + +.cardButton { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 2px; + padding: 8px 12px; + text-align: left; + background: var(--bg-island); + border: 1px solid var(--border); + border-radius: var(--radius-small); + cursor: pointer; +} + +.cardButton:hover { + border-color: var(--border-strong); +} + +.cardName { + color: var(--fg-strong); + font-size: var(--fs-small); + font-weight: 600; +} + +.cardCommand { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--font-mono); + font-size: var(--fs-code); + color: var(--fg); +} + +/* The remove affordance rides on the card's edge. */ +.cardRemove { + position: absolute; + top: 4px; + right: 4px; +} + +.form { + display: flex; + flex-direction: column; + gap: 8px; + width: 100%; +} + +.formActions { + display: flex; + gap: 8px; + justify-content: center; + margin-top: 4px; +} diff --git a/src/features/terminal/CliEditor.tsx b/src/features/terminal/CliEditor.tsx new file mode 100644 index 000000000..12b574880 --- /dev/null +++ b/src/features/terminal/CliEditor.tsx @@ -0,0 +1,66 @@ +/** + * Editor-area tab of one CLI (#2202): the session's xterm while it runs, else a + * Start screen — a tab restored with the project never runs its command on its + * own. The session lives in `cliSessions.ts`; this only attaches its host while + * the tab is the one shown. + */ +import { useLayoutEffect, useRef, type FocusEvent } from "react"; +import { useProject } from "@/platform/project"; +import { useEditorShown, type EditorInput } from "@/workbench/contributions"; +import { Button, EmptyState, T } from "@/ui"; +import { cliData, startTab, useClis } from "./cli"; +import { cliSession } from "./cliSessions"; +import styles from "./Cli.module.css"; +// The pane is the terminal tool window's own: same xterm layout, cursor and scrollbar. +import terminalStyles from "./Terminal.module.css"; + +export function CliEditor({ input }: { input: EditorInput }) { + const data = cliData(input); + const live = useClis((s) => !!s.sessions[input.key]); + const shown = useEditorShown(); + const project = useProject((s) => s.project); + const ref = useRef(null); + + // Hidden tabs stay unopened (xterm opened at 0×0 never takes keys); the session keeps running. + useLayoutEffect(() => { + const el = ref.current; + const session = cliSession(input.key); + if (!el || !session || !shown) return; + session.attach(el); + // The editor focuses the tab wrapper ([data-editor-focus]); hand focus on to xterm. + const wrapper = el.closest("[data-editor-focus]"); + const onFocus = () => session.focus(); + wrapper?.addEventListener("focus", onFocus); + return () => { + wrapper?.removeEventListener("focus", onFocus); + session.detach(el); + }; + }, [input.key, live, shown]); + + if (!data) return ; + if (!live) + return ( +
+
+

{data.name}

+ {data.command &&
{data.command}
} +

+ Starts in the project directory through your login shell. +

+ +
+
+ ); + return ( +
) => { + if (e.target === e.currentTarget) cliSession(input.key)?.focus(); + }} + /> + ); +} diff --git a/src/features/terminal/CliLauncher.tsx b/src/features/terminal/CliLauncher.tsx new file mode 100644 index 000000000..b697e87e4 --- /dev/null +++ b/src/features/terminal/CliLauncher.tsx @@ -0,0 +1,107 @@ +/** + * The New CLI tab (#2202): the saved CLIs as cards, one click starts one as an + * editor tab; "Add CLI…" saves a name + command for all projects, and a plain + * login shell opens the same way. The terminal tool window keeps its own tabs. + */ +import { useState, type ChangeEvent, type KeyboardEvent } from "react"; +import { Button, IconButton, Input, T } from "@/ui"; +import { launchCli, removeSavedCli, saveCli, useSavedClis } from "./cli"; +import styles from "./Cli.module.css"; + +export function CliLauncher() { + const saved = useSavedClis((s) => s.saved); + const [adding, setAdding] = useState(false); + const [name, setName] = useState(""); + const [command, setCommand] = useState(""); + + const canAdd = !!name.trim() && !!command.trim(); + const reset = () => { + setName(""); + setCommand(""); + setAdding(false); + }; + const add = () => { + if (!canAdd) return; + saveCli(name, command); + reset(); + }; + const onFormKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape") { + e.stopPropagation(); + reset(); + } + }; + + return ( +
+
+

+ New CLI +

+
+ {saved.map((s) => ( +
+ + removeSavedCli(s.id)} + /> +
+ ))} + {saved.length === 0 && ( +

+ No saved CLIs yet — add one, or open a plain shell. +

+ )} +
+ {adding ? ( +
+ ) => setName(e.target.value)} + onKeyDown={(e: KeyboardEvent) => { + if (e.key === "Enter") add(); + }} + /> + ) => setCommand(e.target.value)} + onKeyDown={(e: KeyboardEvent) => { + if (e.key === "Enter") add(); + }} + /> +
+ + +
+
+ ) : ( +
+ + +
+ )} +
+
+ ); +} diff --git a/src/features/terminal/TerminalView.tsx b/src/features/terminal/TerminalView.tsx index 56a5d90e8..cfd1bcd31 100644 --- a/src/features/terminal/TerminalView.tsx +++ b/src/features/terminal/TerminalView.tsx @@ -417,6 +417,7 @@ function GroupTabs({ group }: { group: string }) { const renameTarget = renaming && tabs.find((t) => t.id === renaming.id); const moreItems: MenuItem[] = [ { kind: "action", action: "terminal.new" }, + { kind: "action", action: "cli.new" }, { kind: "separator" }, { kind: "header", label: "New Predefined Session" }, ...shellItems(shells), diff --git a/src/features/terminal/cli.test.ts b/src/features/terminal/cli.test.ts new file mode 100644 index 000000000..896f60f1b --- /dev/null +++ b/src/features/terminal/cli.test.ts @@ -0,0 +1,131 @@ +/** + * CLI editor tabs (#2202): input kinds and data validation, the saved CLIs + * (global), and the launch / start flows through the terminal runtime. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + cliData, + cliInput, + decodeSavedClis, + launchCli, + openCliLauncher, + readSavedClis, + removeSavedCli, + saveCli, + startTab, + useSavedClis, + CLI_LAUNCHER_KEY, + type SavedCli, +} from "./cli"; + +const runtime = vi.hoisted(() => ({ + loaded: false, + startCli: vi.fn(), +})); +const editor = vi.hoisted(() => ({ + openInput: vi.fn(async (_input?: unknown, _options?: unknown) => undefined), + closeInput: vi.fn(async (_key?: unknown) => true), +})); + +vi.mock("./loader", () => ({ + loadTerminalRuntime: async () => runtime, + terminalRuntime: () => (runtime.loaded ? runtime : null), +})); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + editorService: () => editor, +})); + +import { useProject } from "@/platform/project"; + +const root = () => useProject.getState().project?.root ?? null; + +beforeEach(() => { + runtime.loaded = true; + useProject.setState({ project: { root: "/repo" } as never }); +}); +afterEach(() => { + useProject.setState({ project: null, settings: null }); + useSavedClis.setState({ saved: [] }); + localStorage.clear(); + vi.clearAllMocks(); +}); + +describe("CLI input data", () => { + it("validates untrusted session data", () => { + const input = cliInput("Claude Code", "claude --continue"); + expect(cliData(input)).toEqual({ name: "Claude Code", command: "claude --continue" }); + expect(cliData({ ...input, data: undefined })).toBeNull(); + expect(cliData({ ...input, data: { name: " ", command: "x" } })).toBeNull(); + expect(cliData({ ...input, data: { name: " A ", command: 3 } })).toEqual({ name: "A", command: "" }); + expect(cliData({ ...input, kind: "file", path: "/repo/a.ts" })).toBeNull(); + }); + + it("mints a fresh key per launch, so restored tabs are their own", () => { + const a = cliInput("A", "a"); + const b = cliInput("A", "a"); + expect(a.key).not.toBe(b.key); + expect(a.kind).toBe("cli"); + }); +}); + +describe("saved CLIs", () => { + it("decodes untrusted JSON: strings only, unique ids, capped", () => { + expect(decodeSavedClis(null)).toEqual([]); + expect(decodeSavedClis("x")).toEqual([]); + const good: SavedCli = { id: "a", name: " A ", command: " aider " }; + expect(decodeSavedClis([good, { id: "b", name: "B", command: "" }, { id: "a", name: "C", command: "c" }])).toEqual([ + { id: "a", name: "A", command: "aider" }, + ]); + const many = Array.from({ length: 40 }, (_, i) => ({ id: `id${i}`, name: `N${i}`, command: `c${i}` })); + expect(decodeSavedClis(many)).toHaveLength(32); + }); + + it("saves and removes for every project", () => { + saveCli("Claude Code", "claude"); + saveCli("Aider", "aider --model x"); + expect(useSavedClis.getState().saved.map((s) => s.name)).toEqual(["Claude Code", "Aider"]); + const again = readSavedClis(); + expect(again).toEqual(useSavedClis.getState().saved); + removeSavedCli(again[0]!.id); + expect(readSavedClis().map((s) => s.name)).toEqual(["Aider"]); + }); +}); + +describe("launching", () => { + it("starts the session in the project root and opens its tab", async () => { + await launchCli("Claude Code", "claude --continue"); + const input = editor.openInput.mock.calls[0]?.[0] as { kind: string; key: string; data: unknown }; + expect(input.kind).toBe("cli"); + expect(input.data).toEqual({ name: "Claude Code", command: "claude --continue" }); + expect(runtime.startCli).toHaveBeenCalledExactlyOnceWith(input.key, "/repo", "claude --continue"); + // The session exists before the tab mounts, so it attaches instead of showing Start. + expect(runtime.startCli.mock.invocationCallOrder[0]).toBeLessThan(editor.openInput.mock.invocationCallOrder[0]!); + // The launcher tab makes way for the new CLI. + expect(editor.closeInput).toHaveBeenCalledWith(CLI_LAUNCHER_KEY); + }); + + it("starts a restored tab's CLI where it stands", async () => { + const input = cliInput("Codex", "codex --yolo"); + await startTab(input); + expect(runtime.startCli).toHaveBeenCalledExactlyOnceWith(input.key, "/repo", "codex --yolo"); + expect(editor.openInput).not.toHaveBeenCalled(); + }); + + it("opens the launcher tab", async () => { + await openCliLauncher(); + expect(editor.openInput).toHaveBeenCalledExactlyOnceWith( + { kind: "cli.launcher", key: CLI_LAUNCHER_KEY, data: {} }, + { focus: true }, + ); + }); + + it("does nothing without a project", async () => { + useProject.setState({ project: null }); + await launchCli("A", "a"); + await startTab(cliInput("A", "a")); + expect(runtime.startCli).not.toHaveBeenCalled(); + expect(editor.openInput).not.toHaveBeenCalled(); + expect(root()).toBeNull(); + }); +}); diff --git a/src/features/terminal/cli.ts b/src/features/terminal/cli.ts new file mode 100644 index 000000000..073a16e72 --- /dev/null +++ b/src/features/terminal/cli.ts @@ -0,0 +1,135 @@ +/** + * Full-size agent CLIs (Claude Code, Codex, aider…) as editor-area tabs (#2202): + * each tab is a terminal session of the user's login shell that runs one saved + * command first. This module is the xterm-free part: input kinds, the session + * snapshot store the tab strip reads, and the saved CLIs (global, all projects). + * The sessions themselves live in `cliSessions.ts`, behind the terminal runtime. + */ +import { create } from "zustand"; +import { editorService, type EditorInput } from "@/workbench/contributions"; +import { useProject } from "@/platform/project"; +import { loadTerminalRuntime } from "./loader"; +import type { SessionSnapshot } from "./session"; + +/** Editor kind of a CLI session tab. */ +export const CLI_KIND = "cli"; +/** Editor kind of the New CLI launcher tab. */ +export const CLI_LAUNCHER_KIND = "cli.launcher"; +/** Key of the one launcher tab. */ +export const CLI_LAUNCHER_KEY = "cli:launcher"; + +/** `data` of a CLI session tab: what the tab runs and what it is called. */ +export interface CliData { + name: string; + command: string; +} + +/** `data` arrives from the saved editor session: treat it as untrusted JSON. */ +export function cliData(input: EditorInput): CliData | null { + if (input.kind !== CLI_KIND) return null; + const d = input.data as Partial | undefined; + if (!d || typeof d.name !== "string" || !d.name.trim()) return null; + return { name: d.name.trim(), command: typeof d.command === "string" ? d.command.trim() : "" }; +} + +let seq = 0; +/** A fresh input for one CLI run; keys never repeat, so a restored tab is its own. */ +export function cliInput(name: string, command: string): EditorInput { + return { kind: CLI_KIND, key: `cli:r${++seq}-${Date.now().toString(36)}`, data: { name, command } }; +} + +/** Snapshots of the live CLI sessions, by editor input key (an empty record: no live tab). */ +export const useClis = create<{ sessions: Record }>(() => ({ sessions: {} })); + +/** A saved CLI: one launcher card. */ +export interface SavedCli { + id: string; + name: string; + command: string; +} + +const SAVED_PREFIX = "openidea.cli.saved.v1:"; +const MAX_SAVED = 32; + +export function readSavedClis(): SavedCli[] { + try { + return decodeSavedClis(JSON.parse(localStorage.getItem(SAVED_PREFIX) ?? "null")); + } catch { + return []; + } +} + +export function writeSavedClis(saved: SavedCli[]) { + try { + localStorage.setItem(SAVED_PREFIX, JSON.stringify(saved)); + } catch { + /* storage unavailable or full: the launcher just forgets the addition */ + } +} + +/** Validates untrusted JSON; returns null when unusable. */ +export function decodeSavedClis(raw: unknown): SavedCli[] { + if (!Array.isArray(raw)) return []; + const out: SavedCli[] = []; + const ids = new Set(); + for (const item of raw.slice(0, MAX_SAVED)) { + if (!item || typeof item !== "object") continue; + const v = item as Partial; + if (typeof v.id !== "string" || !v.id || ids.has(v.id)) continue; + if (typeof v.name !== "string" || !v.name.trim() || typeof v.command !== "string" || !v.command.trim()) continue; + ids.add(v.id); + out.push({ id: v.id, name: v.name.trim(), command: v.command.trim() }); + } + return out; +} + +export const useSavedClis = create<{ saved: SavedCli[] }>(() => ({ saved: readSavedClis() })); + +let savedSeq = 0; + +/** Saves `name` + `command` for every project; returns the new entry. */ +export function saveCli(name: string, command: string): SavedCli { + const saved: SavedCli = { + id: `cli-s${++savedSeq}-${Date.now().toString(36)}`, + name: name.trim(), + command: command.trim(), + }; + const next = [...useSavedClis.getState().saved, saved]; + useSavedClis.setState({ saved: next }); + writeSavedClis(next); + return saved; +} + +export function removeSavedCli(id: string) { + const next = useSavedClis.getState().saved.filter((s) => s.id !== id); + useSavedClis.setState({ saved: next }); + writeSavedClis(next); +} + +/** Opens the New CLI launcher tab. */ +export async function openCliLauncher() { + await editorService().openInput({ kind: CLI_LAUNCHER_KIND, key: CLI_LAUNCHER_KEY, data: {} }, { focus: true }); +} + +/** + * Starts a CLI in a new editor tab: the login shell of the project directory + * runs `command` as its first input. The launcher tab, if open, makes way for it. + */ +export async function launchCli(name: string, command: string) { + const root = useProject.getState().project?.root; + if (!root) return; + const rt = await loadTerminalRuntime(); + const input = cliInput(name, command); + rt.startCli(input.key, root, command); + await editorService().openInput(input, { focus: true }); + await editorService().closeInput?.(CLI_LAUNCHER_KEY); +} + +/** Starts (or resumes) the CLI of an open tab: the Start button of a restored tab. */ +export async function startTab(input: EditorInput) { + const data = cliData(input); + const root = useProject.getState().project?.root; + if (!data || !root) return; + const rt = await loadTerminalRuntime(); + rt.startCli(input.key, root, data.command); +} diff --git a/src/features/terminal/cliKinds.test.tsx b/src/features/terminal/cliKinds.test.tsx new file mode 100644 index 000000000..823c15cb7 --- /dev/null +++ b/src/features/terminal/cliKinds.test.tsx @@ -0,0 +1,163 @@ +/** + * CLI editor tabs (#2202) in the workbench: the editor kinds the terminal + * feature registers, what the editor session saves for them, and the Start + * screen of a tab restored without its session (a command never runs on its own). + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { executeAction } from "@/platform/actions"; +import { setContext } from "@/platform/context"; +import { useProject } from "@/platform/project"; +import { useContributions, type EditorInput } from "@/workbench/contributions"; +import { initialTabsState, openTab, paneIds, type TabsState } from "@/editor/core/model/tabs"; +import { parseSession, restoreTabsState, serializeSession } from "@/editor/core/model/session"; +import { CLI_KIND, cliInput, useClis } from "./cli"; +import { CliEditor } from "./CliEditor"; +import { activate } from "./index"; + +const runtime = vi.hoisted(() => ({ + loaded: false, + startCli: vi.fn(), + disposeCli: vi.fn(), + cliBusy: vi.fn(), +})); +const editorService = vi.hoisted(() => ({ + openInput: vi.fn(async () => undefined), + closeInput: vi.fn(async () => true), +})); + +vi.mock("./loader", () => ({ + loadTerminalRuntime: async () => runtime, + terminalRuntime: () => (runtime.loaded ? runtime : null), +})); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + editorService: () => editorService, +})); + +const cliInputOf = (key = "cli:r1-x"): EditorInput => ({ + kind: CLI_KIND, + key, + data: { name: "Claude Code", command: "claude" }, +}); + +/** Opens both a CLI tab and the launcher tab in a fresh state. */ +const withTabs = (...inputs: EditorInput[]): TabsState => { + let s = initialTabsState(); + const paneId = paneIds(s)[0]!; + for (const i of inputs) { + const r = openTab(s, paneId, i); + s = r.state; + void r.tabId; + } + return s; +}; + +beforeEach(() => { + useProject.setState({ project: { root: "/repo" } as never }); + setContext("projectOpen", true); +}); +afterEach(() => { + vi.clearAllMocks(); + cleanup(); + useProject.setState({ project: null, settings: null }); + useClis.setState({ sessions: {} }); +}); + +describe("CLI editor kinds", () => { + it("registers the session tab (kept alive, restorable, busy-aware) and the transient launcher", () => { + const deactivate = activate(); + try { + const kind = useContributions.getState().editorKinds.get("cli"); + expect(kind).toMatchObject({ restorable: true, keepAlive: true }); + expect(kind?.isBusy?.(cliInputOf())).toBe(false); + expect(kind?.title?.(cliInputOf())).toBe("Claude Code"); + const launcher = useContributions.getState().editorKinds.get("cli.launcher"); + expect(launcher?.title?.({ kind: "cli.launcher", key: "cli:launcher" })).toBe("New CLI"); + expect(launcher?.restorable).toBeFalsy(); + } finally { + deactivate(); + } + expect(useContributions.getState().editorKinds.has("cli")).toBe(false); + }); + + it("asks the runtime about busy tabs and ends their sessions on close", () => { + const deactivate = activate(); + try { + runtime.loaded = true; + runtime.cliBusy.mockReturnValue(true); + const kind = useContributions.getState().editorKinds.get("cli")!; + expect(kind.isBusy?.(cliInputOf())).toBe(true); + expect(runtime.cliBusy).toHaveBeenCalledWith("cli:r1-x"); + kind.onClose?.(cliInputOf()); + expect(runtime.disposeCli).toHaveBeenCalledWith("cli:r1-x"); + } finally { + runtime.loaded = false; + deactivate(); + } + }); + + it("saves CLI tabs with the session (never the launcher) and restores them unstarted", () => { + const deactivate = activate(); + try { + const s = withTabs(cliInputOf(), { kind: "cli.launcher", key: "cli:launcher" }); + const restored = parseSession( + JSON.parse( + JSON.stringify( + serializeSession(s, {}, (i) => !!useContributions.getState().editorKinds.get(i.kind)?.restorable), + ), + ), + ); + expect(restored).not.toBeNull(); + const tabs = restoreTabsState(restored!, (p) => `file:${p}`); + const open = Object.values(tabs.panes).flatMap((p) => p.tabs); + expect(open.map((t) => t.input.kind)).toEqual(["cli"]); + expect(open[0]!.input).toEqual(cliInputOf()); + // A restored tab has no session: it must not run anything on its own. + expect(runtime.startCli).not.toHaveBeenCalled(); + expect(useClis.getState().sessions).toEqual({}); + } finally { + deactivate(); + } + }); + + it("opens the launcher from the cli.new action", async () => { + const deactivate = activate(); + try { + await executeAction("cli.new"); + expect(editorService.openInput).toHaveBeenCalledExactlyOnceWith( + { kind: "cli.launcher", key: "cli:launcher", data: {} }, + { focus: true }, + ); + } finally { + deactivate(); + } + }); +}); + +describe("restored CLI tab", () => { + it("shows Start and runs the command only when asked", async () => { + const deactivate = activate(); + try { + runtime.loaded = true; + render(); + expect(screen.getByRole("button", { name: "Start" })).toBeInTheDocument(); + expect(screen.getByText("claude")).toBeInTheDocument(); + expect(runtime.startCli).not.toHaveBeenCalled(); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Start" }))); + expect(runtime.startCli).toHaveBeenCalledExactlyOnceWith("cli:r2-y", "/repo", "claude"); + // Once the session exists the tab is the xterm pane, not the Start screen. + act(() => { + useClis.setState({ sessions: { "cli:r2-y": { status: "running" } as never } }); + }); + expect(screen.queryByRole("button", { name: "Start" })).not.toBeInTheDocument(); + } finally { + runtime.loaded = false; + deactivate(); + } + }); + + it("mints keys that never repeat, so a restored tab never meets a live session", () => { + expect(cliInput("A", "a").key).not.toBe(cliInput("A", "a").key); + }); +}); diff --git a/src/features/terminal/cliSessions.test.ts b/src/features/terminal/cliSessions.test.ts new file mode 100644 index 000000000..d55141dd0 --- /dev/null +++ b/src/features/terminal/cliSessions.test.ts @@ -0,0 +1,130 @@ +/** + * The PTY side of the CLI editor tabs (#2202): the backend spawns the user's + * login shell (its default, no explicit program), the saved command is the + * session's first input, and closing ends the PTY. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { useClis } from "./cli"; +import { + cliBusy, + cliSession, + cliSessionForTerminalId, + cliSessionFromElement, + disposeAllClis, + disposeCli, + startCli, +} from "./cliSessions"; + +const ipc = vi.hoisted(() => ({ + call: vi.fn(async (v: unknown) => v), + commands: { + fsReadDir: vi.fn(), + fsEntryKind: vi.fn(), + findFiles: vi.fn(), + termSpawn: vi.fn(), + termKill: vi.fn(), + termResize: vi.fn(), + termIsBusy: vi.fn(), + termWrite: vi.fn(), + }, +})); +vi.mock("@/platform/ipc", () => ({ call: ipc.call, commands: ipc.commands, isTauri: () => true })); +// `Channel` needs the Tauri runtime; the tests hand it to the mocked spawn call. +vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ + ...(await importOriginal()), + Channel: class { + onmessage: ((chunk: string) => void) | null = null; + }, +})); + +afterEach(() => { + disposeAllClis(); + vi.clearAllMocks(); +}); + +/** Starts a session's PTY, capturing the output channel for feeding OSC. */ +const start = async (session: ReturnType) => { + let onmessage: ((chunk: string) => void) | null = null; + ipc.commands.termSpawn.mockImplementationOnce( + async (_options: unknown, channel: { onmessage: ((chunk: string) => void) | null }) => { + onmessage = (chunk) => channel.onmessage?.(chunk); + return { id: 42, title: "zsh" }; + }, + ); + await session.start(); + return async (chunk: string) => { + onmessage?.(chunk); + // xterm parses the chunk asynchronously; flush before asserting on it. + await new Promise((resolve) => session.term.write("", resolve)); + }; +}; + +describe("CLI sessions", () => { + it("runs the saved command as the login shell's first input", async () => { + const session = startCli("cli:t1", "/repo", "claude --continue"); + await start(session); + // `shell: null` with no args is the backend's login-shell default (PATH, nvm, aliases). + expect(ipc.commands.termSpawn).toHaveBeenCalledWith( + expect.objectContaining({ cwd: "/repo", shell: null, args: [], shellIntegration: true }), + expect.anything(), + ); + expect(ipc.commands.termWrite).toHaveBeenCalledWith(42, "claude --continue\r"); + expect(session.state).toMatchObject({ status: "running", cwd: "/repo" }); + expect(useClis.getState().sessions["cli:t1"]).toMatchObject({ status: "running" }); + }); + + it("opens a plain shell when the command is empty", async () => { + const session = startCli("cli:t2", "/repo", ""); + await start(session); + expect(ipc.commands.termSpawn).toHaveBeenCalledWith(expect.objectContaining({ cwd: "/repo" }), expect.anything()); + expect(ipc.commands.termWrite).not.toHaveBeenCalled(); + }); + + it("keeps one session per tab key", () => { + const a = startCli("cli:t3", "/repo", "claude"); + expect(startCli("cli:t3", "/repo", "claude")).toBe(a); + expect(ipc.commands.termSpawn).not.toHaveBeenCalled(); + }); + + it("reports busy from shell integration, then from the backend", async () => { + const session = startCli("cli:t4", "/repo", "codex"); + expect(await cliBusy("cli:t4")).toBe(false); + const feed = await start(session); + ipc.commands.termIsBusy.mockResolvedValue(false); + expect(await cliBusy("cli:t4")).toBe(false); + await feed("\x1b]133;C\x07"); + // The integration says a command runs: known without asking the backend. + expect(cliBusy("cli:t4")).toBe(true); + await feed("\x1b]133;D;0\x07"); + ipc.commands.termIsBusy.mockResolvedValue(true); + expect(await cliBusy("cli:t4")).toBe(true); + expect(await cliBusy("cli:gone")).toBe(false); + }); + + it("finds a session by its PTY and by the DOM it owns, and reports its exit", async () => { + const session = startCli("cli:t5", "/repo", "claude"); + await start(session); + expect(cliSessionForTerminalId(42)).toBe(session); + expect(cliSessionFromElement(session.host)).toBe(session); + session.exited(0); + expect(session.state.status).toBe("exited"); + }); + + it("ends the PTY and forgets the snapshot when its tab closes", async () => { + const session = startCli("cli:t6", "/repo", "claude"); + await start(session); + disposeCli("cli:t6"); + expect(ipc.commands.termKill).toHaveBeenCalledWith(42); + expect(cliSession("cli:t6")).toBeUndefined(); + expect(useClis.getState().sessions["cli:t6"]).toBeUndefined(); + }); + + it("ends every session when the project switches", async () => { + const a = startCli("cli:t7", "/repo", "claude"); + const b = startCli("cli:t8", "/repo", "codex"); + await Promise.all([start(a), start(b)]); + disposeAllClis(); + expect(ipc.commands.termKill).toHaveBeenCalledTimes(2); + expect(useClis.getState().sessions).toEqual({}); + }); +}); diff --git a/src/features/terminal/cliSessions.ts b/src/features/terminal/cliSessions.ts new file mode 100644 index 000000000..da4258ae3 --- /dev/null +++ b/src/features/terminal/cliSessions.ts @@ -0,0 +1,88 @@ +/** + * The PTY side of the CLI editor tabs (#2202): one `TerminalSession` per tab + * key, exactly the tool window's session lifecycle — the backend spawns the + * user's login shell (so PATH, nvm and aliases apply), the session buffers the + * saved command typed before the shell starts and sends it as its first input, + * and the shell stays after the CLI exits. Sessions outlive React: they belong + * to the tab, which reattaches the same xterm host when it is shown again. + */ +import { workflowSettings } from "@/platform/workflowSettings"; +import { useClis } from "./cli"; +import { TerminalSession, type SessionSnapshot } from "./session"; + +const sessions = new Map(); + +export function cliSession(key: string): TerminalSession | undefined { + return sessions.get(key); +} + +function allCliSessions(): TerminalSession[] { + return [...sessions.values()]; +} + +export function cliSessionForTerminalId(id: number): TerminalSession | undefined { + return allCliSessions().find((s) => s.terminalId === id); +} + +/** Session whose DOM contains `el` (the focused xterm of a CLI tab). */ +export function cliSessionFromElement(el: Element | null): TerminalSession | undefined { + const host = el?.closest?.("[data-terminal-session]"); + const key = host?.dataset.terminalSession; + return key ? sessions.get(key) : undefined; +} + +function onChange(key: string, snapshot: SessionSnapshot) { + useClis.setState((s) => ({ sessions: { ...s.sessions, [key]: snapshot } })); +} + +/** + * Starts tab `key`'s CLI in `cwd`: a login shell that runs `command` first (an + * empty command is a plain shell). Already-started tabs are returned as they are. + */ +export function startCli(key: string, cwd: string, command: string): TerminalSession { + const existing = sessions.get(key); + if (existing) return existing; + const session = new TerminalSession({ key, cwd, onChange, onFocus() {} }); + sessions.set(key, session); + useClis.setState((s) => ({ sessions: { ...s.sessions, [key]: session.state } })); + // Typed while the PTY is still starting: sent as the shell's first input. + if (command) session.input(`${command}\r`); + return session; +} + +/** Ends the session of a closed tab. */ +export function disposeCli(key: string) { + sessions.get(key)?.dispose(); + sessions.delete(key); + useClis.setState((s) => { + const sessions = { ...s.sessions }; + delete sessions[key]; + return { sessions }; + }); +} + +/** The project switched: the tabs are closed by the editor without `onClose`, so end the sessions here. */ +export function disposeAllClis() { + for (const session of sessions.values()) session.dispose(); + sessions.clear(); + useClis.setState({ sessions: {} }); +} + +/** + * Whether tab `key` is busy (closing it would end a running CLI). A shell-integration + * report is known without asking; otherwise the backend judges the PTY, which may wait. + */ +export function cliBusy(key: string): boolean | Promise { + const session = sessions.get(key); + if (!session || session.state.status !== "running") return false; + return session.state.commandRunning || session.isBusy(); +} + +export function applySettingsToClis() { + const t = workflowSettings().terminal; + for (const session of sessions.values()) session.applySettings(t); +} + +export function applyThemeToClis() { + for (const session of sessions.values()) session.applyTheme(); +} diff --git a/src/features/terminal/copyKeys.test.ts b/src/features/terminal/copyKeys.test.ts index 3a8357db1..fabf40e9b 100644 --- a/src/features/terminal/copyKeys.test.ts +++ b/src/features/terminal/copyKeys.test.ts @@ -8,7 +8,14 @@ const mock = vi.hoisted(() => ({ session: { hasSelection: true, send: vi.fn(), copySelection: vi.fn() }, settings: { terminal: { overrideIdeShortcuts: true } }, })); -vi.mock("./loader", () => ({ terminalRuntime: () => ({ sessionFromElement: () => mock.session }) })); +vi.mock("./loader", () => ({ + terminalRuntime: () => ({ + sessionFromElement: () => mock.session, + // CLI editor tabs have no tool-window Close/Find of their own. + cliSessionFromElement: () => undefined, + cliSession: () => undefined, + }), +})); vi.mock("@/platform/workflowSettings", () => ({ workflowSettings: () => mock.settings })); beforeEach(() => usePlatform.setState({ os: "windows" })); diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts index 28c131a66..355ba3bfb 100644 --- a/src/features/terminal/index.ts +++ b/src/features/terminal/index.ts @@ -1,13 +1,20 @@ /** * Integrated terminal: xterm.js sessions on backend PTYs in the bottom - * "Terminal" tool window (tabs, split tab groups, links, IDEA-style shortcuts). + * "Terminal" tool window (tabs, split tab groups, links, IDEA-style shortcuts), + * plus the CLI editor tabs (#2202): full-size agent CLIs as editor-area tabs. */ import { registerActions } from "@/platform/actions"; import { onIdeEvent } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { onWorkflowSettingsChange } from "@/platform/workflowSettings"; -import { provideEmbeddedTerminal, registerToolWindow, toolWindowService } from "@/workbench/contributions"; +import { + provideEmbeddedTerminal, + registerEditorKind, + registerToolWindow, + toolWindowService, +} from "@/workbench/contributions"; import { lazyComponent } from "@/ui"; +import { CLI_KIND, CLI_LAUNCHER_KIND, cliData, openCliLauncher } from "./cli"; import { installTerminalKeys } from "./keys"; import { loadTerminalRuntime, terminalRuntime } from "./loader"; import { SAMPLE_TUI_END, SAMPLE_TUI_START, sampleTuiFrame } from "./sampleTui"; @@ -104,7 +111,35 @@ export function activate(): () => void { component: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.TerminalView)), headerContent: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.TerminalTabs)), }), + // CLI sessions as editor tabs (#2202): saved with the editor session, kept alive while hidden. + registerEditorKind({ + kind: CLI_KIND, + component: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.CliEditor)), + title: (input) => cliData(input)?.name ?? "CLI", + icon: () => "terminal", + // A reopened tab shows Start: its command never runs on its own. + restorable: true, + keepAlive: true, + onClose: (input) => terminalRuntime()?.disposeCli(input.key), + isBusy: (input) => terminalRuntime()?.cliBusy(input.key) ?? false, + }), + registerEditorKind({ + kind: CLI_LAUNCHER_KIND, + component: lazyComponent(() => import("./CliLauncher").then((m) => m.CliLauncher)), + title: () => "New CLI", + icon: () => "terminal", + }), registerActions([ + { + id: "cli.new", + title: "New CLI", + description: "Opens the New CLI tab: saved agent CLIs (Claude Code, Codex…) start as full-size editor tabs.", + category: "Terminal", + icon: "terminal", + when: "projectOpen", + keywords: ["cli", "agent", "claude", "codex", "aider", "shell"], + run: () => openCliLauncher(), + }, { id: "terminal.new", title: "New Terminal Tab", @@ -266,19 +301,30 @@ export function activate(): () => void { installTerminalKeys(), onWorkflowSettingsChange( (s) => s.terminal, - () => terminalRuntime()?.applySettingsToAll(), + () => { + terminalRuntime()?.applySettingsToAll(); + terminalRuntime()?.applySettingsToClis(); + }, ), // Font "same as editor" follows Editor › Font. useProject.subscribe((s, prev) => { - if (s.settings?.editor !== prev.settings?.editor) terminalRuntime()?.applySettingsToAll(); + if (s.settings?.editor !== prev.settings?.editor) { + terminalRuntime()?.applySettingsToAll(); + terminalRuntime()?.applySettingsToClis(); + } + }), + onIdeEvent("terminalExited", (e) => { + const rt = terminalRuntime(); + (rt?.sessionForTerminalId(e.terminal) ?? rt?.cliSessionForTerminalId(e.terminal))?.exited(e.code); }), - onIdeEvent("terminalExited", (e) => terminalRuntime()?.sessionForTerminalId(e.terminal)?.exited(e.code)), // Sessions belong to the project. Remember this project's tabs, then open the next one's. useProject.subscribe((s, prev) => { const rt = terminalRuntime(); if (rt && s.project?.root !== prev.project?.root) { if (rt.useTerminalFind.getState().open) rt.closeTerminalFind(); rt.syncTerminalProject(s.project?.root ?? null); + // The editor drops the old project's tabs without `onClose`; their CLIs end with it. + rt.disposeAllClis(); } }), ]; @@ -286,6 +332,7 @@ export function activate(): () => void { if (typeof MutationObserver !== "undefined" && typeof document !== "undefined") { const observer = new MutationObserver(() => { terminalRuntime()?.applyThemeToAll(); + terminalRuntime()?.applyThemeToClis(); terminalRuntime()?.applyThemeToEmbedded(); }); // A palette or plugin theme switch keeps data-theme when both themes share a light / dark base. diff --git a/src/features/terminal/keys.ts b/src/features/terminal/keys.ts index 340f4a7b4..b18d17331 100644 --- a/src/features/terminal/keys.ts +++ b/src/features/terminal/keys.ts @@ -151,7 +151,9 @@ export function installTerminalKeys(target: Window = window): () => void { e.stopImmediatePropagation(); return; } - const session = rt.sessionFromElement(e.target as Element | null); + // CLI editor tabs (#2202) are sessions of their own: the same strokes reach their shell. + const session = + rt.sessionFromElement(e.target as Element | null) ?? rt.cliSessionFromElement(e.target as Element | null); if (!session) return; const action = terminalKeyAction(e, session.hasSelection); // "Override IDE shortcuts" off: Ctrl+key and Escape reach the IDE keymap first; @@ -164,6 +166,8 @@ export function installTerminalKeys(target: Window = window): () => void { } // "Move focus to the Editor with Escape": the IDE keymap's Escape (Focus Editor) runs instead. if (action.kind === "send" && e.key === "Escape" && t.escapeToEditor) return; + // A CLI tab is an editor tab: its Close and Find go back to the IDE keymap. + const inEditorTab = rt.cliSession(session.key) === session; switch (action.kind) { case "pass": return; @@ -184,9 +188,11 @@ export function installTerminalKeys(target: Window = window): () => void { session.clear(); break; case "close": + if (inEditorTab) return; void executeAction("terminal.closeSession"); break; case "find": + if (inEditorTab) return; void executeAction("terminal.find"); break; } diff --git a/src/features/terminal/runtime.ts b/src/features/terminal/runtime.ts index 0816ce4ca..031525413 100644 --- a/src/features/terminal/runtime.ts +++ b/src/features/terminal/runtime.ts @@ -17,6 +17,18 @@ export { unsplit, useTerminals, } from "./store"; +export { + applySettingsToClis, + applyThemeToClis, + cliBusy, + cliSession, + cliSessionForTerminalId, + cliSessionFromElement, + disposeAllClis, + disposeCli, + startCli, +} from "./cliSessions"; +export { CliEditor } from "./CliEditor"; export { TerminalTabs, TerminalView } from "./TerminalView"; export { applyThemeToEmbedded, createEmbeddedTerminal } from "./embedded"; export { closeTerminalFind, openTerminalFind, useTerminalFind } from "./FindBar"; diff --git a/src/platform/locales/en.json b/src/platform/locales/en.json index 6cea8b85e..711c5a9ad 100644 --- a/src/platform/locales/en.json +++ b/src/platform/locales/en.json @@ -107,6 +107,9 @@ "common.close": "Close", "common.copied": "Copied", "common.copy": "Copy", + "editor.closeBusy.message": "Do you want to terminate the process '{name}'?", + "editor.closeBusy.terminate": "Terminate", + "editor.closeBusy.title": "Process '{name}' Is Running", "menu.activeEditor": "Active Editor", "menu.editor.toggleSoftWrap": "Soft-Wrap", "menu.editor.toggleRenderedDocs": "Render Documentation Comments", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index a610a6108..515148d90 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,7 +1,19 @@ { + "Add": "Add", + "Add CLI…": "Add CLI…", + "Cancel": "Cancel", + "CLI": "CLI", + "Command": "Command", "Fix ESLint Problems": "Fix ESLint Problems", + "Name": "Name", + "New CLI": "New CLI", "No ESLint problems to fix": "No ESLint problems to fix", + "No saved CLIs yet — add one, or open a plain shell.": "No saved CLIs yet — add one, or open a plain shell.", + "Open Shell": "Open Shell", + "Opens the New CLI tab: saved agent CLIs (Claude Code, Codex…) start as full-size editor tabs.": "Opens the New CLI tab: saved agent CLIs (Claude Code, Codex…) start as full-size editor tabs.", "Pin ({count})": "Pin ({count})", + "Start": "Start", + "Starts in the project directory through your login shell.": "Starts in the project directory through your login shell.", "Unpin ({count})": "Unpin ({count})", "New Group": "New Group", "Rename Group": "Rename Group", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 1ba341d74..43a6c0bd6 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,7 +1,14 @@ { + "Add CLI…": "添加 CLI…", + "CLI": "CLI", "Fix ESLint Problems": "修复 ESLint 问题", + "New CLI": "新建 CLI", "No ESLint problems to fix": "没有可修复的 ESLint 问题", + "No saved CLIs yet — add one, or open a plain shell.": "还没有保存的 CLI——添加一个,或打开普通 Shell。", + "Open Shell": "打开 Shell", + "Opens the New CLI tab: saved agent CLIs (Claude Code, Codex…) start as full-size editor tabs.": "打开“新建 CLI”标签页:保存的 agent CLI(Claude Code、Codex…)以全尺寸编辑器标签页启动。", "Pin ({count})": "固定({count})", + "Starts in the project directory through your login shell.": "通过你的登录 Shell 在项目目录中启动。", "Unpin ({count})": "取消固定({count})", "New Group": "新建组", "Rename Group": "重命名组", diff --git a/src/platform/locales/zh.json b/src/platform/locales/zh.json index bdde8551c..382ca6318 100644 --- a/src/platform/locales/zh.json +++ b/src/platform/locales/zh.json @@ -107,6 +107,9 @@ "common.close": "关闭", "common.copied": "已复制", "common.copy": "复制", + "editor.closeBusy.message": "是否要终止进程“{name}”?", + "editor.closeBusy.terminate": "终止", + "editor.closeBusy.title": "进程“{name}”正在运行", "menu.activeEditor": "活动编辑器", "menu.editor.toggleSoftWrap": "软换行", "menu.editor.toggleRenderedDocs": "渲染文档注释", diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index b294cb430..09a824ca4 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -142,6 +142,12 @@ export interface EditorKindContribution { keepAlive?: boolean; /** Last tab showing this input closed (including split tabs and tab-limit eviction). */ onClose?(input: EditorInput): void; + /** + * Whether the tab is busy (a process is running, like a terminal session's): + * closing its last tab asks first, and tab-limit eviction skips it. May be + * async; both the close confirmation and the eviction await the answer. + */ + isBusy?(input: EditorInput): boolean | Promise; /** * The editor owns a document with unsaved state (a notebook): it takes part in * the dirty mark, Save All, autosave and the close prompts. Tabs with equal