From 882bdf2219a8cbf6318fe21842348a1ebaed8cfe Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:43:01 -0500 Subject: [PATCH 1/2] feat(web): a Terminals page for shells tied to no chat (#1017) The rail gets a Terminals destination: a full-width page of terminal tabs and split panes that belong to no thread. "New tabs in" in the title row picks the project the next tab or split starts in, grouped under each computer's name; picking a project on another computer shows that computer's tabs. Each tab names its folder. Shells keep running while you browse threads, and nothing there starts an agent or makes a chat. Each server keeps its page's tabs under one reserved terminal thread id (TERMINALS_PAGE_THREAD_ID, "terminals-page"); requireThreadAbsent refuses to create a thread with it. Tab lists, history and "Run again" after a restart work as they do for a thread. The client keeps the page's layout through orphan cleanup and applies its terminal events with no thread behind them; removing a computer drops it. The thread drawer is unchanged for users. Its store wiring moves into a shared ManagedTerminalDrawer, the kill/restart question into TerminalStopConfirmDialog, and killing a tab into killTerminalTab; the drawer gains a page layout (fills the page, no hide or height edge, splits stack on phones, no "Restart here", no "Add to chat"). Killing a tab now also drops it from the local copy of the server's list, so an old list can't bring it back. Also: Cmd/Ctrl+Shift+J (navigate.terminals), the command palette (Open Terminals, and the terminal actions while the page is open), the desktop Go menu, the port-in-use notice's Show for a holder on the page, the app guide's Terminals place and topic, and docs/terminal.md. --- .../src/window/DesktopApplicationMenu.ts | 2 + apps/desktop/src/window/DesktopWindow.ts | 1 + apps/server/src/guide/topics.ts | 10 + .../orchestration/commandInvariants.test.ts | 27 + .../src/orchestration/commandInvariants.ts | 22 +- apps/web/src/components/AppSidebarLayout.tsx | 8 + .../src/components/ChatView.shell.browser.tsx | 105 +++ apps/web/src/components/ChatView.tsx | 322 ++------- .../src/components/CommandPaletteDialog.tsx | 58 +- .../ThreadTerminalDrawer.browser.tsx | 23 + .../src/components/ThreadTerminalDrawer.tsx | 177 +++-- .../src/components/sidebar/NavigationRail.tsx | 40 +- .../components/sidebar/destinationLists.tsx | 1 + .../sidebar/navigationRail.logic.test.ts | 1 + .../sidebar/navigationRail.logic.ts | 9 +- .../terminal/ManagedTerminalDrawer.tsx | 244 +++++++ .../terminal/TerminalPortNotice.tsx | 25 +- .../terminal/TerminalStopConfirmDialog.tsx | 89 +++ .../components/terminal/TerminalTabStrip.tsx | 15 +- .../components/terminal/terminalTabActions.ts | 34 + .../components/terminals/TerminalsPage.tsx | 649 ++++++++++++++++++ .../terminals/terminalsPage.logic.ts | 80 +++ .../src/environments/runtime/service.test.ts | 11 + apps/web/src/environments/runtime/service.ts | 19 +- apps/web/src/lib/terminalStateCleanup.test.ts | 16 +- apps/web/src/lib/terminalStateCleanup.ts | 9 + apps/web/src/routeTree.gen.ts | 21 + apps/web/src/routes/_chat.terminals.tsx | 9 + apps/web/src/terminalStateStore.ts | 11 + docs/terminal.md | 38 +- packages/contracts/src/keybindings.ts | 1 + packages/contracts/src/terminal.ts | 6 + packages/shared/src/appPlaces.ts | 9 + packages/shared/src/keybindings.ts | 1 + 34 files changed, 1733 insertions(+), 360 deletions(-) create mode 100644 apps/web/src/components/terminal/ManagedTerminalDrawer.tsx create mode 100644 apps/web/src/components/terminal/TerminalStopConfirmDialog.tsx create mode 100644 apps/web/src/components/terminal/terminalTabActions.ts create mode 100644 apps/web/src/components/terminals/TerminalsPage.tsx create mode 100644 apps/web/src/components/terminals/terminalsPage.logic.ts create mode 100644 apps/web/src/routes/_chat.terminals.tsx diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index fce35d6d1..a9678ee4b 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -21,6 +21,7 @@ type GoMenuAction = | typeof DesktopWindow.OPEN_FLEET_MENU_ACTION | typeof DesktopWindow.OPEN_SCHEDULED_MENU_ACTION | typeof DesktopWindow.OPEN_GENERAL_CHATS_MENU_ACTION + | typeof DesktopWindow.OPEN_TERMINALS_MENU_ACTION | typeof DesktopWindow.OPEN_USAGE_MENU_ACTION; export const GITHUB_REPOSITORY_URL = "https://github.com/Threadlines/threadlines"; @@ -287,6 +288,7 @@ const make = Effect.gen(function* () { { label: "Forward", click: goTo(DesktopWindow.NAVIGATE_FORWARD_MENU_ACTION) }, { type: "separator" }, { label: "General Chats", click: goTo(DesktopWindow.OPEN_GENERAL_CHATS_MENU_ACTION) }, + { label: "Terminals", click: goTo(DesktopWindow.OPEN_TERMINALS_MENU_ACTION) }, { label: "Fleet", click: goTo(DesktopWindow.OPEN_FLEET_MENU_ACTION) }, { label: "Scheduled", click: goTo(DesktopWindow.OPEN_SCHEDULED_MENU_ACTION) }, { label: "Usage", click: goTo(DesktopWindow.OPEN_USAGE_MENU_ACTION) }, diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 6b2c37943..c94b90d1f 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -97,6 +97,7 @@ export const OPEN_SCREEN_CLIP_MENU_ACTION = "open-screen-clip"; /** Renderer actions the Go menu and the tray send; the app shell navigates on them. */ export const OPEN_FLEET_MENU_ACTION = "open-fleet"; export const OPEN_SCHEDULED_MENU_ACTION = "open-scheduled"; +export const OPEN_TERMINALS_MENU_ACTION = "open-terminals"; export const OPEN_GENERAL_CHATS_MENU_ACTION = "open-general-chats"; export const OPEN_USAGE_MENU_ACTION = "open-usage"; /** Opens one thread: the tray's thread rows and links to a thread send it. */ diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 372b84a0b..1f1595f3d 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -393,6 +393,16 @@ The project menu's Project brief and notes, the command palette and the lead cha Show device toolbar, in the browser's options menu (⋮), sets the page's size: Responsive fills the panel, and a Phone, Tablet, Laptop or Desktop size shrinks to fit it. New tabs open at {place:general.browserPageSize}, which the size menu can also set. Words typed in the browser's address bar are searched for, with the search engine set in {place:general.browserSearchEngine}. An address loads as it always did.`, + }, + { + id: "terminals", + title: "Terminals", + keywords: ["terminal", "shell", "split", "dev server", "tabs", "command line", "console"], + body: `Each thread has a terminal drawer under the chat (Cmd+J, Ctrl+J on Windows and Linux): its tabs start in the thread's folder and belong to that thread. + +{place:terminals} (the rail button, or Cmd+Shift+J) holds terminals tied to no chat, for running a web server and an API side by side. "New tabs in" at the top picks the project the next tab or split starts in; each tab names its folder, and picking another project leaves open tabs where they are. Nothing there starts an agent or a chat. + +Every computer has its own set: the menu groups projects under each computer's name, and picking one on another computer shows that computer's tabs. Shells run on that computer and keep running while you look at threads; quitting or restarting Threadlines there stops them, and a command that was running is offered again. Killing a tab stops its shell and drops its output. A computer that's offline shows its tabs again once it's back.`, }, { id: "device-tab", diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts index 9cefc6f87..3febe2d74 100644 --- a/apps/server/src/orchestration/commandInvariants.test.ts +++ b/apps/server/src/orchestration/commandInvariants.test.ts @@ -10,6 +10,7 @@ import { ProviderInstanceId, EMPTY_AGENT_REQUEST_STATE, EMPTY_CHILD_REQUEST_STATE, + TERMINALS_PAGE_THREAD_ID, } from "@threadlines/contracts"; import * as Effect from "effect/Effect"; @@ -227,6 +228,32 @@ describe("commandInvariants", () => { }), ), ).rejects.toThrow("already exists"); + + // The Terminals page's tabs live under this id; no thread may take it. + await expect( + Effect.runPromise( + requireThreadAbsent({ + readModel, + command: { + type: "thread.create", + commandId: CommandId.make("cmd-4"), + threadId: ThreadId.make(TERMINALS_PAGE_THREAD_ID), + projectId: ProjectId.make("project-a"), + title: "reserved", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + }, + threadId: ThreadId.make(TERMINALS_PAGE_THREAD_ID), + }), + ), + ).rejects.toThrow("is reserved"); }); it("requires non-negative integers", async () => { diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts index 90ed771b9..879cc6f42 100644 --- a/apps/server/src/orchestration/commandInvariants.ts +++ b/apps/server/src/orchestration/commandInvariants.ts @@ -1,10 +1,11 @@ -import type { - OrchestrationCommand, - OrchestrationProject, - OrchestrationReadModel, - OrchestrationThread, - ProjectId, - ThreadId, +import { + type OrchestrationCommand, + type OrchestrationProject, + type OrchestrationReadModel, + type OrchestrationThread, + type ProjectId, + TERMINALS_PAGE_THREAD_ID, + type ThreadId, } from "@threadlines/contracts"; import { projectLeadThreadId } from "@threadlines/shared/projectLead"; import * as Effect from "effect/Effect"; @@ -206,6 +207,13 @@ export function requireThreadAbsent(input: { readonly command: OrchestrationCommand; readonly threadId: ThreadId; }): Effect.Effect { + // The Terminals page keeps its tabs under this id; a thread with it would + // share them. + if (input.threadId === TERMINALS_PAGE_THREAD_ID) { + return Effect.fail( + invariantError(input.command.type, `Thread id '${input.threadId}' is reserved.`), + ); + } if (!findThreadById(input.readModel, input.threadId)) { return Effect.void; } diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 2a312aa6c..21aeda9c9 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -111,6 +111,11 @@ function AppShellCommands({ hasList }: { readonly hasList: boolean }) { event.stopPropagation(); void navigate({ to: "/scheduled" }); } + if (command === "navigate.terminals") { + event.preventDefault(); + event.stopPropagation(); + void navigate({ to: "/terminals" }); + } }; window.addEventListener("keydown", onWindowKeyDown); return () => { @@ -135,6 +140,9 @@ function AppShellCommands({ hasList }: { readonly hasList: boolean }) { case "open-scheduled": void navigate({ to: "/scheduled" }); return; + case "open-terminals": + void navigate({ to: "/terminals" }); + return; case "open-general-chats": void navigate({ to: "/chats" }); return; diff --git a/apps/web/src/components/ChatView.shell.browser.tsx b/apps/web/src/components/ChatView.shell.browser.tsx index 269909024..c95891437 100644 --- a/apps/web/src/components/ChatView.shell.browser.tsx +++ b/apps/web/src/components/ChatView.shell.browser.tsx @@ -6,6 +6,7 @@ import { type OrchestrationEvent, type OrchestrationReadModel, type ScheduledTaskId, + TERMINALS_PAGE_THREAD_ID, type ThreadId, WS_METHODS, } from "@threadlines/contracts"; @@ -26,6 +27,7 @@ import { THREAD_ID, THREAD_TITLE, PROJECT_ID, + SECOND_PROJECT_ID, LOCAL_ENVIRONMENT_ID, THREAD_REF, PROJECT_LOGICAL_KEY, @@ -562,6 +564,109 @@ describe("ChatView (full app): app shell", () => { } }); + it("opens terminals in two projects side by side and leaves them running while browsing", async () => { + const base = createSnapshotForTargetUser({ + targetMessageId: MessageId.make("terminals-page"), + targetText: "Start the web and API servers.", + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...base, + projects: [ + ...base.projects, + { + ...base.projects[0]!, + id: SECOND_PROJECT_ID, + title: "Backend", + workspaceRoot: "/repo/backend", + }, + ], + }, + }); + const opened = () => + wsRequests.filter( + (request) => + request._tag === WS_METHODS.terminalOpen && request.threadId === TERMINALS_PAGE_THREAD_ID, + ); + const panes = () => document.querySelectorAll(".thread-terminal-drawer .xterm").length; + + try { + await page.getByTestId("rail-terminals").click(); + await waitForURL(mounted.router, (pathname) => pathname === "/terminals", "Terminals."); + // Visiting starts no shell; the first tab is asked for. + expect(opened()).toEqual([]); + await page.getByRole("button", { name: "New terminal", exact: true }).click(); + await vi.waitFor(() => + expect(opened()).toEqual([expect.objectContaining({ cwd: "/repo/project" })]), + ); + await page.getByRole("button", { name: /^Project for new terminals/ }).click(); + await page.getByRole("menuitem", { name: /Backend/ }).click(); + await page.getByRole("button", { name: /^Split terminal/ }).click(); + await vi.waitFor(() => { + expect(opened()).toContainEqual(expect.objectContaining({ cwd: "/repo/backend" })); + expect(panes()).toBe(2); + }); + // Each tab names its folder. + await expect + .element(page.getByRole("tab", { name: /^Backend\s+Terminal 2/ })) + .toBeInTheDocument(); + + await page.getByTestId("rail-threads").click(); + await waitForURL(mounted.router, (pathname) => pathname !== "/terminals", "Threads."); + await page.getByTestId("rail-terminals").click(); + await vi.waitFor(() => expect(panes()).toBe(2)); + expect(wsRequests.some((request) => request._tag === WS_METHODS.terminalClose)).toBe(false); + } finally { + await mounted.cleanup(); + } + }); + + it("killing the Terminals page's last tab leaves it empty, without a new shell", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: MessageId.make("terminals-page-kill"), + targetText: "One terminal.", + }), + }); + const pageRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, TERMINALS_PAGE_THREAD_ID as ThreadId); + const opened = () => + wsRequests.filter( + (request) => + request._tag === WS_METHODS.terminalOpen && request.threadId === TERMINALS_PAGE_THREAD_ID, + ); + + try { + await page.getByTestId("rail-terminals").click(); + await page.getByRole("button", { name: "New terminal", exact: true }).click(); + await vi.waitFor(() => expect(opened()).toHaveLength(1)); + const terminalId = String(opened()[0]!.terminalId); + // The server lists the tab, and still does for a moment after the kill. + useTerminalStateStore.getState().applyTerminalTabs(pageRef, [ + { + terminalId, + number: 1, + cwd: "/repo/project", + status: "running", + exitCode: null, + exitSignal: null, + createdAt: NOW_ISO, + }, + ]); + await page.getByRole("button", { name: /^Kill .*Terminal 1/ }).click(); + await expect + .element(page.getByRole("button", { name: "New terminal", exact: true })) + .toBeInTheDocument(); + await vi.waitFor(() => + expect(wsRequests.some((request) => request._tag === WS_METHODS.terminalClose)).toBe(true), + ); + expect(opened()).toHaveLength(1); + } finally { + await mounted.cleanup(); + } + }); + it("counts the pull requests waiting on the user on the rail", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 8c05d6f65..ab0128af3 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -61,17 +61,7 @@ import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { Debouncer } from "@tanstack/react-pacer"; import { useQueryClient } from "@tanstack/react-query"; import * as Option from "effect/Option"; -import { - lazy, - memo, - Suspense, - useCallback, - useEffect, - useEffectEvent, - useMemo, - useRef, - useState, -} from "react"; +import { memo, useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; import { useNavigate, useSearch } from "@tanstack/react-router"; import { useShallow } from "zustand/react/shallow"; import { useGitStatus } from "~/lib/gitStatusState"; @@ -296,13 +286,20 @@ import { selectTerminalActivityStartedAt, selectTerminalTabs, noteTerminalMadeOnServer, - terminalKey, - terminalLineRecentlyEntered, terminalTabNumbers, selectThreadTerminalState, useTerminalStateStore, } from "../terminalStateStore"; -import { dropTerminalBuffer, useTerminalThreadStream } from "../terminalStreams"; +import { dropTerminalBuffer } from "../terminalStreams"; +import { killTerminalTab } from "./terminal/terminalTabActions"; +import { + TerminalStopConfirmDialog, + terminalStopNeedsConfirm, +} from "./terminal/TerminalStopConfirmDialog"; +import { + ManagedTerminalDrawer, + type ManagedTerminalDrawerProps, +} from "./terminal/ManagedTerminalDrawer"; import { type TerminalCommandKind, useTerminalCommandsStore } from "../terminalCommands"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { McpAppSidePanel } from "./chat/McpAppCard"; @@ -414,7 +411,6 @@ import { revokeBlobPreviewUrl, revokeUserMessagePreviewUrls, shouldRefreshThreadDetailAfterEventLoopStall, - shouldConfirmTerminalKill, shouldOfferFailedTurnRetry, shouldWriteThreadErrorToCurrentServerThread, THREAD_DETAIL_STALL_PROBE_INTERVAL_MS, @@ -502,10 +498,6 @@ import { resolveComposerProviderSelection, } from "../providerInstances"; -// Lazy so @xterm/xterm (and the drawer's terminal machinery) stays out of -// the entry chunk; the drawer only mounts once a terminal is opened. -const ThreadTerminalDrawer = lazy(() => import("./ThreadTerminalDrawer")); - const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]"; const EMPTY_WORKFLOW_RUNS: ReadonlyArray = []; @@ -961,19 +953,16 @@ function sameItems(left: ReadonlyArray, right: ReadonlyArray): boolean return left.length === right.length && left.every((item, index) => item === right[index]); } -interface PersistentThreadTerminalDrawerProps { - threadRef: { environmentId: EnvironmentId; threadId: ThreadId }; - threadId: ThreadId; - visible: boolean; - focusRequestId: number; - findRequested: boolean; - onFindRequestHandled: () => void; - splitShortcutLabel: string | undefined; - newShortcutLabel: string | undefined; - closeShortcutLabel: string | undefined; - hideShortcutLabel: string | undefined; - findShortcutLabel: string | undefined; - keybindings: ResolvedKeybindingsConfig; +interface PersistentThreadTerminalDrawerProps extends Omit< + ManagedTerminalDrawerProps, + | "layout" + | "cwd" + | "worktreePath" + | "runtimeEnv" + | "onCloseTerminal" + | "onRestartTerminal" + | "onAddTerminalContext" +> { onAddTerminalContext: (selection: TerminalContextSelection) => void; onCloseTerminal: ( threadRef: { environmentId: EnvironmentId; threadId: ThreadId }, @@ -986,29 +975,15 @@ interface PersistentThreadTerminalDrawerProps { threadId: ThreadId, terminalId: string, ) => void; - onHideTerminal: () => void; } -const EMPTY_TERMINAL_COMMANDS: ReadonlyMap = new Map(); - +/** A thread's terminal drawer: new tabs start in the thread's folder now. */ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({ - threadRef, - threadId, - visible, - focusRequestId, - findRequested, - onFindRequestHandled, - splitShortcutLabel, - newShortcutLabel, - closeShortcutLabel, - hideShortcutLabel, - findShortcutLabel, - keybindings, - onAddTerminalContext, onCloseTerminal, onRestartTerminal, - onHideTerminal, + ...props }: PersistentThreadTerminalDrawerProps) { + const { threadRef } = props; const serverThread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef])); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); const projectRef = serverThread @@ -1017,23 +992,6 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) : null; const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef])); - const terminalState = useTerminalStateStore((state) => - selectThreadTerminalState(state.terminalStateByThreadKey, threadRef), - ); - const terminalTabs = useTerminalStateStore((state) => - selectTerminalTabs(state.terminalTabsByThreadKey, threadRef), - ); - const terminalActivityCommandByKey = useTerminalStateStore( - (state) => state.terminalActivityCommandByKey, - ); - const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight); - const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal); - const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal); - const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal); - const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal); - const terminalFontSize = useSettings((settings) => settings.terminalFontSize); - const terminalScreenReaderMode = useSettings((settings) => settings.terminalScreenReaderMode); - const [localFocusRequestId, setLocalFocusRequestId] = useState(0); const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; const threadEffectiveCwd = serverThread?.effectiveCwd ?? null; // Where a new tab starts: the thread's folder now. A tab that exists stays @@ -1059,137 +1017,31 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra : {}, [project, worktreePath], ); - const drawerShown = Boolean(project && terminalState.terminalOpen && cwd); - // This thread's output comes only while its drawer is mounted. - const stream = useTerminalThreadStream(threadRef.environmentId, threadId, drawerShown); - const commandByTerminalId = useMemo(() => { - if (Object.keys(terminalActivityCommandByKey).length === 0) return EMPTY_TERMINAL_COMMANDS; - const commands = new Map(); - for (const terminalId of terminalState.terminalIds) { - const command = terminalActivityCommandByKey[terminalKey(threadRef, terminalId)]; - if (command) commands.set(terminalId, command); - } - return commands; - }, [terminalActivityCommandByKey, terminalState.terminalIds, threadRef]); - - const bumpFocusRequestId = useCallback(() => { - if (!visible) { - return; - } - setLocalFocusRequestId((value) => value + 1); - }, [visible]); - - const setTerminalHeight = useCallback( - (height: number) => { - storeSetTerminalHeight(threadRef, height); - }, - [storeSetTerminalHeight, threadRef], - ); - - const splitTerminal = useCallback(() => { - storeSplitTerminal(threadRef, `terminal-${randomUUID()}`); - bumpFocusRequestId(); - }, [bumpFocusRequestId, storeSplitTerminal, threadRef]); - - const createNewTerminal = useCallback(() => { - storeNewTerminal(threadRef, `terminal-${randomUUID()}`); - bumpFocusRequestId(); - }, [bumpFocusRequestId, storeNewTerminal, threadRef]); - - const activateTerminal = useCallback( - (terminalId: string) => { - storeSetActiveTerminal(threadRef, terminalId); - bumpFocusRequestId(); - }, - [bumpFocusRequestId, storeSetActiveTerminal, threadRef], - ); - const closeTerminal = useCallback( - (terminalId: string, options?: { sessionExited?: boolean }) => { - onCloseTerminal(threadRef, threadId, terminalId, options); - bumpFocusRequestId(); - }, - [bumpFocusRequestId, onCloseTerminal, threadId, threadRef], - ); - - const forgetTerminal = useCallback( - (terminalId: string) => { - storeCloseTerminal(threadRef, terminalId); - dropTerminalBuffer(threadRef.environmentId, threadId, terminalId); - }, - [storeCloseTerminal, threadId, threadRef], + (targetThreadRef: ScopedThreadRef, terminalId: string, options?: { sessionExited?: boolean }) => + onCloseTerminal(targetThreadRef, targetThreadRef.threadId, terminalId, options), + [onCloseTerminal], ); - const restartTerminal = useCallback( - (terminalId: string) => onRestartTerminal(threadRef, threadId, terminalId), - [onRestartTerminal, threadId, threadRef], + (targetThreadRef: ScopedThreadRef, terminalId: string) => + onRestartTerminal(targetThreadRef, targetThreadRef.threadId, terminalId), + [onRestartTerminal], ); - const clearTerminal = useCallback( - (terminalId: string) => { - const api = readEnvironmentApi(threadRef.environmentId); - void api?.terminal.clear({ threadId, terminalId }).catch(() => undefined); - }, - [threadId, threadRef], - ); - - const handleAddTerminalContext = useCallback( - (selection: TerminalContextSelection) => { - if (!visible) { - return; - } - onAddTerminalContext(selection); - }, - [onAddTerminalContext, visible], - ); - - if (!project || !terminalState.terminalOpen || !cwd) { + if (!project || !cwd) { return null; } return ( -
- - - -
+ ); }); @@ -1431,7 +1283,6 @@ export default function ChatView(props: ChatViewProps) { const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal); const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal); const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal); - const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal); const removeComposerDraftTerminalContextsForTerminal = useComposerDraftStore( (store) => store.removeTerminalContextsForTerminal, ); @@ -3697,39 +3548,11 @@ export default function ChatView(props: ChatViewProps) { targetThreadId: ThreadId, terminalId: string, ) => { - const api = readEnvironmentApi(targetThreadRef.environmentId); - if (!api) return; - const targetTerminalState = selectThreadTerminalState( - useTerminalStateStore.getState().terminalStateByThreadKey, - targetThreadRef, - ); - const isFinalTerminal = targetTerminalState.terminalIds.length <= 1; - const fallbackExitWrite = () => - api.terminal - .write({ threadId: targetThreadId, terminalId, data: "exit\n" }) - .catch(() => undefined); - if ("close" in api.terminal && typeof api.terminal.close === "function") { - void (async () => { - if (isFinalTerminal) { - await api.terminal - .clear({ threadId: targetThreadId, terminalId }) - .catch(() => undefined); - } - await api.terminal.close({ - threadId: targetThreadId, - terminalId, - deleteHistory: true, - }); - })().catch(() => fallbackExitWrite()); - } else { - void fallbackExitWrite(); - } - storeCloseTerminal(targetThreadRef, terminalId); - dropTerminalBuffer(targetThreadRef.environmentId, targetThreadId, terminalId); + if (!killTerminalTab(targetThreadRef, terminalId)) return; removeComposerDraftTerminalContextsForTerminal(targetThreadRef, terminalId); setTerminalFocusRequestId((value) => value + 1); }, - [removeComposerDraftTerminalContextsForTerminal, storeCloseTerminal], + [removeComposerDraftTerminalContextsForTerminal], ); // A new shell in the thread's folder now, below the old one's output. const performRestartTerminal = useCallback( @@ -3776,31 +3599,13 @@ export default function ChatView(props: ChatViewProps) { threadId: ThreadId; terminalId: string; } | null>(null); - /** Whether stopping this tab's shell would stop something. */ - const isTerminalBusy = useCallback( - (targetThreadRef: { environmentId: EnvironmentId; threadId: ThreadId }, terminalId: string) => { - const store = useTerminalStateStore.getState(); - return shouldConfirmTerminalKill({ - runningTerminalIds: selectThreadTerminalState( - store.terminalStateByThreadKey, - targetThreadRef, - ).runningTerminalIds, - terminalId, - commandPending: - store.terminalCommandPendingByKey[terminalKey(targetThreadRef, terminalId)] === true || - terminalLineRecentlyEntered(targetThreadRef, terminalId), - sessionExited: false, - }); - }, - [], - ); const requestRestartTerminal = useCallback( ( targetThreadRef: { environmentId: EnvironmentId; threadId: ThreadId }, targetThreadId: ThreadId, terminalId: string, ) => { - if (isTerminalBusy(targetThreadRef, terminalId)) { + if (terminalStopNeedsConfirm(targetThreadRef, terminalId)) { setPendingTerminalAction({ kind: "restart", threadRef: targetThreadRef, @@ -3811,7 +3616,7 @@ export default function ChatView(props: ChatViewProps) { } performRestartTerminal(targetThreadRef, targetThreadId, terminalId); }, - [isTerminalBusy, performRestartTerminal], + [performRestartTerminal], ); const requestCloseTerminal = useCallback( ( @@ -3820,7 +3625,10 @@ export default function ChatView(props: ChatViewProps) { terminalId: string, options?: { sessionExited?: boolean }, ) => { - if (options?.sessionExited !== true && isTerminalBusy(targetThreadRef, terminalId)) { + if ( + options?.sessionExited !== true && + terminalStopNeedsConfirm(targetThreadRef, terminalId) + ) { setPendingTerminalAction({ kind: "kill", threadRef: targetThreadRef, @@ -3831,7 +3639,7 @@ export default function ChatView(props: ChatViewProps) { } performCloseTerminal(targetThreadRef, targetThreadId, terminalId); }, - [isTerminalBusy, performCloseTerminal], + [performCloseTerminal], ); // A tool call the thread already tracks as an agent is not a separate // background run. History is consulted alongside the live turn so a promoted @@ -9430,7 +9238,6 @@ export default function ChatView(props: ChatViewProps) { ))} - { - if (!open) setPendingTerminalAction(null); - }} - > - - - - {pendingTerminalAction?.kind === "restart" ? "Restart terminal?" : "Kill terminal?"} - - - {pendingTerminalAction?.kind === "restart" - ? "Something is still running in this terminal. Restarting stops it and starts a new shell in the thread's folder, below what it printed." - : "A process is still running in this terminal. Killing the terminal stops the process and discards the terminal history. To keep it running, hide the terminal instead."} - - - - }>Cancel - - - - + setPendingTerminalAction(null)} + /> {previewedFile && } ); diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index 30c1538be..3fcfe4839 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -585,6 +585,9 @@ export function OpenCommandPaletteDialog() { const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); const keybindings = useServerKeybindings(); const isHomeRoute = useLocation({ select: (location) => location.pathname === "/" }); + const onTerminalsPage = useLocation({ + select: (location) => location.pathname === "/terminals", + }); const isMobile = useIsMobile(); const sidebarListOpen = useUiStateStore(selectSidebarListShown); const [viewStack, setViewStack] = useState([]); @@ -1832,6 +1835,21 @@ export function OpenCommandPaletteDialog() { }, }); + if (!onTerminalsPage) { + actionItems.push({ + kind: "action", + value: "action:terminals", + searchTerms: ["terminals", "terminal", "shell", "shells", "split terminal", "dev server"], + title: "Open Terminals", + description: "Terminal tabs for any project, outside a chat", + icon: , + shortcutCommand: "navigate.terminals", + run: async () => { + await navigate({ to: "/terminals" }); + }, + }); + } + actionItems.push({ kind: "action", value: "action:fleet", @@ -2105,9 +2123,9 @@ export function OpenCommandPaletteDialog() { }); } - // The terminal's actions, for the thread on screen (its drawer does them, - // with the same confirmations as its own buttons). - if (activeThread || activeDraftThread) { + // The terminal's actions, for the thread on screen or the Terminals page + // (its drawer does them, with the same confirmations as its own buttons). + if (activeThread || activeDraftThread || onTerminalsPage) { const terminalActions: ReadonlyArray<{ readonly kind: TerminalCommandKind; readonly title: string; @@ -2116,18 +2134,30 @@ export function OpenCommandPaletteDialog() { readonly icon: ReactNode; readonly shortcutCommand?: KeybindingCommand; }> = [ - { - kind: "toggle", - title: "Toggle terminal", - description: "Show or hide this thread's terminal", - searchTerms: ["terminal", "toggle terminal", "show terminal", "hide terminal", "shell"], - icon: , - shortcutCommand: "terminal.toggle", - }, + ...(onTerminalsPage + ? [] + : [ + { + kind: "toggle", + title: "Toggle terminal", + description: "Show or hide this thread's terminal", + searchTerms: [ + "terminal", + "toggle terminal", + "show terminal", + "hide terminal", + "shell", + ], + icon: , + shortcutCommand: "terminal.toggle", + } as const, + ]), { kind: "new", title: "New terminal tab", - description: "Open another terminal for this thread", + description: onTerminalsPage + ? "Open a terminal in the project picked for new tabs" + : "Open another terminal for this thread", searchTerms: ["new terminal", "terminal tab", "open terminal", "shell"], icon: , shortcutCommand: "terminal.new", @@ -2151,7 +2181,9 @@ export function OpenCommandPaletteDialog() { { kind: "restart", title: "Restart terminal", - description: "A new shell in the thread's folder, below the old output", + description: onTerminalsPage + ? "A new shell in the same folder, below the old output" + : "A new shell in the thread's folder, below the old output", searchTerms: ["restart terminal", "reset terminal", "new shell", "terminal"], icon: , }, diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx index 0f715494c..6eed8b365 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx @@ -386,6 +386,7 @@ type ViewportOverrides = Partial< Pick< Parameters[0], | "cwd" + | "followsFolder" | "launchCwd" | "interruptedCommand" | "portInUse" @@ -413,6 +414,7 @@ function ViewportUnderTest( terminalId="default" terminalLabel="Terminal" cwd={props.cwd ?? "/repo/project"} + followsFolder={props.followsFolder ?? true} launchCwd={props.launchCwd ?? null} interruptedCommand={props.interruptedCommand ?? null} portInUse={props.portInUse ?? null} @@ -1154,6 +1156,26 @@ describe("TerminalViewport", () => { } }); + it("never asks a Terminals page tab to move: no folder follows it there", async () => { + const environment = createEnvironmentApi({ cwd: "/repo/web" }); + const threadRef = scopeThreadRef("environment-a" as never, THREAD_ID); + environmentApiById.set("environment-a", environment); + const mounted = await mountTerminalViewport({ + threadRef, + // The page's pick for new tabs is another project now. + cwd: "/repo/api", + followsFolder: false, + }); + + try { + await vi.waitFor(() => expect(environment.terminal.open).toHaveBeenCalled()); + await expect.element(page.getByText("Started in", { exact: false })).not.toBeInTheDocument(); + expect(page.getByRole("button", { name: "Restart here" }).elements()).toHaveLength(0); + } finally { + await mounted.cleanup(); + } + }); + it("offers to run again what a restart stopped, or to forget it", async () => { const environment = createEnvironmentApi(); const threadRef = scopeThreadRef("environment-a" as never, THREAD_ID); @@ -1383,6 +1405,7 @@ describe("TerminalTabStrip", () => { command: null, exit: null, cwd: null, + folder: null, }); const screen = await render( void; + /** Absent where there is no chat (the Terminals page): Copy only. */ + onAddToChat: ((selection: TerminalContextSelection) => void) | null; onDismiss: (options?: { clearTerminalSelection?: boolean }) => void; }) { const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 1000, onCopy: () => onDismiss({ clearTerminalSelection: true }), }); - const position = resolveTerminalSelectionActionPopoverPosition({ position: action.position }); + const width = + onAddToChat === null + ? TERMINAL_SELECTION_COPY_POPOVER_WIDTH_PX + : TERMINAL_SELECTION_ACTION_POPOVER_WIDTH_PX; + const position = resolveTerminalSelectionActionPopoverPosition({ + position: action.position, + width, + }); return (
{ event.preventDefault(); @@ -406,16 +418,18 @@ function TerminalSelectionActionPopover({ Copy selected terminal text - + {onAddToChat !== null ? ( + + ) : null}
); } @@ -425,8 +439,13 @@ interface TerminalViewportProps { threadId: ThreadId; terminalId: string; terminalLabel: string; - /** The thread's folder: where a tab that has no shell yet starts one. */ + /** Where a tab that has no shell yet starts one: the thread's folder, or the page's pick. */ cwd: string; + /** + * Whether the drawer follows a thread's folder, so a shell started + * elsewhere offers "Restart here". The Terminals page has no such folder. + */ + followsFolder: boolean; /** Where this tab's shell last started, when the server keeps tab lists. */ launchCwd: string | null; /** The command a restart stopped in this tab, offered to run again. */ @@ -442,7 +461,8 @@ interface TerminalViewportProps { onGone: () => void; onRestart: () => void; onClose: () => void; - onAddTerminalContext: (selection: TerminalContextSelection) => void; + /** Null where there is no chat to add a selection to. */ + onAddTerminalContext: ((selection: TerminalContextSelection) => void) | null; focusRequestId: number; autoFocus: boolean; findOpen: boolean; @@ -460,6 +480,7 @@ export function TerminalViewport({ terminalId, terminalLabel, cwd, + followsFolder, launchCwd, interruptedCommand, portInUse, @@ -516,7 +537,7 @@ export function TerminalViewport({ const handleGone = useEffectEvent(() => onGone()); const handleFindOpen = useEffectEvent(() => onFindOpen()); const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => { - onAddTerminalContext(selection); + onAddTerminalContext?.(selection); }); const readTerminalLabel = useEffectEvent(() => terminalLabel); const readAutoFocus = useEffectEvent(() => autoFocus); @@ -1285,6 +1306,7 @@ export function TerminalViewport({ const ended = session !== null && (session.status === "exited" || session.status === "error"); const movedFrom = + followsFolder && session !== null && !ended && trimTrailingSeparators(session.cwd) !== trimTrailingSeparators(cwd) @@ -1382,7 +1404,7 @@ export function TerminalViewport({ {selectionAction ? ( ) : null} @@ -1404,9 +1426,21 @@ function fitIfShown(fitAddon: FitAddon, box: HTMLElement | null): boolean { return true; } +/** Where a tab the server doesn't list yet starts its shell, and with what environment. */ +export interface TerminalLaunch { + readonly cwd: string; + readonly runtimeEnv: Record; +} + interface ThreadTerminalDrawerProps { threadRef: ScopedThreadRef; threadId: ThreadId; + /** + * `drawer`: under a thread's chat, with a height edge and a hide button, + * following the thread's folder. `page`: the Terminals page, filling its + * parent; each tab names its folder and none follows another. + */ + layout?: "drawer" | "page"; cwd: string; worktreePath?: string | null; runtimeEnv?: Record; @@ -1430,7 +1464,12 @@ interface ThreadTerminalDrawerProps { screenReaderMode: boolean; onSplitTerminal: () => void; onNewTerminal: () => void; - onHideTerminal: () => void; + /** Absent on the Terminals page, which has nothing to hide into. */ + onHideTerminal?: (() => void) | undefined; + /** Where a tab the server doesn't list yet starts, when not at `cwd`. */ + launchFor?: ((terminalId: string) => TerminalLaunch | null) | undefined; + /** The folder a tab names before "Terminal N" (the Terminals page). */ + folderLabelFor?: ((terminalId: string, cwd: string | null) => string | null) | undefined; splitShortcutLabel?: string | undefined; newShortcutLabel?: string | undefined; closeShortcutLabel?: string | undefined; @@ -1443,7 +1482,8 @@ interface ThreadTerminalDrawerProps { onRestartTerminal: (terminalId: string) => void; onClearTerminal: (terminalId: string) => void; onHeightChange: (height: number) => void; - onAddTerminalContext: (selection: TerminalContextSelection) => void; + /** Null where there is no chat to add a selection to. */ + onAddTerminalContext: ((selection: TerminalContextSelection) => void) | null; keybindings: ResolvedKeybindingsConfig; } @@ -1481,6 +1521,7 @@ function HeaderIconButton({ export default function ThreadTerminalDrawer({ threadRef, threadId, + layout = "drawer", cwd, worktreePath, runtimeEnv, @@ -1502,6 +1543,8 @@ export default function ThreadTerminalDrawer({ onSplitTerminal, onNewTerminal, onHideTerminal, + launchFor, + folderLabelFor, splitShortcutLabel, newShortcutLabel, closeShortcutLabel, @@ -1629,18 +1672,22 @@ export default function ThreadTerminalDrawer({ group.terminalIds.map((terminalId): TerminalStripTab => { const tab = tabById.get(terminalId); const ended = tab !== undefined && (tab.status === "exited" || tab.status === "error"); + const tabCwd = tab?.cwd ?? launchFor?.(terminalId)?.cwd ?? null; return { terminalId, label: labelById.get(terminalId) ?? "Terminal", + folder: folderLabelFor?.(terminalId, tabCwd) ?? null, running: running.has(terminalId), command: running.has(terminalId) ? (commandByTerminalId.get(terminalId) ?? null) : null, exit: ended ? { code: tab.exitCode, signal: tab.exitSignal } : null, - cwd: tab?.cwd ?? null, + cwd: tabCwd, }; }), ); }, [ commandByTerminalId, + folderLabelFor, + launchFor, normalizedTerminalIds, resolvedTerminalGroups, runningTerminalIds, @@ -1790,20 +1837,24 @@ export default function ThreadTerminalDrawer({ }; }, [syncHeight]); + const isPage = layout === "page"; const renderViewport = (terminalId: string, autoFocus: boolean) => { const tab = tabById.get(terminalId); + const launch = launchFor?.(terminalId) ?? null; + const viewportEnv = launch?.runtimeEnv ?? runtimeEnv; return ( onCloseTerminal(terminalId, { sessionExited: true })} onGone={() => onForgetTerminal(terminalId)} @@ -1825,26 +1876,34 @@ export default function ThreadTerminalDrawer({ return (