From 707b6fe169e40a989a086325bdbb7ab7601ea31d Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Tue, 24 Nov 2026 19:01:14 -0800 Subject: [PATCH] feat(terminal): drag terminal tabs into editor groups and splits (#5734) Terminal tabs can be dragged from the Terminal tool window into any editor tab strip position, onto an editor pane or the empty editor area, or onto a pane edge to open a split, keeping the running session (PTY, processes, scrollback, focus). Splitting a terminal editor tab opens a fresh shell in the same working directory instead of showing one session in two panes (editor kinds can declare singleton + splitInput). Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- docs/en/guide/terminal.mdx | 4 +- docs/zh/guide/terminal.mdx | 4 +- e2e/terminal-ui.spec.ts | 110 ++++++++++++++- src/editor/core/controller.test.ts | 44 ++++++ src/editor/core/controller.ts | 151 ++++++++++++++++----- src/editor/core/model/tabs.ts | 2 +- src/editor/core/view/EditorArea.tsx | 19 ++- src/features/terminal/TerminalView.tsx | 7 +- src/features/terminal/cli.test.ts | 44 +++++- src/features/terminal/cli.ts | 40 +++++- src/features/terminal/cliKinds.test.tsx | 9 +- src/features/terminal/closeLastTab.test.ts | 9 +- src/features/terminal/index.ts | 10 +- src/features/terminal/runtime.ts | 1 + src/features/terminal/store.ts | 1 + src/ui/Tabs.test.tsx | 31 +++++ src/ui/Tabs.tsx | 12 +- src/ui/pointerDrag.ts | 12 +- src/workbench/contributions.ts | 54 ++++++-- 19 files changed, 482 insertions(+), 82 deletions(-) diff --git a/docs/en/guide/terminal.mdx b/docs/en/guide/terminal.mdx index e66bf314b9..b4bd4277dd 100644 --- a/docs/en/guide/terminal.mdx +++ b/docs/en/guide/terminal.mdx @@ -18,8 +18,8 @@ Showing an empty Terminal window opens a tab in the start directory (the project - **+** (**New Tab**) opens a tab with the default shell. - The **▾** button (**More Terminal Options**) has **New Terminal Tab**, **New Predefined Session** (one entry per installed shell, plus **SSH Session…**), **Split Right**, **Split Down** and **Settings**. -- Right-click a tab for **Rename Session…**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it. -- Drag tabs to reorder them, or drop a tab on the edge of another group to split. +- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it. +- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab. A tab is named after your custom name, otherwise after the program running in it (when the shell reports it), otherwise `Local`, `Local (2)` and so on. A spinner shows while a command runs; **Exited** or **Failed** shows once the session ends. diff --git a/docs/zh/guide/terminal.mdx b/docs/zh/guide/terminal.mdx index d2c7721364..918f5ea158 100644 --- a/docs/zh/guide/terminal.mdx +++ b/docs/zh/guide/terminal.mdx @@ -18,8 +18,8 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找 - **+**(**新建标签页**)用默认 Shell 打开一个标签页。 - **▾** 按钮(**更多终端选项**)包含 **新建终端标签页**、**新建预定义会话**(每个已安装的 Shell 一项,另有 **SSH 会话…**)、**向右拆分**、**向下拆分** 和 **设置**。 -- 右键标签页可以 **重命名会话…**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。 -- 拖动标签页可以调整顺序,拖到另一组的边缘则会拆分。 +- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。 +- 拖动标签页可以调整顺序,拖到另一组的边缘会拆分;拖入编辑器分组(或其边缘)则会带着正在运行的会话作为编辑器标签页打开。 标签页名称优先用你设置的名字,其次是 Shell 报告的正在运行的程序名,否则就是 `本地`、`本地 (2)` 等默认名称。命令运行时标签上会显示转圈图标,会话结束后显示 **已退出** 或 **失败**。 diff --git a/e2e/terminal-ui.spec.ts b/e2e/terminal-ui.spec.ts index 63077309aa..cda2d13b73 100644 --- a/e2e/terminal-ui.spec.ts +++ b/e2e/terminal-ui.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from "./fixtures"; +import { expect, stubDesktop, test } from "./fixtures"; test("terminal output menu groups session, clipboard and split actions and opens Find", async ({ workbench: page }) => { await page.evaluate(async () => { @@ -360,3 +360,111 @@ test("terminal composition follows a drawn caret inside the session", async ({ w }) .toBe(true); }); + +test("dragging terminal tabs into editor strips and split edges preserves live sessions and scrollback", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(async () => { + const handlers = window.__ipc.handlers; + let id = 0; + const killed: number[] = []; + (window as unknown as { __killedPtys: number[] }).__killedPtys = killed; + handlers.term_default_shell = () => "/bin/zsh"; + handlers.term_available_shells = () => ["/bin/zsh"]; + handlers.term_spawn = () => ({ id: ++id, title: "zsh", pid: id }); + handlers.term_resize = () => null; + handlers.term_write = () => null; + handlers.term_is_busy = () => false; + handlers.term_kill = (args: unknown) => { + killed.push((args as { id: number }).id); + return null; + }; + + const contributions = "/src/workbench/contributions.ts"; + const editor = (await import(contributions)).editorService(); + await editor.openFile("/dev/acme-api/App.tsx", { focus: false }); + await editor.openFile("/dev/acme-api/README.md", { focus: false }); + const store = "/src/workbench/toolwindows/store.ts"; + const layout = await import(store); + layout.setToolWindowSize("bottom", 240); + layout.showToolWindow("terminal", true); + }); + + const terminal = page.getByRole("region", { name: "Terminal", exact: true }); + await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused(); + + // Open a second terminal tab and write distinct output into both sessions. + await terminal.getByRole("button", { name: "New Tab", exact: true }).click(); + const termStrip = terminal.getByRole("tablist", { name: "Terminal sessions" }); + await expect(termStrip.getByRole("tab")).toHaveCount(2); + + await page.evaluate(async () => { + const store = "/src/features/terminal/store.ts"; + const rt = await import(store); + const [first, second] = rt.useTerminals.getState().tabs; + const s1 = rt.getSession(first!.session)!; + const s2 = rt.getSession(second!.session)!; + await new Promise((done) => s1.term.write("ALPHA-SESSION-OUTPUT\r\n", done)); + await new Promise((done) => s2.term.write("BETA-TEST-RUNNER\r\n", done)); + }); + + // 1) Drag "Local" into the editor tab strip between App.tsx and README.md. + const localTab = termStrip.getByRole("tab", { name: "Local", exact: true }); + const readmeTab = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "README.md" }); + const from1 = (await localTab.boundingBox())!; + const to1 = (await readmeTab.boundingBox())!; + await page.mouse.move(from1.x + from1.width / 2, from1.y + from1.height / 2); + await page.mouse.down(); + await page.mouse.move(to1.x + 6, to1.y + to1.height / 2, { steps: 8 }); + if (process.env.OPENIDEA_TERMINAL_SHOTS) + await page.screenshot({ + path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-strip-hover.png`, + animations: "disabled", + }); + await page.mouse.up(); + + const editorLists = page.getByRole("tablist", { name: "Editor tabs" }); + await expect(editorLists.first().getByRole("tab")).toHaveText(["App.tsx", "Local", "README.md"]); + await expect(termStrip.getByRole("tab")).toHaveCount(1); + + const editorArea = page.locator("[data-pane-id]"); + await expect(editorArea.locator(".xterm-rows")).toContainText("ALPHA-SESSION-OUTPUT"); + await expect(editorArea.locator(".xterm-helper-textarea")).toBeFocused(); + + // 2) Drag the remaining "Local (2)" onto the right edge of the editor pane to split it, hiding the empty tool window. + const local2Tab = termStrip.getByRole("tab", { name: "Local (2)", exact: true }); + const paneBox = (await editorArea.first().locator('[role="tabpanel"]').boundingBox())!; + const from2 = (await local2Tab.boundingBox())!; + await page.mouse.move(from2.x + from2.width / 2, from2.y + from2.height / 2); + await page.mouse.down(); + await page.mouse.move(paneBox.x + paneBox.width - 20, paneBox.y + paneBox.height / 2, { steps: 8 }); + if (process.env.OPENIDEA_TERMINAL_SHOTS) + await page.screenshot({ + path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-split-hover.png`, + animations: "disabled", + }); + await page.mouse.up(); + + await expect(terminal).toBeHidden(); + await expect(editorArea).toHaveCount(2); + await expect(editorArea.nth(1).locator(".xterm-rows")).toContainText("BETA-TEST-RUNNER"); + await expect(editorArea.nth(1).locator(".xterm-helper-textarea")).toBeFocused(); + + // 3) Resize the editor split divider and confirm both panes and the live PTY survive. + const widthBefore = (await editorArea.nth(1).boundingBox())!.width; + const divider = page.locator("[data-editor-area]").getByRole("separator"); + const divBox = (await divider.boundingBox())!; + await page.mouse.move(divBox.x + divBox.width / 2, divBox.y + divBox.height / 2); + await page.mouse.down(); + await page.mouse.move(divBox.x - 100, divBox.y + divBox.height / 2, { steps: 6 }); + await page.mouse.up(); + await expect.poll(async () => (await editorArea.nth(1).boundingBox())!.width).toBeGreaterThan(widthBefore + 50); + await expect(editorArea.nth(1).locator(".xterm-rows")).toContainText("BETA-TEST-RUNNER"); + if (process.env.OPENIDEA_TERMINAL_SHOTS) + await page.screenshot({ + path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-final.png`, + animations: "disabled", + }); + expect(await page.evaluate(() => (window as unknown as { __killedPtys: number[] }).__killedPtys)).toEqual([]); +}); diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts index 533cb137f6..eb42d9d75f 100644 --- a/src/editor/core/controller.test.ts +++ b/src/editor/core/controller.test.ts @@ -804,6 +804,50 @@ describe("EditorController", () => { offWrapper(); } }); + + it("opens inputs at explicit strip indices or split edges and never clones singleton kinds", async () => { + let seq = 1; + const dispose = registerEditorKind({ + kind: "singleton-term", + component: () => null, + title: (i) => i.key, + singleton: true, + splitInput: () => ({ kind: "singleton-term", key: `singleton-term:${++seq}` }), + }); + try { + ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" })); + ctrl.start(); + await ctrl.openFile("/p/a.ts", { focus: false }); + await ctrl.openFile("/p/b.ts", { focus: false }); + const p1 = useTabs.getState().activePane; + + // Explicit strip index inserts between a.ts and b.ts. + const term1 = { kind: "singleton-term", key: "singleton-term:1" }; + await ctrl.openInput(term1, { pane: p1, index: 1, focus: false }); + expect(useTabs.getState().panes[p1]!.tabs.map((t) => t.input.key)).toEqual([ + "file:/p/a.ts", + "singleton-term:1", + "file:/p/b.ts", + ]); + + // Splitting a singleton tab opens `splitInput` in the new pane instead of duplicating the key. + ctrl.activate(p1, useTabs.getState().panes[p1]!.tabs[1]!.id, false); + ctrl.split(p1, "row"); + await vi.waitFor(() => expect(Object.keys(useTabs.getState().panes)).toHaveLength(2)); + const p2 = Object.keys(useTabs.getState().panes).find((id) => id !== p1)!; + expect(useTabs.getState().panes[p1]!.tabs.map((t) => t.input.key)).toContain("singleton-term:1"); + expect(useTabs.getState().panes[p2]!.tabs.map((t) => t.input.key)).toEqual(["singleton-term:2"]); + + // Re-opening an already open singleton at an edge moves it into the new split instead of duplicating it. + await ctrl.openInput(term1, { pane: p2, edge: "bottom", focus: false }); + const allTerm1 = Object.values(useTabs.getState().panes).flatMap((p) => + p.tabs.filter((t) => t.input.key === "singleton-term:1"), + ); + expect(allTerm1).toHaveLength(1); + } finally { + dispose(); + } + }); }); describe("editor action when clauses", () => { diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 00dd7f823b..57689185d4 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -1402,45 +1402,94 @@ export class EditorController implements SlotHost { const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle })); const preview = !!o.preview && editorPrefs().tabs.previewTab && canPreview; if (!activate && preview) return; + const kind = kinds.get(input.kind); let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null; if (!paneId) return; - if (o.side) { - const right = neighbourPane(s, paneId); - if (right) paneId = right; - else { - const split = splitPane(s, paneId, "row"); + const existingSingleton = kind?.singleton ? findTab(s, input.key, paneId) : null; + let tabId: string; + if (existingSingleton) { + tabId = existingSingleton.tab.id; + if (o.edge) { + const moved = moveTabToNewSplit(s, existingSingleton.paneId, tabId, paneId, o.edge); + if (moved) { + s = moved.state; + paneId = moved.paneId; + } else { + paneId = existingSingleton.paneId; + if (activate) s = activateTab(setActivePane(s, paneId), paneId, tabId); + } + } else if ((o.pane || o.side) && existingSingleton.paneId !== paneId) { + const target = o.side ? (neighbourPane(s, paneId) ?? paneId) : paneId; + if (target !== existingSingleton.paneId) { + s = moveTab( + s, + existingSingleton.paneId, + tabId, + target, + o.index ?? s.panes[target]?.tabs.length ?? 0, + o.pinned, + ); + paneId = target; + } else if (o.side) { + const moved = moveTabToNewSplit(s, existingSingleton.paneId, tabId, paneId, "right"); + if (moved) { + s = moved.state; + paneId = moved.paneId; + } + } + } else { + paneId = existingSingleton.paneId; + if (activate) s = activateTab(setActivePane(s, paneId), paneId, tabId); + } + if (!o.preview || !canPreview) s = promoteTab(s, paneId, tabId); + } else { + if (o.edge) { + const split = splitAtEdge(s, paneId, o.edge); s = split.state; paneId = split.paneId; - // The new pane starts with only the requested input. - const pane = s.panes[paneId]!; - s = { ...s, panes: { ...s.panes, [paneId]: { ...pane, tabs: [], active: null, mru: [] } } }; if (!activate) s = { ...s, activePane: useTabs.getState().activePane }; + } else if (o.side) { + const right = neighbourPane(s, paneId); + if (right) paneId = right; + else { + const split = splitPane(s, paneId, "row"); + s = split.state; + paneId = split.paneId; + // The new pane starts with only the requested input. + const pane = s.panes[paneId]!; + s = { ...s, panes: { ...s.panes, [paneId]: { ...pane, tabs: [], active: null, mru: [] } } }; + if (!activate) s = { ...s, activePane: useTabs.getState().activePane }; + } } - } - const found = findTab(s, input.key, paneId); - let tabId: string; - if (found && (!(o.side || o.pane) || found.paneId === paneId)) { - paneId = found.paneId; - if (activate) s = activateTab(setActivePane(s, paneId), paneId, found.tab.id); - if (!o.preview || !canPreview) s = promoteTab(s, paneId, found.tab.id); - tabId = found.tab.id; - if (activate && found.tab.input.data !== input.data && input.data !== undefined) - s = openTab(s, paneId, input, { - preview: o.preview && canPreview, + const found = findTab(s, input.key, paneId); + if (found && (!(o.side || o.pane || o.edge) || found.paneId === paneId)) { + paneId = found.paneId; + if (activate) s = activateTab(setActivePane(s, paneId), paneId, found.tab.id); + if (!o.preview || !canPreview) s = promoteTab(s, paneId, found.tab.id); + tabId = found.tab.id; + if (activate && found.tab.input.data !== input.data && input.data !== undefined) + s = openTab(s, paneId, input, { + preview: o.preview && canPreview, + activate, + }).state; + } else { + const tabs = editorPrefs().tabs; + const r = openTab(s, paneId, input, { + preview, + pinned: o.pinned, activate, - }).state; - } else { - const tabs = editorPrefs().tabs; - const r = openTab(s, paneId, input, { - preview, - activate, - preservePreview: !activate, - keepPreview: (t) => !isTextInput(t.input), - ...(tabs.openAtEnd ? { index: s.panes[paneId]?.tabs.length ?? 0 } : {}), - }); - s = r.state; - tabId = r.tabId; - if (tabs.sortAlphabetically) s = sortTabs(s, paneId, (t) => tabSortKey(t.input)); + preservePreview: !activate, + keepPreview: (t) => !isTextInput(t.input), + ...(o.index !== undefined + ? { index: o.index } + : tabs.openAtEnd + ? { index: s.panes[paneId]?.tabs.length ?? 0 } + : {}), + }); + s = r.state; + tabId = r.tabId; + if (tabs.sortAlphabetically && o.index === undefined) s = sortTabs(s, paneId, (t) => tabSortKey(t.input)); + } } if (o.selection) this.selectionRequests.set(tabId, Math.max(generation.sequence, this.selectionRequests.get(tabId) ?? 0)); @@ -1891,18 +1940,26 @@ export class EditorController implements SlotHost { keepTab(paneId: string, tabId: string) { this.apply((s) => (s.panes[paneId] ? promoteTab(s, paneId, tabId) : s)); } + private focusMovedTab(tabId: string) { + const slot = this.slots.get(tabId); + if (slot?.view) slot.focus(); + else if (slot) slot.wantsFocus = true; + else + requestAnimationFrame(() => { + if (this.activeTabOf()?.id === tabId) this.focus(); + }); + } /** Drag & drop; the tab keeps its id (and slot) when moved within a pane. */ moveTab(fromPane: string, tabId: string, toPane: string, index: number, pin?: boolean) { this.apply((s) => moveTab(s, fromPane, tabId, toPane, index, pin)); + this.focusMovedTab(tabId); } /** Drag & drop onto an editor edge: the tab moves into a new split on that side. */ moveTabToSplit(fromPane: string, tabId: string, targetPane: string, edge: SplitEdge) { const r = moveTabToNewSplit(useTabs.getState(), fromPane, tabId, targetPane, edge); if (!r) return; useTabs.setState(r.state, true); - const slot = this.slots.get(tabId); - if (slot?.view) slot.focus(); - else if (slot) slot.wantsFocus = true; + this.focusMovedTab(tabId); } /** Files dropped on an editor: opened in that pane, or in a new split at `edge`. */ async openFilesIn(paths: readonly string[], paneId: string, edge: SplitEdge | "center") { @@ -1944,6 +2001,19 @@ export class EditorController implements SlotHost { split(paneId: string, dir: "row" | "column") { const s = useTabs.getState(); const srcPane = s.panes[paneId]; + const active = srcPane?.tabs.find((t) => t.id === srcPane.active); + const kind = active ? useContributions.getState().editorKinds.get(active.input.kind) : undefined; + if (active && kind?.singleton) { + if (kind.splitInput) { + void Promise.resolve(kind.splitInput(active.input)).then((fresh) => { + if (!fresh || !useTabs.getState().panes[paneId]) return; + void this.openInput(fresh, { pane: paneId, edge: dir === "row" ? "right" : "bottom", focus: true }); + }); + } else if (srcPane && srcPane.tabs.length > 1) { + this.moveTabToSplit(paneId, active.id, paneId, dir === "row" ? "right" : "bottom"); + } + return; + } const srcSlot = srcPane?.active ? this.slots.get(srcPane.active) : undefined; const r = splitPane(s, paneId, dir); useTabs.setState(r.state, true); @@ -2058,6 +2128,17 @@ export class EditorController implements SlotHost { this.activate(paneId, tabId, false); return this.split(paneId, "row"); } + const kind = useContributions.getState().editorKinds.get(tab.input.kind); + if (kind?.singleton) { + if (kind.splitInput) { + void Promise.resolve(kind.splitInput(tab.input)).then((fresh) => { + if (fresh && useTabs.getState().panes[target]) void this.openInput(fresh, { pane: target, focus: true }); + }); + } else { + this.moveToOpposite(paneId, tabId); + } + return; + } const r = openTab(s, target, tab.input); useTabs.setState(r.state, true); void this.ensureSlot(r.tabId, { from: this.slots.get(tabId) }).then((slot) => { diff --git a/src/editor/core/model/tabs.ts b/src/editor/core/model/tabs.ts index a4ae711177..11071bf9f5 100644 --- a/src/editor/core/model/tabs.ts +++ b/src/editor/core/model/tabs.ts @@ -197,7 +197,7 @@ export function openTab( } else { const pins = pinnedCount(pane); let index: number; - if (tab.pinned) index = pins; + if (tab.pinned) index = opts.index !== undefined ? Math.max(0, Math.min(opts.index, pins)) : pins; else if (opts.index !== undefined) index = Math.max(pins, Math.min(opts.index, tabs.length)); else { const activeIdx = tabs.findIndex((t) => t.id === pane.active); diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 38c8e0b0b6..68c0fe6bab 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -27,6 +27,7 @@ import { EDITOR_TAB_MIME, acceptsEditorDrop, dropOnEditor, + editorDropAllowsSplit, getFileDecoration, prepareMenuGroups, textEditorWrapperFor, @@ -107,7 +108,7 @@ function EmptyEditorArea() { const el = ref.current; if (!el) return; return registerDropTarget(el, { - accepts: (type) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type), + accepts: (type, data) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type, data), over: (data) => setOver(data.type !== FILES_DRAG || droppedFiles(data.payload).length > 0), leave: () => setOver(false), drop: (data) => { @@ -119,7 +120,7 @@ function EmptyEditorArea() { return; } if (data.type !== EDITOR_TAB_MIME) { - dropOnEditor(data); + dropOnEditor(data, { paneId, zone: "center", index: 0 }); return; } const p = parseTabPayload(data.payload); @@ -301,10 +302,14 @@ function PaneView({ paneId }: { paneId: string }) { const strip = (offset: number, pin?: boolean): TabsDnd => ({ type: EDITOR_TAB_MIME, payload: (tabId) => JSON.stringify({ paneId, tabId }), + accepts: (data) => acceptsEditorDrop(data.type, data), onDrop: (raw, index) => { const p = parseTabPayload(raw); if (p) ctrl.moveTab(p.paneId, p.tabId, paneId, index + offset, pin); }, + onExternalDrop: (data, index) => { + dropOnEditor(data, { paneId, zone: "center", index: index + offset, pinned: pin }); + }, onDropOutside: dropOutside, }); return { all: strip(0), pinned: strip(0, true), rest: strip(pinnedCount, false) }; @@ -318,10 +323,13 @@ function PaneView({ paneId }: { paneId: string }) { if (!el) return; const zoneAt = (x: number, y: number) => dropZoneAt(x, y, el.getBoundingClientRect()); return registerDropTarget(el, { - accepts: (type) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type), + accepts: (type, data) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type, data), over: (data, x, y) => { if (data.type === FILES_DRAG) setDropZone(droppedFiles(data.payload).length ? zoneAt(x, y) : null); - else setDropZone(data.type === EDITOR_TAB_MIME ? zoneAt(x, y) : "center"); + else + setDropZone( + data.type === EDITOR_TAB_MIME || editorDropAllowsSplit(data.type, data) ? zoneAt(x, y) : "center", + ); }, leave: () => setDropZone(null), drop: (data, x, y) => { @@ -332,7 +340,8 @@ function PaneView({ paneId }: { paneId: string }) { return; } if (data.type !== EDITOR_TAB_MIME) { - dropOnEditor(data); + const target = useTabs.getState().panes[paneId]; + dropOnEditor(data, { paneId, zone, ...(zone === "center" ? { index: target?.tabs.length ?? 0 } : {}) }); return; } const p = parseTabPayload(data.payload); diff --git a/src/features/terminal/TerminalView.tsx b/src/features/terminal/TerminalView.tsx index f8bc7e6b5a..010012414f 100644 --- a/src/features/terminal/TerminalView.tsx +++ b/src/features/terminal/TerminalView.tsx @@ -50,15 +50,12 @@ import { type GroupLayout, type TerminalTab, } from "./store"; +import { TERMINAL_TAB_MIME } from "./cli"; import { openTerminalFind, TerminalFindBar } from "./FindBar"; import styles from "./Terminal.module.css"; const TAB_PREFIX = "openidea-terminal"; -/** - * Drag type of terminal tabs: dragging one reorders its group's strip or moves - * it to another group's, like IDEA's terminal tabs. - */ -const TAB_MIME = "application/x-openidea-terminal-tab"; +const TAB_MIME = TERMINAL_TAB_MIME; /** Session title and working directory, even when available space trims the label. */ function tabTooltip(tab: TerminalTab, sessions: Parameters[1]): string | undefined { diff --git a/src/features/terminal/cli.test.ts b/src/features/terminal/cli.test.ts index 59c518c5be..541a2e4a4c 100644 --- a/src/features/terminal/cli.test.ts +++ b/src/features/terminal/cli.test.ts @@ -3,11 +3,11 @@ * Start flow of a restored tab through the terminal runtime. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { cliData, cliInput, moveTerminalToEditor, startTab } from "./cli"; +import { CLI_KIND, cliData, cliInput, moveTerminalToEditor, splitCliTab, startTab } from "./cli"; const tabs = vi.hoisted(() => ({ state: { - tabs: [] as { id: string; session: string }[], + tabs: [] as { id: string; name?: string; session: string }[], activeTab: null as string | null, sessions: {} as Record, }, @@ -16,12 +16,16 @@ const runtime = vi.hoisted(() => ({ loaded: false, startCli: vi.fn(), adoptCli: vi.fn(), + cliSession: vi.fn(), detachTab: vi.fn(), + nextTabName: vi.fn((existing: readonly string[], base = "Local") => (existing.includes(base) ? `${base} (2)` : base)), + startDirectory: vi.fn((root: string) => root), tabTitle: vi.fn((_tab: unknown, _sessions: unknown) => "Local (2)"), useTerminals: { getState: () => tabs.state }, })); const editor = vi.hoisted(() => ({ openInput: vi.fn(async (_input?: unknown, _options?: unknown) => undefined), + openTabs: vi.fn(() => [] as { input: { kind: string; key: string; data?: unknown }; title: string }[]), })); const toolWindows = vi.hoisted(() => ({ hide: vi.fn() })); @@ -106,6 +110,42 @@ describe("Move to Editor", () => { expect(runtime.detachTab).not.toHaveBeenCalled(); expect(editor.openInput).not.toHaveBeenCalled(); }); + + it("forwards pane, split edge, insertion index and pin state for editor drops", async () => { + tabs.state.tabs = [{ id: "t1", session: "s1" }]; + runtime.detachTab.mockImplementationOnce(() => session); + await moveTerminalToEditor("t1", { paneId: "pane-2", zone: "bottom" }); + expect(editor.openInput).toHaveBeenLastCalledWith(expect.objectContaining({ kind: CLI_KIND }), { + focus: true, + pane: "pane-2", + edge: "bottom", + }); + + runtime.detachTab.mockImplementationOnce(() => session); + await moveTerminalToEditor("t1", { paneId: "pane-1", zone: "center", index: 1, pinned: true }); + expect(editor.openInput).toHaveBeenLastCalledWith(expect.objectContaining({ kind: CLI_KIND }), { + focus: true, + pane: "pane-1", + index: 1, + pinned: true, + }); + }); + + it("splits an editor terminal tab into a fresh session in its working directory", async () => { + tabs.state.tabs = [{ id: "t1", name: "Local", session: "s1" }]; + const existing = cliInput("Local (2)", "", "/repo"); + editor.openTabs.mockReturnValueOnce([{ input: existing, title: "Local (2)" }]); + runtime.cliSession.mockReturnValueOnce({ state: { cwd: "/repo/sub" } }); + runtime.nextTabName.mockReturnValueOnce("Local (3)"); + + const fresh = await splitCliTab(existing); + expect(fresh).toMatchObject({ + kind: CLI_KIND, + data: { name: "Local (3)", command: "", cwd: "/repo/sub" }, + }); + expect(fresh?.key).not.toBe(existing.key); + expect(runtime.startCli).toHaveBeenCalledExactlyOnceWith(fresh!.key, "/repo/sub", "", "/repo"); + }); }); describe("restored tabs", () => { diff --git a/src/features/terminal/cli.ts b/src/features/terminal/cli.ts index f67a798526..b24efb8985 100644 --- a/src/features/terminal/cli.ts +++ b/src/features/terminal/cli.ts @@ -7,10 +7,11 @@ */ import { createElement } from "react"; import { create } from "zustand"; -import { editorService, toolWindowService, type EditorInput } from "@/workbench/contributions"; +import { editorService, toolWindowService, type EditorDropTarget, type EditorInput } from "@/workbench/contributions"; import { useTx } from "@/platform/i18n"; import { useProject } from "@/platform/project"; import { isRemoteWindow } from "@/platform/remote"; +import { workflowSettings } from "@/platform/workflowSettings"; import { Badge } from "@/ui"; import { loadTerminalRuntime } from "./loader"; import type { SessionSnapshot } from "./session"; @@ -18,6 +19,9 @@ import type { SessionSnapshot } from "./session"; /** Editor kind of a terminal session tab. */ export const CLI_KIND = "cli"; +/** Drag type of terminal tabs: reorders within the tool window, or drops onto the editor area. */ +export const TERMINAL_TAB_MIME = "application/x-openidea-terminal-tab"; + /** `data` of a terminal editor tab: its title and where it started. */ export interface CliData { name: string; @@ -91,7 +95,7 @@ function trackCliTerminalId(input: EditorInput) { * Move to Editor: tab `id` of the Terminal tool window (the active one when omitted) * leaves the tool window and opens as an editor tab, its session still running. */ -export async function moveTerminalToEditor(id?: string) { +export async function moveTerminalToEditor(id?: string, target?: EditorDropTarget) { const rt = await loadTerminalRuntime(); const state = rt.useTerminals.getState(); const tab = state.tabs.find((t) => t.id === (id ?? state.activeTab)); @@ -104,7 +108,37 @@ export async function moveTerminalToEditor(id?: string) { rt.adoptCli(input.key, session); trackCliTerminalId(input); if (rt.useTerminals.getState().tabs.length === 0) toolWindowService().hide("terminal"); - await editorService().openInput(input, { focus: true }); + await editorService().openInput(input, { + focus: true, + ...(target + ? { + pane: target.paneId, + ...(target.zone !== "center" ? { edge: target.zone } : {}), + ...(target.index !== undefined ? { index: target.index } : {}), + ...(target.pinned !== undefined ? { pinned: target.pinned } : {}), + } + : {}), + }); +} + +/** Splits a terminal editor tab into a new shell session in the same directory. */ +export async function splitCliTab(input: EditorInput): Promise { + const root = useProject.getState().project?.root; + if (!root) return null; + const rt = await loadTerminalRuntime(); + const cwd = rt.cliSession(input.key)?.state.cwd || cliData(input)?.cwd || rt.startDirectory(root); + const openNames = + editorService() + .openTabs?.() + .flatMap((t) => (t.input.kind === CLI_KIND ? [cliData(t.input)?.name ?? t.title] : [])) ?? []; + const name = rt.nextTabName( + [...rt.useTerminals.getState().tabs.map((t) => t.name), ...openNames], + workflowSettings().terminal.tabName, + ); + const fresh = cliInput(name, "", cwd); + rt.startCli(fresh.key, cwd, "", root); + trackCliTerminalId(fresh); + return fresh; } /** Starts the session of a restored tab: its Start button. */ diff --git a/src/features/terminal/cliKinds.test.tsx b/src/features/terminal/cliKinds.test.tsx index 1a420fe576..0770959e0a 100644 --- a/src/features/terminal/cliKinds.test.tsx +++ b/src/features/terminal/cliKinds.test.tsx @@ -8,10 +8,10 @@ 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 { dropOnEditor, editorDropAllowsSplit, 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 { CLI_KIND, TERMINAL_TAB_MIME, cliInput, useClis } from "./cli"; import { CliEditor } from "./CliEditor"; import { activate } from "./index"; @@ -71,7 +71,9 @@ describe("terminal editor kind", () => { const deactivate = activate(); try { const kind = useContributions.getState().editorKinds.get("cli"); - expect(kind).toMatchObject({ restorable: true, keepAlive: true }); + expect(kind).toMatchObject({ restorable: true, keepAlive: true, singleton: true }); + expect(editorDropAllowsSplit(TERMINAL_TAB_MIME)).toBe(true); + expect(dropOnEditor({ type: TERMINAL_TAB_MIME, payload: "t9" }, { paneId: "p1", zone: "right" })).toBe(true); expect(kind?.isBusy?.(cliInputOf())).toBe(false); expect(kind?.title?.(cliInputOf())).toBe("Claude Code"); expect(kind?.title?.({ kind: "cli", key: "cli:r9", data: {} })).toBe("Terminal"); @@ -79,6 +81,7 @@ describe("terminal editor kind", () => { deactivate(); } expect(useContributions.getState().editorKinds.has("cli")).toBe(false); + expect(editorDropAllowsSplit(TERMINAL_TAB_MIME)).toBe(false); }); it("asks the runtime about busy tabs and ends their sessions on close", () => { diff --git a/src/features/terminal/closeLastTab.test.ts b/src/features/terminal/closeLastTab.test.ts index 2d6ba0a6d4..bedb643e7a 100644 --- a/src/features/terminal/closeLastTab.test.ts +++ b/src/features/terminal/closeLastTab.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions"; import { getContext, setContext } from "@/platform/context"; -import { closeAll, closeTab, getSession, newTab, useTerminals } from "./store"; +import { closeAll, closeTab, detachTab, getSession, newTab, useTerminals } from "./store"; const { focused } = vi.hoisted(() => ({ focused: [] as string[] })); @@ -121,6 +121,13 @@ describe("terminalFocus after the focused pane goes away", () => { expect(getContext().terminalFocus).toBe(false); }); + it("is cleared when the focused tab is detached to the editor", () => { + const tab = newTab("/repo"); + typeInto(tab.session); + expect(detachTab(tab.id)?.key).toBe(tab.session); + expect(getContext().terminalFocus).toBe(false); + }); + it("is left alone when a background session ends", () => { const a = newTab("/repo"); const b = newTab("/repo"); diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts index b0c7ed449b..3958b1c92c 100644 --- a/src/features/terminal/index.ts +++ b/src/features/terminal/index.ts @@ -13,12 +13,13 @@ import { onWorkflowSettingsChange } from "@/platform/workflowSettings"; import { provideEmbeddedTerminal, registerAgentContextSource, + registerEditorDropHandler, registerEditorKind, registerToolWindow, toolWindowService, } from "@/workbench/contributions"; import { lazyComponent } from "@/ui"; -import { CLI_KIND, CliDoneMark, cliData, moveTerminalToEditor } from "./cli"; +import { CLI_KIND, CliDoneMark, TERMINAL_TAB_MIME, cliData, moveTerminalToEditor, splitCliTab } from "./cli"; import { installTerminalKeys } from "./keys"; import { loadTerminalRuntime, terminalRuntime } from "./loader"; import { SAMPLE_TUI_END, SAMPLE_TUI_START, sampleTuiFrame } from "./sampleTui"; @@ -144,9 +145,16 @@ export function activate(): () => void { // A reopened tab shows Start: nothing runs on its own. restorable: true, keepAlive: true, + singleton: true, + splitInput: splitCliTab, onClose: (input) => terminalRuntime()?.disposeCli(input.key), isBusy: (input) => terminalRuntime()?.cliBusy(input.key) ?? false, }), + registerEditorDropHandler({ + accepts: (type) => type === TERMINAL_TAB_MIME, + allowSplit: true, + drop: ({ payload }, target) => void moveTerminalToEditor(payload, target), + }), registerActions([ { id: "terminal.moveToEditor", diff --git a/src/features/terminal/runtime.ts b/src/features/terminal/runtime.ts index bb8b162d92..0d410e9e12 100644 --- a/src/features/terminal/runtime.ts +++ b/src/features/terminal/runtime.ts @@ -7,6 +7,7 @@ export { detachTab, newTab, newTabRunning, + nextTabName, pluginSession, rememberTerminals, syncTerminalProject, diff --git a/src/features/terminal/store.ts b/src/features/terminal/store.ts index a4d7bb44bd..516e19d906 100644 --- a/src/features/terminal/store.ts +++ b/src/features/terminal/store.ts @@ -315,6 +315,7 @@ export function detachTab(id: string): TerminalSession | undefined { const tab = useTerminals.getState().tabs.find((t) => t.id === id); const session = tab && sessions.get(tab.session); if (!tab || !session) return undefined; + if (document.activeElement && session.host?.contains(document.activeElement)) publishFocus(false); sessions.delete(tab.session); useTerminals.setState((s) => { const next = { ...s.sessions }; diff --git a/src/ui/Tabs.test.tsx b/src/ui/Tabs.test.tsx index 1e0f1498b7..6553e99b61 100644 --- a/src/ui/Tabs.test.tsx +++ b/src/ui/Tabs.test.tsx @@ -460,4 +460,35 @@ describe("Tabs drag & drop", () => { pointer(window, "pointerup", 180); expect(onDrop).toHaveBeenCalledWith("a", 2); }); + + it("accepts external drag types with an insertion marker and routes them to onExternalDrop", () => { + const onExternalDrop = vi.fn(); + render( + <> + + {}} + dnd={{ + type: "application/x-other", + payload: (id) => id, + onDrop: () => {}, + accepts: (data) => data.type === TYPE && data.payload === "term-1", + onExternalDrop, + }} + /> + , + ); + pointer(within(tab("Source", "term-1")).getByRole("tab"), "pointerdown", 50); + hit = strip("Editor"); + pointer(window, "pointermove", 120); + expect(tab("Editor", "d")).toHaveClass(styles.dropBefore!); + pointer(window, "pointerup", 120); + expect(onExternalDrop).toHaveBeenCalledWith({ type: TYPE, payload: "term-1" }, 1); + }); }); diff --git a/src/ui/Tabs.tsx b/src/ui/Tabs.tsx index e7fef37d24..ee331ca2b7 100644 --- a/src/ui/Tabs.tsx +++ b/src/ui/Tabs.tsx @@ -22,7 +22,7 @@ import { IconButton } from "./Button"; import { Menu, type MenuItem } from "./Menu"; import { HiddenTabsPopup } from "./HiddenTabsPopup"; import { tooltipAttrs } from "./Tooltip"; -import { isOutsideWindow, registerDropTarget, startPointerDrag } from "./pointerDrag"; +import { isOutsideWindow, registerDropTarget, startPointerDrag, type DragData } from "./pointerDrag"; import { Given } from "./T"; import styles from "./Tabs.module.css"; import { tx, useGivenTx } from "@/platform/i18n"; @@ -69,6 +69,9 @@ export interface TabsDnd { type: string; payload: (id: string) => string; onDrop: (payload: string, index: number) => void; + /** Extra drag payloads accepted onto this strip (shown with the cross-strip insertion line). */ + accepts?: (data: DragData) => boolean; + onExternalDrop?: (data: DragData, index: number) => void; /** * A dragged tab released with no accepting target (the pointer left the * window): the editor uses it to detach the tab into a new window. Gets the @@ -242,12 +245,15 @@ export function Tabs({ return next ? items.indexOf(next) : items.length; }; return registerDropTarget(el, { - accepts: (type) => type === dropState.current.dnd?.type, + accepts: (type, data) => type === dropState.current.dnd?.type || !!dropState.current.dnd?.accepts?.(data), over: (_, x, y) => setDrop(indexAt(x, y)), leave: () => setDrop(null), drop: (data, x, y) => { setDrop(null); - dropState.current.dnd?.onDrop(data.payload, indexAt(x, y)); + const current = dropState.current.dnd; + const at = indexAt(x, y); + if (data.type === current?.type) current.onDrop(data.payload, at); + else current?.onExternalDrop?.(data, at); }, }); }, [dndType]); diff --git a/src/ui/pointerDrag.ts b/src/ui/pointerDrag.ts index e90534f891..3d3ba7b791 100644 --- a/src/ui/pointerDrag.ts +++ b/src/ui/pointerDrag.ts @@ -19,7 +19,7 @@ export const FILES_DRAG = "application/x-openidea-files"; export const REMOTE_FILES_DRAG = "application/x-openidea-remote-files"; export interface DropTarget { - accepts(type: string): boolean; + accepts(type: string, data: DragData): boolean; /** The pointer moved over the target. */ over(data: DragData, x: number, y: number): void; /** The pointer left the target, or the drag ended elsewhere / was cancelled. */ @@ -36,11 +36,11 @@ export function registerDropTarget(el: Element, target: DropTarget): () => void }; } -/** The innermost registered target under (x, y) accepting `type`. */ -function targetAt(type: string, x: number, y: number): DropTarget | null { +/** The innermost registered target under (x, y) accepting `data`. */ +function targetAt(data: DragData, x: number, y: number): DropTarget | null { for (let el = document.elementFromPoint(x, y); el; el = el.parentElement) { const t = targets.get(el); - if (t?.accepts(type)) return t; + if (t?.accepts(data.type, data)) return t; } return null; } @@ -98,12 +98,12 @@ export function dragSession(data: DragData): DragSession { }; return { move(x, y) { - enter(targetAt(data.type, x, y)); + enter(targetAt(data, x, y)); current?.over(data, x, y); return !!current; }, drop(x, y) { - const t = targetAt(data.type, x, y); + const t = targetAt(data, x, y); enter(null); t?.drop(data, x, y); return !!t; diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index f108aac8d0..fac591f975 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -153,6 +153,14 @@ export interface EditorKindContribution { * tab keeps running; `useEditorShown` tells it whether it is the one shown. */ keepAlive?: boolean; + /** + * Its input owns one live view (e.g. a terminal session's DOM + PTY) and cannot appear in + * two panes at once: splitting or "Open in Opposite Group" opens a fresh input from + * `splitInput`, or moves the tab instead. + */ + singleton?: boolean; + /** Fresh input opened when splitting a `singleton` tab (e.g. a new shell in the same cwd). */ + splitInput?(input: EditorInput): EditorInput | Promise | null; /** Last tab showing this input closed (including split tabs and tab-limit eviction). */ 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. */ @@ -716,6 +724,15 @@ export const OWNS_FILE_DROP = { "data-owns-file-drop": "" } as const; // Services implemented by one feature and consumed by others. The provider // calls `provide*` during activation; consumers call through the accessor. +export type EditorDropEdge = "left" | "right" | "top" | "bottom"; + +export interface EditorDropTarget { + paneId: string; + zone: EditorDropEdge | "center"; + index?: number; + pinned?: boolean; +} + export interface OpenOptions { /** Select / reveal this range (0-based line, UTF-16 col). */ selection?: { line: number; col: number; endLine?: number; endCol?: number }; @@ -723,8 +740,14 @@ export interface OpenOptions { preview?: boolean; /** Open to the side (split right). */ side?: boolean; + /** Split `pane` (or the active pane) at this edge and open in the new group. */ + edge?: EditorDropEdge; /** Open in this editor pane, in a tab of its own even when another pane shows the file. */ pane?: string; + /** 0-based insertion index in the target pane's tab strip. */ + index?: number; + /** Open as a pinned tab (e.g. dropped onto the pinned tabs row). */ + pinned?: boolean; focus?: boolean; /** Open in the text editor even when a file editor provider claims the file (SVG as text). */ asText?: boolean; @@ -1050,13 +1073,15 @@ export function registerCommitCheckProvider(p: CommitCheckProvider): () => void } /** - * Handles a pointer drag dropped on the editor content: features register handlers for - * their own drag types (e.g. an agent task dragged from the tool window) without the - * editor depending on them. The editor shows its center drop-zone for accepted types. + * Handles a pointer drag dropped on the editor area (a tab strip, a pane, or an edge split): + * features register handlers for their own drag types (e.g. an agent task or a terminal tab + * dragged from a tool window) without the editor depending on them. */ export interface EditorDropHandler { - accepts(type: string): boolean; - drop(data: DragData): void; + accepts(type: string, data?: DragData): boolean; + /** Whether dropping near an editor pane's edge splits off a new group on that side. */ + allowSplit?: boolean; + drop(data: DragData, target?: EditorDropTarget): void; } const editorDropHandlers: EditorDropHandler[] = []; @@ -1070,16 +1095,21 @@ export function registerEditorDropHandler(handler: EditorDropHandler): () => voi }; } -/** Whether any registered handler takes this drag type. */ -export function acceptsEditorDrop(type: string): boolean { - return editorDropHandlers.some((h) => h.accepts(type)); +/** Whether any registered handler takes this drag. */ +export function acceptsEditorDrop(type: string, data?: DragData): boolean { + return editorDropHandlers.some((h) => h.accepts(type, data)); } -/** Hands a drag dropped on editor content to its registered handler, if any. */ -export function dropOnEditor(data: DragData): boolean { - const handler = editorDropHandlers.find((h) => h.accepts(data.type)); +/** Whether the handler taking this drag supports edge-split drop zones. */ +export function editorDropAllowsSplit(type: string, data?: DragData): boolean { + return !!editorDropHandlers.find((h) => h.accepts(type, data))?.allowSplit; +} + +/** Hands a drag dropped on the editor to its registered handler, if any. */ +export function dropOnEditor(data: DragData, target?: EditorDropTarget): boolean { + const handler = editorDropHandlers.find((h) => h.accepts(data.type, data)); if (!handler) return false; - handler.drop(data); + handler.drop(data, target); return true; }