From cbcdb8b390638d7a05f7b50e1f98e645215eb7ea Mon Sep 17 00:00:00 2001 From: asm <113964+asm@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:11:41 -0700 Subject: [PATCH 01/11] =?UTF-8?q?=F0=9F=A4=96=20feat:=20show=20the=20plan?= =?UTF-8?q?=20in=20a=20right=20sidebar=20Plan=20tab?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plan file was only viewable in the chat card or a modal behind Stats → Context. A Plan tab shows it next to the chat with the card's main actions, re-read when a turn ends or the window regains focus, and it keeps each workspace's scroll position across leaving and returning. "/plan open" and the Stats tab's plan row open the tab, and Ctrl/Cmd+Shift+B opens it on every layout. The modal viewer is removed. Co-Authored-By: Claude Fable 5.1 --- docs/agents/plan-mode.mdx | 8 + docs/config/keybinds.mdx | 3 +- .../WorkspaceMenuBar/WorkspaceMenuBar.tsx | 30 +++ .../WorkspaceShell/deferredSidebarInput.ts | 2 + .../features/RightSidebar/NewTabLauncher.tsx | 1 + .../RightSidebar/PlanFileDialog.stories.tsx | 100 -------- .../RightSidebar/PlanFileDialog.test.tsx | 179 ------------- .../features/RightSidebar/PlanFileDialog.tsx | 148 ----------- .../features/RightSidebar/PlanTab.stories.tsx | 101 ++++++++ .../features/RightSidebar/PlanTab.test.tsx | 242 ++++++++++++++++++ src/browser/features/RightSidebar/PlanTab.tsx | 188 ++++++++++++++ .../RightSidebar/PostCompactionSection.tsx | 17 +- .../features/RightSidebar/RightSidebar.tsx | 39 +++ .../features/RightSidebar/Tabs/TabLabels.tsx | 9 + .../features/RightSidebar/Tabs/tabConfig.ts | 7 + .../features/RightSidebar/Tabs/tabIcons.ts | 2 + .../RightSidebar/Tabs/tabRegistry.tsx | 12 + .../RightSidebar/dialogsReconnect.test.tsx | 18 +- .../features/RightSidebar/usePlanFile.ts | 87 +++++++ .../Settings/Sections/KeybindsSection.tsx | 2 + src/browser/utils/chatCommands.test.ts | 91 ++----- src/browser/utils/chatCommands.ts | 54 +--- src/browser/utils/commands/sources.ts | 13 +- src/browser/utils/latestPlanAction.ts | 18 ++ src/browser/utils/openPlanTab.ts | 10 + src/browser/utils/slashCommands/registry.ts | 2 +- src/browser/utils/ui/keybinds.test.ts | 1 + src/browser/utils/ui/keybinds.ts | 3 + src/common/constants/events.ts | 9 + src/common/constants/storage.ts | 11 + .../builtInSkillContent.generated.ts | 11 +- 31 files changed, 838 insertions(+), 580 deletions(-) delete mode 100644 src/browser/features/RightSidebar/PlanFileDialog.stories.tsx delete mode 100644 src/browser/features/RightSidebar/PlanFileDialog.test.tsx delete mode 100644 src/browser/features/RightSidebar/PlanFileDialog.tsx create mode 100644 src/browser/features/RightSidebar/PlanTab.stories.tsx create mode 100644 src/browser/features/RightSidebar/PlanTab.test.tsx create mode 100644 src/browser/features/RightSidebar/PlanTab.tsx create mode 100644 src/browser/features/RightSidebar/usePlanFile.ts create mode 100644 src/browser/utils/latestPlanAction.ts create mode 100644 src/browser/utils/openPlanTab.ts diff --git a/docs/agents/plan-mode.mdx b/docs/agents/plan-mode.mdx index 0402c626ed0..8245ac6efdc 100644 --- a/docs/agents/plan-mode.mdx +++ b/docs/agents/plan-mode.mdx @@ -109,6 +109,14 @@ Availability: ## UI Features +The right sidebar's **Plan** tab shows the plan file next to the chat. It reads the file again +when a turn ends and when the window regains focus, so a plan the agent is writing, or one you +edited in an external editor, stays current. Open it from a New tab in the sidebar, with +`/plan open`, with `Ctrl+Shift+B` (`Cmd+Shift+B` on Mac), or from the **Plan file** row in the +Stats tab's post-compaction context. The tab has the plan card's main actions: **Implement**, +**Edit** (opens the file in your external editor) and **Copy**. `/plan` shows the plan in the +chat instead. + The `propose_plan` tool call in chat includes: - **Rendered Markdown**: View the plan with proper formatting. diff --git a/docs/config/keybinds.mdx b/docs/config/keybinds.mdx index b7c3b3a25a5..35b644b0133 100644 --- a/docs/config/keybinds.mdx +++ b/docs/config/keybinds.mdx @@ -83,9 +83,10 @@ While a workspace's actions menu (`⋮` in the sidebar row, `…` in the header) | Toggle left sidebar | `Ctrl+P` | | Toggle right sidebar | `Ctrl+Shift+B` | | New right sidebar tab (lists the tools) | `Ctrl+Alt+N` | +| Open the Plan tab | `Ctrl+Shift+B` | | Close the right sidebar's active tab | `Ctrl+W` | -The right sidebar shows only the tabs you open. A new tab lists the tools it can show (Stats, Review, Instructions, Goal, Terminal, and more); pick one to open it in that tab's place. The **+** button after the last tab opens a new tab. Closing the last tab closes the sidebar. The chevron at the right end of the tab strip lists your open tabs. +The right sidebar shows only the tabs you open. A new tab lists the tools it can show (Stats, Review, Instructions, Plan, Goal, Terminal, and more); pick one to open it in that tab's place. The **+** button after the last tab opens a new tab. Closing the last tab closes the sidebar. The chevron at the right end of the tab strip lists your open tabs. ### Command Palette diff --git a/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx b/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx index 4bd949cad7b..87894762621 100644 --- a/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx +++ b/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx @@ -444,6 +444,36 @@ export const WorkspaceMenuBar: React.FC = ({ return () => window.removeEventListener("keydown", handler); }, [artifactsExperimentEnabled, isTimelineSidebarHidden, openSidebarTab]); + // The Plan tab while the sidebar is hidden: its shortcut (RightSidebar owns the wide-layout + // handler) and "/plan open" (OPEN_PLAN_TAB; RightSidebar already selected the tab, so only a + // hidden sidebar needs showing). + useEffect(() => { + const open = () => openSidebarTab("plan", activeElement()); + const onKeyDown = (e: KeyboardEvent) => { + if ( + !matchesKeybind(e, KEYBINDS.OPEN_PLAN_TAB) || + isDialogOpen() || + !isTimelineSidebarHidden() || + isTerminalFocused(e.target) || + isDesktopViewportFocused(e.target) + ) { + return; + } + e.preventDefault(); + open(); + }; + const onOpenPlanTab = (event: Event) => { + const detail = (event as CustomEvent<{ workspaceId: string }>).detail; + if (detail?.workspaceId === workspaceId && isTimelineSidebarHidden()) open(); + }; + window.addEventListener("keydown", onKeyDown); + window.addEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, onOpenPlanTab); + return () => { + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, onOpenPlanTab); + }; + }, [isTimelineSidebarHidden, openSidebarTab, workspaceId]); + // openArtifact() (chat cards, file cards, Review, palette) and "Open in tab" on an MCP Apps // tool card: while the sidebar is hidden, they show their tab full-screen (RightSidebar // handles the same events on wider layouts). diff --git a/src/browser/components/WorkspaceShell/deferredSidebarInput.ts b/src/browser/components/WorkspaceShell/deferredSidebarInput.ts index c02adbcb489..cd9cfb58ab3 100644 --- a/src/browser/components/WorkspaceShell/deferredSidebarInput.ts +++ b/src/browser/components/WorkspaceShell/deferredSidebarInput.ts @@ -16,6 +16,7 @@ export type HeldSidebarInput = () => void; // at once and opens the side chat full-screen when no sidebar claims it, as on a narrow layout. const SIDEBAR_EVENTS = [ CUSTOM_EVENTS.OPEN_GOAL_TAB, + CUSTOM_EVENTS.OPEN_PLAN_TAB, CUSTOM_EVENTS.OPEN_NEW_SIDEBAR_TAB, CUSTOM_EVENTS.FOCUS_SIDEBAR_TAB, CUSTOM_EVENTS.OPEN_MCP_APP_VIEW, @@ -26,6 +27,7 @@ const SIDEBAR_EVENTS = [ const SIDEBAR_KEYBINDS = [ ...([1, 2, 3, 4, 5, 6, 7, 8, 9] as const).map((n) => KEYBINDS[`SIDEBAR_TAB_${n}`]), KEYBINDS.OPEN_ARTIFACTS_TAB, + KEYBINDS.OPEN_PLAN_TAB, KEYBINDS.CLOSE_TAB, ]; diff --git a/src/browser/features/RightSidebar/NewTabLauncher.tsx b/src/browser/features/RightSidebar/NewTabLauncher.tsx index 2aa87a32d2b..aa4c3d06a25 100644 --- a/src/browser/features/RightSidebar/NewTabLauncher.tsx +++ b/src/browser/features/RightSidebar/NewTabLauncher.tsx @@ -16,6 +16,7 @@ import { mcpAppEntrypointDescription } from "./AppViewTab/mcpAppEntrypoints"; /** Tools with a global shortcut of their own; the launcher shows it as a hint. */ const TOOL_KEYBINDS: Partial> = { artifacts: KEYBINDS.OPEN_ARTIFACTS_TAB, + plan: KEYBINDS.OPEN_PLAN_TAB, }; interface NewTabLauncherProps { diff --git a/src/browser/features/RightSidebar/PlanFileDialog.stories.tsx b/src/browser/features/RightSidebar/PlanFileDialog.stories.tsx deleted file mode 100644 index 4ee47ef31e3..00000000000 --- a/src/browser/features/RightSidebar/PlanFileDialog.stories.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { useRef } from "react"; -import type { FC, ReactNode } from "react"; -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { waitFor, within } from "storybook/test"; - -import { TooltipProvider } from "@/browser/components/Tooltip/Tooltip"; -import type { APIClient } from "@/browser/contexts/API"; -import { APIProvider } from "@/browser/contexts/API"; -import { ThemeProvider } from "@/browser/contexts/ThemeContext"; -import { createMockORPCClient } from "@/browser/stories/mocks/orpc"; -import assert from "@/common/utils/assert"; - -import { PlanFileDialog } from "./PlanFileDialog"; - -const PLAN_PREVIEW_WORKSPACE_ID = "ws-plan-preview"; -const PLAN_PREVIEW_PATH = "/home/user/.mux/plans/my-app/ws-plan-preview.md"; -const PLAN_PREVIEW_CONTENT = `# Plan preview modal story - -- Show the preserved plan directly in the right sidebar flow. -- Keep open-in-editor as a secondary action. -- Verify markdown remains readable in a dialog.`; - -const PlanStoryShell: FC<{ setup: () => APIClient; children: ReactNode }> = ({ - setup, - children, -}) => { - const clientRef = useRef(null); - clientRef.current ??= setup(); - - return ( - - - {children} - - - ); -}; - -function setupPlanPreviewClient(): APIClient { - const client = createMockORPCClient(); - - client.workspace.getPlanContent = (input) => { - assert(input.workspaceId === PLAN_PREVIEW_WORKSPACE_ID, "Unexpected workspace in story mock"); - - return Promise.resolve({ - success: true as const, - data: { - content: PLAN_PREVIEW_CONTENT, - path: PLAN_PREVIEW_PATH, - }, - }); - }; - - return client; -} - -const meta: Meta = { - title: "Features/RightSidebar/PlanFileDialog", - component: PlanFileDialog, - parameters: { - layout: "fullscreen", - pixel: { - // Wide variant: these stories need >=1600px, so use the 1900px desktop viewport. - matrix: { themes: ["dark", "light"], viewports: ["desktop"] }, - }, - }, - decorators: [ - (Story) => ( -
- -
- ), - ], -}; - -export default meta; - -type Story = StoryObj; - -export const PlanPreviewModal: Story = { - render: () => ( - - { - // No-op in Storybook; dialog remains open for visual regression snapshots. - }} - workspaceId={PLAN_PREVIEW_WORKSPACE_ID} - /> - - ), - play: async () => { - const body = within(document.body); - - await waitFor(() => { - body.getByText("Plan preview modal story"); - body.getByText(PLAN_PREVIEW_PATH); - }); - }, -}; diff --git a/src/browser/features/RightSidebar/PlanFileDialog.test.tsx b/src/browser/features/RightSidebar/PlanFileDialog.test.tsx deleted file mode 100644 index 9e99156a5ed..00000000000 --- a/src/browser/features/RightSidebar/PlanFileDialog.test.tsx +++ /dev/null @@ -1,179 +0,0 @@ -import * as RealMarkdownCore from "../Messages/MarkdownCore"; -import * as RealMarkdownRenderer from "../Messages/MarkdownRenderer"; -import { APIContext, APIProvider } from "@/browser/contexts/API"; -import type { ReactElement, ReactNode } from "react"; -import { PlanFileDialog } from "./PlanFileDialog"; -import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; -import { GlobalWindow } from "happy-dom"; -import { cleanup, render, waitFor } from "@testing-library/react"; -import * as RealDialogModule from "@/browser/components/Dialog/Dialog"; -import type { APIClient } from "@/browser/contexts/API"; -import { createTestApiClient, type TestApiOverrides } from "@/browser/testUtils"; - -type GetPlanContentResult = - | { success: true; data: { content: string; path: string } } - | { success: false; error: string }; - -let mockApi: TestApiOverrides | null = null; - -// Scope module mocks to each test so renderer assertions use the real pipeline. -const realModules: Array<[string, Record]> = [ - ["@/browser/components/Dialog/Dialog", { ...RealDialogModule }], - ["@/browser/features/Messages/MarkdownCore", { ...RealMarkdownCore }], - ["@/browser/features/Messages/MarkdownRenderer", { ...RealMarkdownRenderer }], -]; - -async function installModuleMocks() { - await mock.module("@/browser/components/Dialog/Dialog", () => ({ - Dialog: (props: { open: boolean; children: ReactNode }) => - props.open ?
{props.children}
: null, - DialogContent: (props: { children: ReactNode; className?: string }) => ( -
{props.children}
- ), - DialogHeader: (props: { children: ReactNode }) =>
{props.children}
, - DialogTitle: (props: { children: ReactNode; className?: string }) => ( -

{props.children}

- ), - })); - - await mock.module("@/browser/features/Messages/MarkdownCore", () => ({ - MarkdownCore: (props: { content: string }) => ( -
{props.content}
- ), - })); - - await mock.module("@/browser/features/Messages/MarkdownRenderer", () => ({ - PlanMarkdownContainer: (props: { children: ReactNode }) => ( -
{props.children}
- ), - })); -} - -// Inject the client through the real provider (a module mock of contexts/API is process-wide). -// The wrapper reads mockApi at render time; a null mockApi models an unavailable backend. -function ApiWrapper(props: { children: ReactNode }) { - if (mockApi === null) { - return ( - undefined, - retry: () => undefined, - }} - > - {props.children} - - ); - } - return {props.children}; -} - -function renderWithApi(ui: ReactElement) { - return render(ui, { wrapper: ApiWrapper }); -} - -async function restoreModuleMocks() { - for (const [path, exports] of realModules) await mock.module(path, () => exports); -} - -describe("PlanFileDialog", () => { - let originalWindow: typeof globalThis.window; - let originalDocument: typeof globalThis.document; - - beforeEach(async () => { - await installModuleMocks(); - originalWindow = globalThis.window; - originalDocument = globalThis.document; - globalThis.window = new GlobalWindow() as unknown as Window & typeof globalThis; - globalThis.document = globalThis.window.document; - mockApi = null; - }); - - afterEach(async () => { - cleanup(); - await restoreModuleMocks(); - mock.restore(); - globalThis.window = originalWindow; - globalThis.document = originalDocument; - }); - - test("fetches plan content only after the dialog opens", async () => { - const getPlanContent = mock(() => - Promise.resolve({ - success: true, - data: { - content: "# Plan title\n\n- item", - path: "/tmp/plan.md", - }, - } satisfies GetPlanContentResult) - ); - - mockApi = { - workspace: { - getPlanContent, - }, - }; - - const onOpenChange = () => undefined; - const view = renderWithApi( - - ); - - expect(getPlanContent).toHaveBeenCalledTimes(0); - - view.rerender(); - - await waitFor(() => { - expect(getPlanContent).toHaveBeenCalledTimes(1); - }); - - await waitFor(() => { - expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Plan title"); - }); - - expect(view.getByText("/tmp/plan.md")).toBeTruthy(); - }); - - test("shows API error responses in the dialog", async () => { - const getPlanContent = mock(() => - Promise.resolve({ - success: false, - error: "Plan file not found", - } satisfies GetPlanContentResult) - ); - - mockApi = { - workspace: { - getPlanContent, - }, - }; - - const view = renderWithApi( - undefined} workspaceId="workspace-2" /> - ); - - await waitFor(() => { - expect(getPlanContent).toHaveBeenCalledTimes(1); - }); - - await waitFor(() => { - expect(view.getByTestId("plan-file-dialog-error").textContent).toContain( - "Plan file not found" - ); - }); - }); - - test("renders API-unavailable state when not connected", async () => { - mockApi = null; - - const view = renderWithApi( - undefined} workspaceId="workspace-3" /> - ); - - await waitFor(() => { - expect(view.getByTestId("plan-file-dialog-error").textContent).toContain("API unavailable"); - }); - }); -}); diff --git a/src/browser/features/RightSidebar/PlanFileDialog.tsx b/src/browser/features/RightSidebar/PlanFileDialog.tsx deleted file mode 100644 index 1a5ea885fc9..00000000000 --- a/src/browser/features/RightSidebar/PlanFileDialog.tsx +++ /dev/null @@ -1,148 +0,0 @@ -import React, { useEffect, useRef, useState } from "react"; -import assert from "@/common/utils/assert"; -import { useAPI, type APIClient } from "@/browser/contexts/API"; -import { MarkdownCore } from "@/browser/features/Messages/MarkdownCore"; -import { PlanMarkdownContainer } from "@/browser/features/Messages/MarkdownRenderer"; -import { - Dialog, - DialogContent, - DialogHeader, - DialogTitle, -} from "@/browser/components/Dialog/Dialog"; -import { isConnectionLostError } from "@/browser/contexts/connectionLink"; -import { getErrorMessage } from "@/common/utils/errors"; - -interface PlanFileDialogProps { - open: boolean; - onOpenChange: (open: boolean) => void; - workspaceId: string; -} - -export const PlanFileDialog: React.FC = (props) => ( - - - {/* PostCompactionSection renders this dialog while closed: the body, and so its plan - read, mounts only while the dialog is open. Keyed by workspace, so another workspace - (or reopening the dialog) starts from an empty body, while a new API client (a - reconnect) re-reads the plan in the background and keeps it shown. */} - - - -); - -type PlanRead = - | { status: "ok"; content: string; path: string } - | { status: "error"; error: string } - /** Cut off by a lost connection (ConnectionLostError): not a plan error. */ - | { status: "lost" }; - -async function readPlan(api: APIClient, workspaceId: string): Promise { - try { - const result = await api.workspace.getPlanContent({ workspaceId }); - if (!result.success) { - return { status: "error", error: result.error }; - } - assert(result.data.path.length > 0, "Plan path should be non-empty"); - return { status: "ok", content: result.data.content, path: result.data.path }; - } catch (error: unknown) { - return isConnectionLostError(error) - ? { status: "lost" } - : { status: "error", error: getErrorMessage(error) }; - } -} - -function usePlanFile(workspaceId: string) { - const { api } = useAPI(); - - const [isLoading, setIsLoading] = useState(true); - const [error, setError] = useState(null); - const [content, setContent] = useState(null); - const [path, setPath] = useState(null); - // True once a plan is on screen: offline (no client during a reconnect) then keeps it. - const hasPlanRef = useRef(false); - - useEffect(() => { - assert(workspaceId.trim().length > 0, "workspaceId is required to load plan preview"); - - if (!api) { - if (!hasPlanRef.current) { - setIsLoading(false); - setError("API unavailable"); - } - return; - } - - // A read with a client replaces the offline error. Without a plan on screen, it shows - // "Loading plan…" (the dialog may have opened while there was no client). - setError(null); - if (!hasPlanRef.current) { - setIsLoading(true); - } - - let cancelled = false; - - void readPlan(api, workspaceId).then((read) => { - // A lost connection (or this effect's own cleanup) keeps what is shown for the next client. - if (cancelled || read.status === "lost") { - return; - } - setIsLoading(false); - if (read.status === "error") { - setError(read.error); - return; - } - setError(null); - setContent(read.content); - setPath(read.path); - hasPlanRef.current = true; - }); - - return () => { - cancelled = true; - }; - }, [api, workspaceId]); - - return { isLoading, error, content, path }; -} - -function PlanFileBody(props: { workspaceId: string }) { - const { isLoading, error, content, path } = usePlanFile(props.workspaceId); - - return ( - <> - - - Plan file - {path && ( - - {path} - - )} - - - -
- {error ? ( -
- {error} -
- ) : isLoading ? ( -
Loading plan…
- ) : content !== null ? ( - content.length > 0 ? ( - - {/* Keyed by the text: a reload replaces the plan in place, and Streamdown's - elements re-render only when their source position changes, so an edit that - keeps the positions would otherwise stay stale on screen. */} - - - ) : ( -
Plan file is empty
- ) - ) : ( -
No plan loaded
- )} -
- - ); -} diff --git a/src/browser/features/RightSidebar/PlanTab.stories.tsx b/src/browser/features/RightSidebar/PlanTab.stories.tsx new file mode 100644 index 00000000000..83f2b444027 --- /dev/null +++ b/src/browser/features/RightSidebar/PlanTab.stories.tsx @@ -0,0 +1,101 @@ +import { useRef } from "react"; +import type { FC, ReactNode } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { waitFor, within } from "storybook/test"; + +import { TooltipProvider } from "@/browser/components/Tooltip/Tooltip"; +import type { APIClient } from "@/browser/contexts/API"; +import { APIProvider } from "@/browser/contexts/API"; +import { ThemeProvider } from "@/browser/contexts/ThemeContext"; +import { createMockORPCClient } from "@/browser/stories/mocks/orpc"; + +import { PlanTab } from "./PlanTab"; + +const PLAN_WORKSPACE_ID = "ws-plan-tab"; +const PLAN_PATH = "/home/user/.xum/plans/my-app/ws-plan-tab.md"; +const PLAN_CONTENT = `# Plan tab story + +## Goal + +Show the workspace's plan next to the chat, with the plan card's main actions. + +## Steps + +1. Read the plan file through \`workspace.getPlanContent\`. +2. Re-read it when a turn ends or the window regains focus. +3. Keep **Implement**, **Edit** and **Copy** one click away.`; + +const PlanStoryShell: FC<{ setup: () => APIClient; children: ReactNode }> = ({ + setup, + children, +}) => { + const clientRef = useRef(null); + clientRef.current ??= setup(); + + return ( + + + {children} + + + ); +}; + +function setupClient(result: Awaited>) { + return (): APIClient => { + const client = createMockORPCClient(); + client.workspace.getPlanContent = () => Promise.resolve(result); + return client; + }; +} + +const meta: Meta = { + title: "Features/RightSidebar/PlanTab", + component: PlanTab, + parameters: { layout: "fullscreen" }, + decorators: [ + (Story) => ( + // A right-sidebar pane's width. +
+ +
+ ), + ], +}; + +export default meta; + +type Story = StoryObj; + +export const WithPlan: Story = { + render: () => ( + + + + ), + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await waitFor(() => { + canvas.getByText("Plan tab story"); + canvas.getByText(PLAN_PATH); + }); + }, +}; + +export const NoPlanYet: Story = { + render: () => ( + + + + ), + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await waitFor(() => { + canvas.getByText(/Switch to the Plan agent/); + }); + }, +}; diff --git a/src/browser/features/RightSidebar/PlanTab.test.tsx b/src/browser/features/RightSidebar/PlanTab.test.tsx new file mode 100644 index 00000000000..fee20113e3b --- /dev/null +++ b/src/browser/features/RightSidebar/PlanTab.test.tsx @@ -0,0 +1,242 @@ +import * as RealMarkdownCore from "../Messages/MarkdownCore"; +import * as RealMarkdownRenderer from "../Messages/MarkdownRenderer"; +import { APIContext, APIProvider } from "@/browser/contexts/API"; +import type { ReactElement, ReactNode } from "react"; +import { PlanTab } from "./PlanTab"; +import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; +import { GlobalWindow } from "happy-dom"; +import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import type { APIClient } from "@/browser/contexts/API"; +import { createTestApiClient, type TestApiOverrides } from "@/browser/testUtils"; +import { CUSTOM_EVENTS, type CustomEventType } from "@/common/constants/events"; + +type GetPlanContentResult = + | { success: true; data: { content: string; path: string } } + | { success: false; error: string }; + +let mockApi: TestApiOverrides | null = null; + +// Scope module mocks to each test so renderer assertions use the real pipeline. +const realModules: Array<[string, Record]> = [ + ["@/browser/features/Messages/MarkdownCore", { ...RealMarkdownCore }], + ["@/browser/features/Messages/MarkdownRenderer", { ...RealMarkdownRenderer }], +]; + +async function installModuleMocks() { + await mock.module("@/browser/features/Messages/MarkdownCore", () => ({ + MarkdownCore: (props: { content: string }) => ( +
{props.content}
+ ), + })); + + await mock.module("@/browser/features/Messages/MarkdownRenderer", () => ({ + PlanMarkdownContainer: (props: { children: ReactNode }) => ( +
{props.children}
+ ), + })); +} + +// Inject the client through the real provider (a module mock of contexts/API is process-wide). +// The wrapper reads mockApi at render time; a null mockApi models an unavailable backend. +function ApiWrapper(props: { children: ReactNode }) { + if (mockApi === null) { + return ( + undefined, + retry: () => undefined, + }} + > + {props.children} + + ); + } + return {props.children}; +} + +function renderWithApi(ui: ReactElement) { + return render(ui, { wrapper: ApiWrapper }); +} + +async function restoreModuleMocks() { + for (const [path, exports] of realModules) await mock.module(path, () => exports); +} + +function planResult(content: string, path = "/tmp/plan.md"): GetPlanContentResult { + return { success: true, data: { content, path } }; +} + +describe("PlanTab", () => { + let originalWindow: typeof globalThis.window; + let originalDocument: typeof globalThis.document; + + beforeEach(async () => { + await installModuleMocks(); + originalWindow = globalThis.window; + originalDocument = globalThis.document; + globalThis.window = new GlobalWindow() as unknown as Window & typeof globalThis; + globalThis.document = globalThis.window.document; + mockApi = null; + }); + + afterEach(async () => { + cleanup(); + await restoreModuleMocks(); + mock.restore(); + globalThis.window = originalWindow; + globalThis.document = originalDocument; + }); + + test("shows the plan and its path once read", async () => { + const getPlanContent = mock(() => Promise.resolve(planResult("# Plan title\n\n- item"))); + mockApi = { workspace: { getPlanContent } }; + + const view = renderWithApi(); + + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Plan title"); + }); + expect(getPlanContent).toHaveBeenCalledTimes(1); + expect(view.getByTestId("plan-tab-path").textContent).toBe("/tmp/plan.md"); + expect(view.getByRole("button", { name: "Implement" }).hasAttribute("disabled")).toBe(false); + }); + + test("re-reads the plan when the window regains focus", async () => { + let planText = "# First draft"; + const getPlanContent = mock(() => Promise.resolve(planResult(planText))); + mockApi = { workspace: { getPlanContent } }; + + const view = renderWithApi(); + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# First draft"); + }); + + // An external editor saved the file: the next focus shows the saved text. + planText = "# Second draft"; + act(() => { + window.dispatchEvent(new window.Event("focus")); + }); + + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Second draft"); + }); + expect(getPlanContent).toHaveBeenCalledTimes(2); + }); + + test("a workspace without a plan says how to get one and disables the actions", async () => { + const getPlanContent = mock(() => + Promise.resolve({ + success: false, + error: "Plan file not found at /tmp/plans/ws.md", + } satisfies GetPlanContentResult) + ); + mockApi = { workspace: { getPlanContent } }; + + const view = renderWithApi(); + + await waitFor(() => { + expect(view.getByTestId("plan-tab-error").textContent).toContain("Plan file not found"); + }); + expect(view.getByText(/Switch to the Plan agent/)).toBeTruthy(); + expect(view.getByRole("button", { name: "Implement" }).hasAttribute("disabled")).toBe(true); + expect(view.getByRole("button", { name: "Edit" }).hasAttribute("disabled")).toBe(true); + }); + + test("other read errors show without the how-to hint", async () => { + const getPlanContent = mock(() => + Promise.resolve({ + success: false, + error: "Could not read the plan file because the workspace runtime is unreachable", + } satisfies GetPlanContentResult) + ); + mockApi = { workspace: { getPlanContent } }; + + const view = renderWithApi(); + + await waitFor(() => { + expect(view.getByTestId("plan-tab-error").textContent).toContain("unreachable"); + }); + expect(view.queryByText(/Switch to the Plan agent/)).toBeNull(); + }); + + test("restores a workspace's plan scroll offset when the tab returns", async () => { + const getPlanContent = mock(() => Promise.resolve(planResult("# Long plan"))); + mockApi = { workspace: { getPlanContent } }; + + const first = renderWithApi(); + await waitFor(() => { + expect(first.getByTestId("plan-markdown-core").textContent).toContain("# Long plan"); + }); + fireEvent.scroll(first.getByTestId("plan-tab-body"), { target: { scrollTop: 120 } }); + // Leaving the workspace (or switching tabs) unmounts the body, which saves the offset. + first.unmount(); + + const second = renderWithApi(); + await waitFor(() => { + expect(second.getByTestId("plan-markdown-core").textContent).toContain("# Long plan"); + }); + expect(second.getByTestId("plan-tab-body").scrollTop).toBe(120); + second.unmount(); + + // Another workspace starts from its own (unset) offset. + const other = renderWithApi(); + await waitFor(() => { + expect(other.getByTestId("plan-markdown-core").textContent).toContain("# Long plan"); + }); + expect(other.getByTestId("plan-tab-body").scrollTop).toBe(0); + }); + + test("renders API-unavailable state when not connected", async () => { + mockApi = null; + + const view = renderWithApi(); + + await waitFor(() => { + expect(view.getByTestId("plan-tab-error").textContent).toContain("API unavailable"); + }); + }); + + test("Implement runs the latest plan card's action and reports when none can run", async () => { + mockApi = { workspace: { getPlanContent: mock(() => Promise.resolve(planResult("# Plan"))) } }; + const view = renderWithApi(); + await waitFor(() => { + expect(view.getByRole("button", { name: "Implement" }).hasAttribute("disabled")).toBe(false); + }); + + // showFeedbackToast dispatches its event only where the composer hosts toasts; elsewhere + // it falls back to a native alert. + const composer = document.createElement("div"); + composer.setAttribute("data-component", "ChatInputSection"); + document.body.appendChild(composer); + const toasts: Array<{ type: string }> = []; + const onToast = (event: Event) => { + toasts.push((event as CustomEventType).detail); + }; + const requests: string[] = []; + const planCard = (event: Event) => { + const { detail } = event as CustomEventType; + requests.push(detail.workspaceId); + detail.handled = true; + }; + window.addEventListener(CUSTOM_EVENTS.ANALYTICS_REBUILD_TOAST, onToast); + window.addEventListener(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, planCard); + try { + // A plan card is listening: it runs the action, so there is nothing to report. + fireEvent.click(view.getByRole("button", { name: "Implement" })); + expect(requests).toEqual(["workspace-1"]); + expect(toasts).toEqual([]); + + // No card can run it (none rendered, or its action disabled): the tab says so. + window.removeEventListener(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, planCard); + fireEvent.click(view.getByRole("button", { name: "Implement" })); + expect(toasts.map((toast) => toast.type)).toEqual(["error"]); + } finally { + window.removeEventListener(CUSTOM_EVENTS.ANALYTICS_REBUILD_TOAST, onToast); + window.removeEventListener(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, planCard); + composer.remove(); + } + }); +}); diff --git a/src/browser/features/RightSidebar/PlanTab.tsx b/src/browser/features/RightSidebar/PlanTab.tsx new file mode 100644 index 00000000000..95454cea8cd --- /dev/null +++ b/src/browser/features/RightSidebar/PlanTab.tsx @@ -0,0 +1,188 @@ +import React, { useEffect, useRef, useState } from "react"; +import { Check, Copy, ExternalLink, Play } from "lucide-react"; +import { useLiveAPI } from "@/browser/contexts/API"; +import { useOptionalWorkspaceMetadata } from "@/browser/contexts/WorkspaceContext"; +import { MarkdownCore } from "@/browser/features/Messages/MarkdownCore"; +import { PlanMarkdownContainer } from "@/browser/features/Messages/MarkdownRenderer"; +import { useCopyToClipboard } from "@/browser/hooks/useCopyToClipboard"; +import { readPersistedState, updatePersistedState } from "@/browser/hooks/usePersistedState"; +import { useOptionalWorkspaceSidebarState } from "@/browser/stores/WorkspaceStore"; +import { showFeedbackToast } from "@/browser/utils/feedbackToast"; +import { NO_RUNNABLE_PLAN_MESSAGE, runLatestPlanAction } from "@/browser/utils/latestPlanAction"; +import { openInEditor } from "@/browser/utils/openInEditor"; +import { getPlanTabScrollTopKey } from "@/common/constants/storage"; +import { TAB_ICONS } from "./Tabs/tabIcons"; +import { usePlanFile } from "./usePlanFile"; + +interface PlanTabProps { + workspaceId: string; +} + +/** + * The right sidebar's Plan tab: the workspace's plan file, next to the chat instead of in a + * modal, with the plan card's main actions. Keyed by workspace, so another workspace starts + * from an empty body instead of showing the previous plan while its own loads. + */ +export const PlanTab: React.FC = (props) => ( + +); + +/** The plan reader's wording for a workspace without a plan (getWorkspacePlanContent). */ +const NO_PLAN_ERROR_PREFIX = "Plan file not found"; + +function normalizeScrollTop(value: unknown): number { + return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0; +} + +const ACTION_CLASS = + "text-subtle hover:text-foreground inline-flex items-center gap-1 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50"; + +function PlanTabBody(props: { workspaceId: string }) { + const { workspaceId } = props; + const api = useLiveAPI(); + const runtimeConfig = + useOptionalWorkspaceMetadata()?.workspaceMetadata.get(workspaceId)?.runtimeConfig; + + // The plan has no push channel, so it is re-read at the moments it can have changed: a turn + // ending (the plan agent writes the file during its turn) and the window regaining focus + // (an external editor). + const [refreshKey, setRefreshKey] = useState(0); + const isStreaming = useOptionalWorkspaceSidebarState(workspaceId)?.canInterrupt === true; + const [wasStreaming, setWasStreaming] = useState(isStreaming); + if (wasStreaming !== isStreaming) { + setWasStreaming(isStreaming); + if (!isStreaming) setRefreshKey((key) => key + 1); + } + useEffect(() => { + const handleFocus = () => setRefreshKey((key) => key + 1); + window.addEventListener("focus", handleFocus); + return () => window.removeEventListener("focus", handleFocus); + }, []); + + const { isLoading, error, content, path } = usePlanFile(workspaceId, refreshKey); + const { copied, copyToClipboard } = useCopyToClipboard(); + const hasPlan = content !== null && content.length > 0; + + // Leaving the workspace or switching tabs unmounts this body: keep the plan's scroll offset + // per workspace. Tracked while scrolling, saved on unmount, restored once the plan renders + // (the body has its height only then). A re-read keeps the body, so its offset stays. + const bodyRef = useRef(null); + const scrollTopRef = useRef(0); + useEffect(() => { + if (!hasPlan) return; + const saved = normalizeScrollTop( + readPersistedState(getPlanTabScrollTopKey(workspaceId), 0) + ); + scrollTopRef.current = saved; + if (bodyRef.current) bodyRef.current.scrollTop = saved; + }, [hasPlan, workspaceId]); + useEffect(() => { + return () => { + updatePersistedState(getPlanTabScrollTopKey(workspaceId), scrollTopRef.current, 0); + }; + }, [workspaceId]); + + const handleImplement = () => { + if (!runLatestPlanAction(workspaceId)) { + showFeedbackToast({ type: "error", message: NO_RUNNABLE_PLAN_MESSAGE }); + } + }; + + const handleOpenInEditor = async () => { + if (path === null) return; + const result = await openInEditor({ + api, + workspaceId, + targetPath: path, + runtimeConfig, + isFile: true, + }); + if (!result.success) { + showFeedbackToast({ type: "error", message: result.error ?? "Failed to open editor" }); + } + }; + + return ( +
+
+
+ + + Plan + +
+ + + +
+
+ {path && ( + + {path} + + )} +
+ +
{ + scrollTopRef.current = normalizeScrollTop(event.currentTarget.scrollTop); + }} + > + {error ? ( +
+
+ {error} +
+ {error.startsWith(NO_PLAN_ERROR_PREFIX) && ( +
+ Switch to the Plan agent and ask for a plan; it shows here as the agent writes it. +
+ )} +
+ ) : isLoading ? ( +
Loading plan…
+ ) : content !== null ? ( + hasPlan ? ( + + {/* Keyed by the text: a reload replaces the plan in place, and Streamdown's + elements re-render only when their source position changes, so an edit that + keeps the positions would otherwise stay stale on screen. */} + + + ) : ( +
Plan file is empty
+ ) + ) : ( +
No plan loaded
+ )} +
+
+ ); +} diff --git a/src/browser/features/RightSidebar/PostCompactionSection.tsx b/src/browser/features/RightSidebar/PostCompactionSection.tsx index 8b86a32927e..eaef7e3c325 100644 --- a/src/browser/features/RightSidebar/PostCompactionSection.tsx +++ b/src/browser/features/RightSidebar/PostCompactionSection.tsx @@ -1,10 +1,10 @@ -import React, { useMemo, useState } from "react"; +import React, { useMemo } from "react"; import { ChevronRight, FileText, ExternalLink, Eye, EyeOff, Info } from "lucide-react"; import { usePersistedState } from "@/browser/hooks/usePersistedState"; import { useOpenInEditor } from "@/browser/hooks/useOpenInEditor"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/browser/components/Tooltip/Tooltip"; import type { RuntimeConfig } from "@/common/types/runtime"; -import { PlanFileDialog } from "./PlanFileDialog"; +import { openPlanTab } from "@/browser/utils/openPlanTab"; import { POST_COMPACTION_COLLAPSED_KEY, POST_COMPACTION_FILES_EXPANDED_KEY, @@ -35,7 +35,6 @@ export const PostCompactionSection: React.FC = (prop POST_COMPACTION_FILES_EXPANDED_KEY, false ); - const [isPlanDialogOpen, setIsPlanDialogOpen] = useState(false); const handleOpenPlan = (e: React.MouseEvent) => { e.stopPropagation(); @@ -129,7 +128,10 @@ export const PostCompactionSection: React.FC = (prop - View plan + Open the Plan tab @@ -156,11 +158,6 @@ export const PostCompactionSection: React.FC = (prop - )} diff --git a/src/browser/features/RightSidebar/RightSidebar.tsx b/src/browser/features/RightSidebar/RightSidebar.tsx index 23688562c31..aababd297a2 100644 --- a/src/browser/features/RightSidebar/RightSidebar.tsx +++ b/src/browser/features/RightSidebar/RightSidebar.tsx @@ -1848,6 +1848,19 @@ const RightSidebarComponent: React.FC = ({ return () => window.removeEventListener(CUSTOM_EVENTS.OPEN_GOAL_TAB, handleOpenGoalTab); }, [setCollapsed, setLayout, workspaceId]); + // "/plan open" and the Stats tab's "Plan file" row: open (and un-collapse) the Plan tab. While + // the narrow layout hides the sidebar, WorkspaceMenuBar shows the tab full-screen as well. + React.useEffect(() => { + const handleOpenPlanTab = (event: Event) => { + const detail = (event as CustomEventType).detail; + if (detail?.workspaceId !== workspaceId) return; + setCollapsed(false); + setLayout((prev) => selectOrAddTab(prev, "plan")); + }; + window.addEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, handleOpenPlanTab); + return () => window.removeEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, handleOpenPlanTab); + }, [setCollapsed, setLayout, workspaceId]); + const [tabToFocus, setTabToFocus] = React.useState(null); const sidebarContainerRef = React.useRef(null); @@ -1939,6 +1952,31 @@ const RightSidebarComponent: React.FC = ({ }, }); + // Global shortcut: open (and un-collapse) the Plan tab, with the Artifacts shortcut's guards. + // While the narrow layout hides the sidebar, WorkspaceMenuBar shows the tab full-screen + // instead; this handler then stays out, so one keystroke never acts twice. + React.useEffect(() => { + const handler = (e: KeyboardEvent) => { + const container = sidebarContainerRef.current; + if ( + !matchesKeybind(e, KEYBINDS.OPEN_PLAN_TAB) || + (container != null && isRightSidebarResponsivelyHidden(container)) || + isDialogOpen() || + // Remote desktops, browsers and terminals own their keystrokes. + isTerminalFocused(e.target) || + isDesktopViewportFocused(e.target) || + isBrowserViewportFocused(e.target) + ) { + return; + } + e.preventDefault(); + setCollapsed(false); + setLayout((prev) => selectOrAddTab(prev, "plan")); + }; + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }, [setCollapsed, setLayout]); + // Auto-surface the Workflows tab when a run starts: the tab is the primary // run-detail surface (the chat card stays collapsed while it exists), but a // background-added tab with a small badge is easy to miss. Only a mounted @@ -2562,6 +2600,7 @@ const RightSidebarComponent: React.FC = ({ costs: true, review: canReviewDiffs, instructions: true, + plan: true, goal: true, workflows: true, timeline: true, diff --git a/src/browser/features/RightSidebar/Tabs/TabLabels.tsx b/src/browser/features/RightSidebar/Tabs/TabLabels.tsx index dc4b128516f..3fff4508c70 100644 --- a/src/browser/features/RightSidebar/Tabs/TabLabels.tsx +++ b/src/browser/features/RightSidebar/Tabs/TabLabels.tsx @@ -254,6 +254,15 @@ export const WorkflowsTabLabel: React.FC = ({ workspaceI ); }; +export function PlanTabLabel() { + return ( + + + Plan + + ); +} + export function OutputTabLabel() { return ( diff --git a/src/browser/features/RightSidebar/Tabs/tabConfig.ts b/src/browser/features/RightSidebar/Tabs/tabConfig.ts index 4a4514a2485..63cc569b6a7 100644 --- a/src/browser/features/RightSidebar/Tabs/tabConfig.ts +++ b/src/browser/features/RightSidebar/Tabs/tabConfig.ts @@ -47,6 +47,13 @@ const TAB_CONFIG_DEF = { defaultOrder: 30, paletteKeywords: ["agents", "agents.md", "claude.md", "instructions", "prompt", "context"], }, + plan: { + description: "The plan the agent wrote for this chat", + name: "Plan", + contentClassName: "overflow-hidden p-0", + defaultOrder: 33, + paletteKeywords: ["plan", "propose_plan", "planning"], + }, goal: { description: "Give the agent a goal and track its progress", name: "Goal", diff --git a/src/browser/features/RightSidebar/Tabs/tabIcons.ts b/src/browser/features/RightSidebar/Tabs/tabIcons.ts index 62513c5bf04..5e6b404aefc 100644 --- a/src/browser/features/RightSidebar/Tabs/tabIcons.ts +++ b/src/browser/features/RightSidebar/Tabs/tabIcons.ts @@ -3,6 +3,7 @@ import { Brain, BugPlay, ChartColumn, + ClipboardList, FileText, GitCompare, Globe, @@ -24,6 +25,7 @@ export const TAB_ICONS: Record = { costs: ChartColumn, review: GitCompare, instructions: FileText, + plan: ClipboardList, goal: Target, workflows: Workflow, timeline: ListTree, diff --git a/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx b/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx index 6a8af71cb60..f029284fde1 100644 --- a/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx +++ b/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx @@ -36,6 +36,7 @@ import { ArtifactsTabLabel, MemoryTabLabel, OutputTabLabel, + PlanTabLabel, ReviewTabLabel, StatsTabLabel, TimelineTabLabel, @@ -77,6 +78,9 @@ const DevToolsTab = lazyPanel("Debug", () => const GoalTab = lazyPanel("Goal", () => import("@/browser/features/RightSidebar/GoalTab").then((m) => m.GoalTab) ); +const PlanTab = lazyPanel("Plan", () => + import("@/browser/features/RightSidebar/PlanTab").then((m) => m.PlanTab) +); const MemoryTab = lazyPanel("Memory", () => import("@/browser/features/RightSidebar/Memory/MemoryTab").then((m) => m.MemoryTab) ); @@ -186,6 +190,14 @@ const TAB_RENDERERS = { Label: ({ workspaceId }) => , renderPanel: (ctx) => , }, + plan: { + Label: PlanTabLabel, + renderPanel: (ctx) => ( + + + + ), + }, goal: { Label: ({ workspaceId }) => , renderPanel: (ctx) => ( diff --git a/src/browser/features/RightSidebar/dialogsReconnect.test.tsx b/src/browser/features/RightSidebar/dialogsReconnect.test.tsx index 2d2bd851721..d02737f62be 100644 --- a/src/browser/features/RightSidebar/dialogsReconnect.test.tsx +++ b/src/browser/features/RightSidebar/dialogsReconnect.test.tsx @@ -15,7 +15,7 @@ import { } from "@/browser/contexts/connection.testHarness"; import { SubagentTranscriptDialog } from "@/browser/features/Tools/SubagentTranscriptDialog"; import type { TestApiOutput, TestApiOverrides } from "@/browser/testUtils"; -import { PlanFileDialog } from "./PlanFileDialog"; +import { PlanTab } from "./PlanTab"; /* * A dialog that shows loaded content keeps it across a dropped connection: the new client @@ -104,9 +104,9 @@ describe.each([...GAP_MODES])("dialogs across a dropped connection (%s)", (mode) cleanupDom = null; }); - test("the plan dialog keeps the shown plan until the new client's read lands", async () => { + test("the plan tab keeps the shown plan until the new client's read lands", async () => { answerPlan = () => Promise.resolve(planResult("Plan A")); - const view = render(, { + const view = render(, { wrapper: Wrapper, }); await view.findByText("Plan A"); @@ -123,7 +123,7 @@ describe.each([...GAP_MODES])("dialogs across a dropped connection (%s)", (mode) expect(view.queryByText("Loading plan…")).toBeNull(); await drop(); expect(view.queryByText("Plan A")).not.toBeNull(); - expect(view.queryByTestId("plan-file-dialog-error")).toBeNull(); + expect(view.queryByTestId("plan-tab-error")).toBeNull(); const next = deferred(); answerPlan = () => next.promise; @@ -209,9 +209,9 @@ describe.each([...GAP_MODES])("dialogs opened while reconnecting (%s)", (mode) = cleanupDom = null; }); - test("the plan dialog shows its loading state once a client reads the plan", async () => { + test("the plan tab shows its loading state once a client reads the plan", async () => { answerPlan = () => Promise.resolve(planResult("unused")); - const view = render(, { + const view = render(, { wrapper: Wrapper, }); await settle(); @@ -220,7 +220,7 @@ describe.each([...GAP_MODES])("dialogs opened while reconnecting (%s)", (mode) = answerPlan = () => next.promise; await reconnect(); expect(view.queryByText("Loading plan…")).not.toBeNull(); - expect(view.queryByTestId("plan-file-dialog-error")).toBeNull(); + expect(view.queryByTestId("plan-tab-error")).toBeNull(); next.resolve(planResult("Plan A")); await view.findByText("Plan A"); @@ -260,14 +260,14 @@ describe("dialogs opened on other data", () => { test("another workspace clears the shown plan while its own plan loads", async () => { answerPlan = () => Promise.resolve(planResult("Plan A")); - const view = render(, { + const view = render(, { wrapper: Wrapper, }); await view.findByText("Plan A"); const pending = deferred(); answerPlan = () => pending.promise; - view.rerender(); + view.rerender(); await waitFor(() => expect(view.queryByText("Loading plan…")).not.toBeNull()); expect(view.queryByText("Plan A")).toBeNull(); }); diff --git a/src/browser/features/RightSidebar/usePlanFile.ts b/src/browser/features/RightSidebar/usePlanFile.ts new file mode 100644 index 00000000000..7bf6a6a5dd6 --- /dev/null +++ b/src/browser/features/RightSidebar/usePlanFile.ts @@ -0,0 +1,87 @@ +import { useEffect, useRef, useState } from "react"; +import assert from "@/common/utils/assert"; +import { useAPI, type APIClient } from "@/browser/contexts/API"; +import { isConnectionLostError } from "@/browser/contexts/connectionLink"; +import { getErrorMessage } from "@/common/utils/errors"; + +export type PlanRead = + | { status: "ok"; content: string; path: string } + | { status: "error"; error: string } + /** Cut off by a lost connection (ConnectionLostError): not a plan error. */ + | { status: "lost" }; + +export async function readPlan(api: APIClient, workspaceId: string): Promise { + try { + const result = await api.workspace.getPlanContent({ workspaceId }); + if (!result.success) { + return { status: "error", error: result.error }; + } + assert(result.data.path.length > 0, "Plan path should be non-empty"); + return { status: "ok", content: result.data.content, path: result.data.path }; + } catch (error: unknown) { + return isConnectionLostError(error) + ? { status: "lost" } + : { status: "error", error: getErrorMessage(error) }; + } +} + +/** + * The workspace's plan file, read through `workspace.getPlanContent` and read again whenever + * `refreshKey` changes (the plan has no push channel). A plan already on screen stays while + * the next read is in flight, and offline (no client during a reconnect): the new client's + * read then replaces it in the background. Without a plan on screen, a read shows the loading + * state first. + */ +export function usePlanFile(workspaceId: string, refreshKey = 0) { + const { api } = useAPI(); + + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [content, setContent] = useState(null); + const [path, setPath] = useState(null); + // True once a plan is on screen: offline (no client during a reconnect) then keeps it. + const hasPlanRef = useRef(false); + + useEffect(() => { + assert(workspaceId.trim().length > 0, "workspaceId is required to load plan preview"); + + if (!api) { + if (!hasPlanRef.current) { + setIsLoading(false); + setError("API unavailable"); + } + return; + } + + // A read with a client replaces the offline error. Without a plan on screen, it shows + // "Loading plan…" (the view may have opened while there was no client). + setError(null); + if (!hasPlanRef.current) { + setIsLoading(true); + } + + let cancelled = false; + + void readPlan(api, workspaceId).then((read) => { + // A lost connection (or this effect's own cleanup) keeps what is shown for the next client. + if (cancelled || read.status === "lost") { + return; + } + setIsLoading(false); + if (read.status === "error") { + setError(read.error); + return; + } + setError(null); + setContent(read.content); + setPath(read.path); + hasPlanRef.current = true; + }); + + return () => { + cancelled = true; + }; + }, [api, workspaceId, refreshKey]); + + return { isLoading, error, content, path }; +} diff --git a/src/browser/features/Settings/Sections/KeybindsSection.tsx b/src/browser/features/Settings/Sections/KeybindsSection.tsx index bc384cd46bb..90513a655f4 100644 --- a/src/browser/features/Settings/Sections/KeybindsSection.tsx +++ b/src/browser/features/Settings/Sections/KeybindsSection.tsx @@ -76,6 +76,7 @@ export const KEYBIND_LABELS: Record = { OPEN_TIMELINE_DIALOG: "Open Timeline tab (small viewports)", OPEN_STATS_DIALOG: "Open Stats tab (small viewports)", OPEN_ARTIFACTS_TAB: "Focus Artifacts tab, or hide the sidebar when focused", + OPEN_PLAN_TAB: "Open Plan tab", TOGGLE_AGENT_INTERFACE_VIEW: "Switch between status page and chat (Agent interface view)", TOGGLE_STATUS_TRANSCRIPT_PEEK: "Show or hide the transcript on the status page", STATUS_START_HERE: "Start here from the agent's last reply (status page)", @@ -281,6 +282,7 @@ export const KEYBIND_GROUPS: Array<{ "REVEAL_TIMELINE_EVENT", "OPEN_TIMELINE_DIALOG", "OPEN_STATS_DIALOG", + "OPEN_PLAN_TAB", ], }, { diff --git a/src/browser/utils/chatCommands.test.ts b/src/browser/utils/chatCommands.test.ts index 8efd42724b9..0603eae0c6c 100644 --- a/src/browser/utils/chatCommands.test.ts +++ b/src/browser/utils/chatCommands.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test, beforeEach, mock, spyOn } from "bun:test"; +import { CUSTOM_EVENTS } from "@/common/constants/events"; import type { HistoryEditPrecondition, ProvidersConfigMap, @@ -1662,82 +1663,28 @@ describe("compact and plan command results", () => { }); }); - test("plan open with no plan consumes with an error toast and skips the editor", async () => { - const getInfo = mock(() => Promise.resolve(null)); - const settled = await finishCommand( - await processSlashCommand( - { type: "plan-open" }, - createEnv({ - api: { - workspace: { - getPlanContent: mock(() => - Promise.resolve({ success: false, error: "No plan found" }) - ), - getInfo, - }, - } as unknown as SlashCommandEnv["api"], - }) - ) - ); - expectDisposition(settled.result, "consume"); - expectToast(settled.result.actions, { - type: "error", - message: "No plan found for this workspace", - }); - expect(getInfo).not.toHaveBeenCalled(); - }); - - test("plan open surfaces an editor-open failure as an error toast", async () => { + test("plan open opens the Plan tab without reading the plan or an editor", async () => { const getPlanContent = mock(() => Promise.resolve({ success: true, data: { content: "# My Plan", path: "/path/to/plan.md" } }) ); - const getInfo = mock(() => - Promise.resolve({ runtimeConfig: { type: "local" } } as unknown as FrontendWorkspaceMetadata) - ); - // openInEditor opens a blank placeholder window before its awaits; give it a - // live stub so the flow reaches the recordEditorOpen admission check, whose - // refusal is the deterministic failure path independent of deep-link launch. - const windowWithOpen = window as unknown as { open?: (...args: unknown[]) => unknown }; - const previousOpen = windowWithOpen.open; - windowWithOpen.open = () => ({ - closed: false, - close: () => undefined, - location: { href: "" }, - }); - // This suite aliases window to globalThis, which turns the tests/setup.ts - // location getter (window.location fallback) into infinite recursion when - // deep-link code reads location. Pin an own-value location for this test. - const previousLocation = Object.getOwnPropertyDescriptor(globalThis, "location"); - Object.defineProperty(globalThis, "location", { - configurable: true, - value: { href: "http://localhost/", hostname: "localhost" }, + ensureWindowDispatchEvent(); + const result = await processSlashCommand( + { type: "plan-open" }, + createEnv({ api: { workspace: { getPlanContent } } as unknown as SlashCommandEnv["api"] }) + ); + expect(result).toEqual({ + kind: "complete", + actions: [{ type: "clear-input" }], + inputDisposition: "consume", }); - try { - const settled = await finishCommand( - await processSlashCommand( - { type: "plan-open" }, - createEnv({ - api: { - workspace: { getPlanContent, getInfo }, - general: { - recordEditorOpen: mock(() => - Promise.resolve({ success: false, error: "Archive in progress" }) - ), - }, - } as unknown as SlashCommandEnv["api"], - }) - ) - ); - expectDisposition(settled.result, "consume"); - expectToast(settled.result.actions, { type: "error", message: "Archive in progress" }); - expect(getPlanContent).toHaveBeenCalledWith({ workspaceId: "test-ws" }); - expect(getInfo).toHaveBeenCalledWith({ workspaceId: "test-ws" }); - } finally { - windowWithOpen.open = previousOpen; - if (previousLocation) { - Object.defineProperty(globalThis, "location", previousLocation); - } - } + // The tab shows the plan, or that there is none yet: nothing to read or open here. + expect(window.dispatchEvent).toHaveBeenCalledWith( + expect.objectContaining({ + type: CUSTOM_EVENTS.OPEN_PLAN_TAB, + detail: { workspaceId: "test-ws" }, + }) + ); + expect(getPlanContent).not.toHaveBeenCalled(); }); }); diff --git a/src/browser/utils/chatCommands.ts b/src/browser/utils/chatCommands.ts index f04b8815d28..4256666e9a3 100644 --- a/src/browser/utils/chatCommands.ts +++ b/src/browser/utils/chatCommands.ts @@ -82,7 +82,7 @@ import { buildCompactionMessageText } from "@/common/utils/compaction/compaction import { getProviderModelEntryId } from "@/common/utils/providers/modelEntries"; import { isCustomProviderConfig } from "@/common/utils/providers/customProviders"; import { isValidProvider } from "@/common/constants/providers"; -import { openInEditor } from "@/browser/utils/openInEditor"; +import { openPlanTab } from "@/browser/utils/openPlanTab"; import { appendStagedAttachmentNotice, getStagedAttachments, @@ -2055,53 +2055,11 @@ function handlePlanShowCommand(env: WorkspaceCommandEnv): CommandResult { } function handlePlanOpenCommand(env: WorkspaceCommandEnv): CommandResult { - return phase([{ type: "clear-input" }], async () => { - try { - const planResult = await env.api.workspace.getPlanContent({ workspaceId: env.workspaceId }); - if (!planResult.success) { - return complete("consume", [ - showToast({ - id: Date.now().toString(), - type: "error", - message: "No plan found for this workspace", - }), - ]); - } - const workspaceInfo = await env.api.workspace.getInfo({ workspaceId: env.workspaceId }); - const openResult = await openInEditor({ - api: env.api, - workspaceId: env.workspaceId, - targetPath: planResult.data.path, - runtimeConfig: workspaceInfo?.runtimeConfig, - isFile: true, - }); - if (!openResult.success) { - return complete("consume", [ - showToast({ - id: Date.now().toString(), - type: "error", - message: openResult.error ?? "Failed to open editor", - }), - ]); - } - trackCommandUsed("plan"); - return complete("consume", [ - showToast({ - id: Date.now().toString(), - type: "success", - message: "Opened plan in editor", - }), - ]); - } catch (error) { - return complete("restore", [ - showToast({ - id: Date.now().toString(), - type: "error", - message: error instanceof Error ? error.message : "Failed to open plan", - }), - ]); - } - }); + // The Plan tab shows the plan, or that there is none yet; opening it in an editor is one of + // the tab's actions. + openPlanTab(env.workspaceId); + trackCommandUsed("plan"); + return complete("consume", [{ type: "clear-input" }]); } // ============================================================================ diff --git a/src/browser/utils/commands/sources.ts b/src/browser/utils/commands/sources.ts index 9680d0836ea..f0b996ea7ec 100644 --- a/src/browser/utils/commands/sources.ts +++ b/src/browser/utils/commands/sources.ts @@ -5,6 +5,7 @@ import type { APIClient } from "@/browser/contexts/API"; import type { ConfirmDialogOptions } from "@/browser/contexts/ConfirmDialogContext"; import { getContextResetSuccessMessage } from "@/browser/utils/contextResetFeedback"; import { showFeedbackToast as showCommandFeedbackToast } from "@/browser/utils/feedbackToast"; +import { NO_RUNNABLE_PLAN_MESSAGE, runLatestPlanAction } from "@/browser/utils/latestPlanAction"; import { formatKeybind, KEYBINDS } from "@/browser/utils/ui/keybinds"; import type { PinnedMoveDirection } from "@/browser/utils/ui/pinnedReorder"; import type { AutoRoutingDimension } from "@/browser/utils/aiSelectionIntent"; @@ -427,9 +428,6 @@ const SESSION_TAPES_PATH_TOAST_MS = 15_000; const NO_BACKGROUND_PROCESSES_MESSAGE = "No background processes are running in this workspace."; -const NO_RUNNABLE_PLAN_MESSAGE = - "No plan to implement: the latest plan's Implement / Continue in Auto is missing or disabled."; - // Module-level: palette sources are rebuilt on every render, so a closure flag would reset. let reportSlownessRunning = false; @@ -1670,14 +1668,7 @@ export function buildCoreSources(p: BuildSourcesParams): Array<() => CommandActi keywords: ["plan", "implement", "continue in auto", "propose_plan"], shortcutHint: formatKeybind(KEYBINDS.RUN_LATEST_PLAN_ACTION), run: () => { - // The latest plan card runs its enabled primary action and marks the request handled - // (#4963); listeners run synchronously inside dispatchEvent. - const request = createCustomEvent(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, { - workspaceId: id, - handled: false, - }); - window.dispatchEvent(request); - if (!request.detail.handled) { + if (!runLatestPlanAction(id)) { showCommandFeedbackToast({ type: "error", message: NO_RUNNABLE_PLAN_MESSAGE }); } }, diff --git a/src/browser/utils/latestPlanAction.ts b/src/browser/utils/latestPlanAction.ts new file mode 100644 index 00000000000..87e4dc971ea --- /dev/null +++ b/src/browser/utils/latestPlanAction.ts @@ -0,0 +1,18 @@ +import { CUSTOM_EVENTS, createCustomEvent } from "@/common/constants/events"; + +export const NO_RUNNABLE_PLAN_MESSAGE = + "No plan to implement: the latest plan's Implement / Continue in Auto is missing or disabled."; + +/** + * Run the latest plan card's primary action (Implement, or Continue in Auto in Auto mode) for a + * workspace. The card marks the request handled synchronously (#4963); false means no card could + * run it, and the caller says so (NO_RUNNABLE_PLAN_MESSAGE). + */ +export function runLatestPlanAction(workspaceId: string): boolean { + const request = createCustomEvent(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, { + workspaceId, + handled: false, + }); + window.dispatchEvent(request); + return request.detail.handled; +} diff --git a/src/browser/utils/openPlanTab.ts b/src/browser/utils/openPlanTab.ts new file mode 100644 index 00000000000..6b4375ebed6 --- /dev/null +++ b/src/browser/utils/openPlanTab.ts @@ -0,0 +1,10 @@ +import { CUSTOM_EVENTS, createCustomEvent } from "@/common/constants/events"; + +/** + * Open (and focus) the right sidebar's Plan tab for a workspace. RightSidebar adds or selects + * the tab and un-collapses the sidebar; on a narrow layout, where the sidebar is hidden, + * WorkspaceMenuBar shows the tab full-screen instead. + */ +export function openPlanTab(workspaceId: string): void { + window.dispatchEvent(createCustomEvent(CUSTOM_EVENTS.OPEN_PLAN_TAB, { workspaceId })); +} diff --git a/src/browser/utils/slashCommands/registry.ts b/src/browser/utils/slashCommands/registry.ts index cdf1088e32f..909423627aa 100644 --- a/src/browser/utils/slashCommands/registry.ts +++ b/src/browser/utils/slashCommands/registry.ts @@ -307,7 +307,7 @@ const vimCommandDefinition: SlashCommandDefinition = { const planOpenCommandDefinition: SlashCommandDefinition = { key: "open", - description: "Open plan in external editor", + description: "Open the plan in the sidebar's Plan tab", appendSpace: false, handler: (): ParsedCommand => ({ type: "plan-open" }), }; diff --git a/src/browser/utils/ui/keybinds.test.ts b/src/browser/utils/ui/keybinds.test.ts index 94d3a2fac36..b6647f4e94a 100644 --- a/src/browser/utils/ui/keybinds.test.ts +++ b/src/browser/utils/ui/keybinds.test.ts @@ -455,6 +455,7 @@ describe("global keybind collisions", () => { "TOGGLE_AGENT_INTERFACE_VIEW", "TOGGLE_STATUS_TRANSCRIPT_PEEK", "STATUS_START_HERE", + "OPEN_PLAN_TAB", "SIDEBAR_TAB_1", "SIDEBAR_TAB_2", "SIDEBAR_TAB_3", diff --git a/src/browser/utils/ui/keybinds.ts b/src/browser/utils/ui/keybinds.ts index 63b7655caaa..3a9f6a0a4d3 100644 --- a/src/browser/utils/ui/keybinds.ts +++ b/src/browser/utils/ui/keybinds.ts @@ -638,6 +638,9 @@ export const KEYBINDS = { /** Agent interface view: open Start Here from the agent's last reply, from the status page's bar */ STATUS_START_HERE: { key: "h", code: "KeyH", ctrl: true, alt: true, shift: true }, + /** Open (or focus) the Plan tab in the right sidebar */ + OPEN_PLAN_TAB: { key: "B", ctrl: true, shift: true }, + // Artifacts tab shortcuts: only handled while focus is inside the Artifacts panel, // like the Review panel's single-key hunk navigation. /** Toggle fullscreen for the selected artifact */ diff --git a/src/common/constants/events.ts b/src/common/constants/events.ts index 62fc2ca636a..7ba7223ee38 100644 --- a/src/common/constants/events.ts +++ b/src/common/constants/events.ts @@ -137,6 +137,12 @@ export const CUSTOM_EVENTS = { */ OPEN_GOAL_TAB: "mux:openGoalTab", + /** + * Event to open the right-sidebar Plan tab ("/plan open", the Stats tab's plan row). + * Detail: { workspaceId: string } + */ + OPEN_PLAN_TAB: "mux:openPlanTab", + /** * Open (and focus) a New tab in the focused right-sidebar pane, the same path as "+" and the * keyboard shortcut. Detail: { workspaceId: string } @@ -283,6 +289,9 @@ export interface CustomEventPayloads { workspaceId: string; openCompleteInput?: boolean; }; + [CUSTOM_EVENTS.OPEN_PLAN_TAB]: { + workspaceId: string; + }; [CUSTOM_EVENTS.OPEN_NEW_SIDEBAR_TAB]: { workspaceId: string; }; diff --git a/src/common/constants/storage.ts b/src/common/constants/storage.ts index 8385540ad35..3a8565bfdfd 100644 --- a/src/common/constants/storage.ts +++ b/src/common/constants/storage.ts @@ -595,6 +595,16 @@ export function getRightSidebarLayoutKey(workspaceId: string): string { return `right-sidebar:layout:${workspaceId}`; } +/** + * Scroll offset of the right sidebar's Plan tab per workspace. The tab unmounts when the user + * leaves the workspace or switches tabs, so the offset is saved then and restored once the plan + * renders again, like the mobile left sidebar's list position. + * Format: "plan-tab:scroll-top:{workspaceId}" + */ +export function getPlanTabScrollTopKey(workspaceId: string): string { + return `plan-tab:scroll-top:${workspaceId}`; +} + /** * Artifacts tab selection for the most recently used workspaces, as one global map * `{ [workspaceId]: { scope, path } }` (artifactSelection.ts). Per-workspace keys would @@ -873,6 +883,7 @@ export const PERSISTED_KEY_REGISTRY: readonly PersistedKeyRegistration[] = [ workspaceKey(getReviewSearchStateKey, "workspace-scoped", true, REVIEW_SEARCH_STATE_MAX_CHARS), workspaceKey(getReviewImmersiveKey, "workspace-scoped", true, 16), workspaceKey(getWorkspaceLastReadKey, "workspace-scoped", true, 32), + workspaceKey(getPlanTabScrollTopKey, "workspace-scoped", true, 16), // Not a cache: a status_set result compacted out of history cannot be re-derived after reload // (see StreamingMessageAggregator.loadPersistedAgentStatus), so it must never be evicted. // ~28 skeleton + the STATUS_STATE_*_MAX_CHARS field caps. diff --git a/src/node/services/agentSkills/builtInSkillContent.generated.ts b/src/node/services/agentSkills/builtInSkillContent.generated.ts index 2ddf67c56bb..6c79a1c245d 100644 --- a/src/node/services/agentSkills/builtInSkillContent.generated.ts +++ b/src/node/services/agentSkills/builtInSkillContent.generated.ts @@ -4145,6 +4145,14 @@ export const BUILTIN_SKILL_FILES: Record> = { "", "## UI Features", "", + "The right sidebar's **Plan** tab shows the plan file next to the chat. It reads the file again", + "when a turn ends and when the window regains focus, so a plan the agent is writing, or one you", + "edited in an external editor, stays current. Open it from a New tab in the sidebar, with", + "`/plan open`, with `Ctrl+Shift+B` (`Cmd+Shift+B` on Mac), or from the **Plan file** row in the", + "Stats tab's post-compaction context. The tab has the plan card's main actions: **Implement**,", + "**Edit** (opens the file in your external editor) and **Copy**. `/plan` shows the plan in the", + "chat instead.", + "", "The `propose_plan` tool call in chat includes:", "", "- **Rendered Markdown**: View the plan with proper formatting.", @@ -5071,9 +5079,10 @@ export const BUILTIN_SKILL_FILES: Record> = { "| Toggle left sidebar | `Ctrl+P` |", "| Toggle right sidebar | `Ctrl+Shift+B` |", "| New right sidebar tab (lists the tools) | `Ctrl+Alt+N` |", + "| Open the Plan tab | `Ctrl+Shift+B` |", "| Close the right sidebar's active tab | `Ctrl+W` |", "", - "The right sidebar shows only the tabs you open. A new tab lists the tools it can show (Stats, Review, Instructions, Goal, Terminal, and more); pick one to open it in that tab's place. The **+** button after the last tab opens a new tab. Closing the last tab closes the sidebar. The chevron at the right end of the tab strip lists your open tabs.", + "The right sidebar shows only the tabs you open. A new tab lists the tools it can show (Stats, Review, Instructions, Plan, Goal, Terminal, and more); pick one to open it in that tab's place. The **+** button after the last tab opens a new tab. Closing the last tab closes the sidebar. The chevron at the right end of the tab strip lists your open tabs.", "", "### Command Palette", "", From e59f1c2f8edf3c7a76bc85d696ecb74bb343a57e Mon Sep 17 00:00:00 2001 From: asm <113964+asm@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:46:14 -0700 Subject: [PATCH 02/11] =?UTF-8?q?=F0=9F=A4=96=20fix:=20clear=20a=20stale?= =?UTF-8?q?=20plan=20on=20read=20errors=20and=20seed=20the=20saved=20scrol?= =?UTF-8?q?l=20offset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-ups: a re-read that fails (the plan file deleted after it was shown) clears the shown plan, so the actions disable instead of copying or opening stale content; the scroll ref starts from the saved offset, so an unmount before the plan rendered no longer saves 0 over it; the story shell reads its props through `props`. Co-Authored-By: Claude Fable 5.1 --- .../features/RightSidebar/PlanTab.stories.tsx | 9 ++-- .../features/RightSidebar/PlanTab.test.tsx | 41 +++++++++++++++++++ src/browser/features/RightSidebar/PlanTab.tsx | 20 ++++----- .../features/RightSidebar/usePlanFile.ts | 10 ++++- 4 files changed, 62 insertions(+), 18 deletions(-) diff --git a/src/browser/features/RightSidebar/PlanTab.stories.tsx b/src/browser/features/RightSidebar/PlanTab.stories.tsx index 83f2b444027..d04bf51ec39 100644 --- a/src/browser/features/RightSidebar/PlanTab.stories.tsx +++ b/src/browser/features/RightSidebar/PlanTab.stories.tsx @@ -25,17 +25,14 @@ Show the workspace's plan next to the chat, with the plan card's main actions. 2. Re-read it when a turn ends or the window regains focus. 3. Keep **Implement**, **Edit** and **Copy** one click away.`; -const PlanStoryShell: FC<{ setup: () => APIClient; children: ReactNode }> = ({ - setup, - children, -}) => { +const PlanStoryShell: FC<{ setup: () => APIClient; children: ReactNode }> = (props) => { const clientRef = useRef(null); - clientRef.current ??= setup(); + clientRef.current ??= props.setup(); return ( - {children} + {props.children} ); diff --git a/src/browser/features/RightSidebar/PlanTab.test.tsx b/src/browser/features/RightSidebar/PlanTab.test.tsx index fee20113e3b..15ca6a6808d 100644 --- a/src/browser/features/RightSidebar/PlanTab.test.tsx +++ b/src/browser/features/RightSidebar/PlanTab.test.tsx @@ -9,6 +9,8 @@ import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react import type { APIClient } from "@/browser/contexts/API"; import { createTestApiClient, type TestApiOverrides } from "@/browser/testUtils"; import { CUSTOM_EVENTS, type CustomEventType } from "@/common/constants/events"; +import { readPersistedState, updatePersistedState } from "@/browser/hooks/usePersistedState"; +import { getPlanTabScrollTopKey } from "@/common/constants/storage"; type GetPlanContentResult = | { success: true; data: { content: string; path: string } } @@ -189,6 +191,45 @@ describe("PlanTab", () => { expect(other.getByTestId("plan-tab-body").scrollTop).toBe(0); }); + test("a saved scroll offset survives an unmount before the plan loaded", () => { + const key = getPlanTabScrollTopKey("workspace-1"); + updatePersistedState(key, 120, 0); + // The read never settles: a slow remote runtime. + mockApi = { workspace: { getPlanContent: mock(() => new Promise(() => undefined)) } }; + + const view = renderWithApi(); + expect(view.getByText("Loading plan…")).toBeTruthy(); + view.unmount(); + + expect(readPersistedState(key, 0)).toBe(120); + }); + + test("a re-read that fails clears the shown plan and disables its actions", async () => { + let read: GetPlanContentResult = planResult("# Plan"); + const getPlanContent = mock(() => Promise.resolve(read)); + mockApi = { workspace: { getPlanContent } }; + + const view = renderWithApi(); + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Plan"); + }); + + // The file was deleted after it was shown. + read = { success: false, error: "Plan file not found at /tmp/plan.md" }; + act(() => { + window.dispatchEvent(new window.Event("focus")); + }); + + await waitFor(() => { + expect(view.getByTestId("plan-tab-error").textContent).toContain("Plan file not found"); + }); + expect(view.queryByTestId("plan-markdown-core")).toBeNull(); + expect(view.queryByTestId("plan-tab-path")).toBeNull(); + expect(view.getByRole("button", { name: "Implement" }).hasAttribute("disabled")).toBe(true); + expect(view.getByRole("button", { name: "Edit" }).hasAttribute("disabled")).toBe(true); + expect(view.getByRole("button", { name: "Copy" }).hasAttribute("disabled")).toBe(true); + }); + test("renders API-unavailable state when not connected", async () => { mockApi = null; diff --git a/src/browser/features/RightSidebar/PlanTab.tsx b/src/browser/features/RightSidebar/PlanTab.tsx index 95454cea8cd..1b9e3283dd7 100644 --- a/src/browser/features/RightSidebar/PlanTab.tsx +++ b/src/browser/features/RightSidebar/PlanTab.tsx @@ -64,18 +64,18 @@ function PlanTabBody(props: { workspaceId: string }) { const hasPlan = content !== null && content.length > 0; // Leaving the workspace or switching tabs unmounts this body: keep the plan's scroll offset - // per workspace. Tracked while scrolling, saved on unmount, restored once the plan renders - // (the body has its height only then). A re-read keeps the body, so its offset stays. + // per workspace. The ref starts from the saved offset, so an unmount before the plan rendered + // (a slow read, no client) saves it back unchanged; scrolling updates it, unmount saves it, + // and the restore runs once the plan renders (the body has its height only then). A re-read + // keeps the body, so its offset stays. const bodyRef = useRef(null); - const scrollTopRef = useRef(0); + const [savedScrollTop] = useState(() => + normalizeScrollTop(readPersistedState(getPlanTabScrollTopKey(workspaceId), 0)) + ); + const scrollTopRef = useRef(savedScrollTop); useEffect(() => { - if (!hasPlan) return; - const saved = normalizeScrollTop( - readPersistedState(getPlanTabScrollTopKey(workspaceId), 0) - ); - scrollTopRef.current = saved; - if (bodyRef.current) bodyRef.current.scrollTop = saved; - }, [hasPlan, workspaceId]); + if (hasPlan && bodyRef.current) bodyRef.current.scrollTop = scrollTopRef.current; + }, [hasPlan]); useEffect(() => { return () => { updatePersistedState(getPlanTabScrollTopKey(workspaceId), scrollTopRef.current, 0); diff --git a/src/browser/features/RightSidebar/usePlanFile.ts b/src/browser/features/RightSidebar/usePlanFile.ts index 7bf6a6a5dd6..34570ae8d5d 100644 --- a/src/browser/features/RightSidebar/usePlanFile.ts +++ b/src/browser/features/RightSidebar/usePlanFile.ts @@ -29,8 +29,8 @@ export async function readPlan(api: APIClient, workspaceId: string): Promise Date: Mon, 19 Oct 2026 17:02:51 -0700 Subject: [PATCH 03/11] =?UTF-8?q?=F0=9F=A4=96=20fix:=20Plan=20tab=20shortc?= =?UTF-8?q?uts,=20editor-launch=20errors,=20narrow-layout=20hold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-ups: the Plan tab has scoped shortcuts (E opens the plan file in the editor, Y copies it) and takes focus when its shortcut opens it, like the Artifacts panel; a rejected editor launch (remote editor discovery during a dropped connection) shows a toast instead of an unhandled rejection; and OPEN_PLAN_TAB joins the held-input exemption for the narrow layout, where WorkspaceMenuBar already acts on it. Co-Authored-By: Claude Fable 5.1 --- docs/config/keybinds.mdx | 11 ++- .../WorkspaceShell/deferredSidebarInput.ts | 10 ++- .../features/RightSidebar/PlanTab.test.tsx | 44 ++++++++++ src/browser/features/RightSidebar/PlanTab.tsx | 80 ++++++++++++++----- .../features/RightSidebar/RightSidebar.tsx | 17 +++- .../RightSidebar/Tabs/tabRegistry.tsx | 11 ++- .../Settings/Sections/KeybindsSection.tsx | 7 +- src/browser/utils/ui/keybinds.ts | 7 ++ .../builtInSkillContent.generated.ts | 11 ++- 9 files changed, 170 insertions(+), 28 deletions(-) diff --git a/docs/config/keybinds.mdx b/docs/config/keybinds.mdx index 35b644b0133..12973afa99a 100644 --- a/docs/config/keybinds.mdx +++ b/docs/config/keybinds.mdx @@ -83,7 +83,6 @@ While a workspace's actions menu (`⋮` in the sidebar row, `…` in the header) | Toggle left sidebar | `Ctrl+P` | | Toggle right sidebar | `Ctrl+Shift+B` | | New right sidebar tab (lists the tools) | `Ctrl+Alt+N` | -| Open the Plan tab | `Ctrl+Shift+B` | | Close the right sidebar's active tab | `Ctrl+W` | The right sidebar shows only the tabs you open. A new tab lists the tools it can show (Stats, Review, Instructions, Plan, Goal, Terminal, and more); pick one to open it in that tab's place. The **+** button after the last tab opens a new tab. Closing the last tab closes the sidebar. The chevron at the right end of the tab strip lists your open tabs. @@ -98,6 +97,16 @@ The command palette (`Ctrl+Shift+P`) has two modes: This separation keeps the switcher clean and fast while making all other commands easily accessible via `>`. +### Plan tab + +The shortcuts other than opening the tab apply while focus is inside the Plan tab. + +| Action | Shortcut | +| --------------------------------- | -------------- | +| Open the Plan tab | `Ctrl+Shift+B` | +| Open the plan file in your editor | `E` | +| Copy the plan | `Y` | + ### Artifacts tab (experimental) These work when the **Artifacts** experiment is on. Shortcuts other than opening the tab only apply while focus is inside the Artifacts tab (inside an HTML or SVG preview, `Shift+F` and `Esc` only exit fullscreen). On narrow windows, where the right sidebar is hidden, `Ctrl+Shift+K` shows the sidebar full-screen on the Artifacts tab. The image zoom shortcuts apply while focus is on the image or its zoom controls. diff --git a/src/browser/components/WorkspaceShell/deferredSidebarInput.ts b/src/browser/components/WorkspaceShell/deferredSidebarInput.ts index cd9cfb58ab3..9adc2a6cfc1 100644 --- a/src/browser/components/WorkspaceShell/deferredSidebarInput.ts +++ b/src/browser/components/WorkspaceShell/deferredSidebarInput.ts @@ -80,11 +80,13 @@ export function holdSidebarInput(held: HeldSidebarInput[]): () => void { function holdEventInto(held: HeldSidebarInput[]): (e: Event) => void { return (e) => { - // While the layout hides the sidebar, RightSidebar ignores these two and WorkspaceMenuBar acts - // on them. Chromium may already have run the menu bar's listener (window listeners run in - // registration order at the window target), so a replay would act twice (#6208). + // While the layout hides the sidebar, WorkspaceMenuBar acts on these events (it shows the + // tab full-screen). Chromium may already have run the menu bar's listener (window listeners + // run in registration order at the window target), so a replay would act twice (#6208). const menuBarEvent = - e.type === CUSTOM_EVENTS.OPEN_ARTIFACT || e.type === CUSTOM_EVENTS.OPEN_MCP_APP_VIEW; + e.type === CUSTOM_EVENTS.OPEN_ARTIFACT || + e.type === CUSTOM_EVENTS.OPEN_MCP_APP_VIEW || + e.type === CUSTOM_EVENTS.OPEN_PLAN_TAB; if ( menuBarEvent && isWorkspaceRightSidebarHidden(document.querySelector("[data-workspace-shell]")) diff --git a/src/browser/features/RightSidebar/PlanTab.test.tsx b/src/browser/features/RightSidebar/PlanTab.test.tsx index 15ca6a6808d..6f9950a897c 100644 --- a/src/browser/features/RightSidebar/PlanTab.test.tsx +++ b/src/browser/features/RightSidebar/PlanTab.test.tsx @@ -1,5 +1,6 @@ import * as RealMarkdownCore from "../Messages/MarkdownCore"; import * as RealMarkdownRenderer from "../Messages/MarkdownRenderer"; +import * as RealClipboard from "@/browser/utils/clipboard"; import { APIContext, APIProvider } from "@/browser/contexts/API"; import type { ReactElement, ReactNode } from "react"; import { PlanTab } from "./PlanTab"; @@ -22,8 +23,12 @@ let mockApi: TestApiOverrides | null = null; const realModules: Array<[string, Record]> = [ ["@/browser/features/Messages/MarkdownCore", { ...RealMarkdownCore }], ["@/browser/features/Messages/MarkdownRenderer", { ...RealMarkdownRenderer }], + ["@/browser/utils/clipboard", { ...RealClipboard }], ]; +/** What the mocked clipboard received. */ +let clipboardWrites: string[] = []; + async function installModuleMocks() { await mock.module("@/browser/features/Messages/MarkdownCore", () => ({ MarkdownCore: (props: { content: string }) => ( @@ -36,6 +41,14 @@ async function installModuleMocks() {
{props.children}
), })); + + await mock.module("@/browser/utils/clipboard", () => ({ + ...RealClipboard, + copyToClipboard: (text: string) => { + clipboardWrites.push(text); + return Promise.resolve(); + }, + })); } // Inject the client through the real provider (a module mock of contexts/API is process-wide). @@ -82,6 +95,7 @@ describe("PlanTab", () => { globalThis.window = new GlobalWindow() as unknown as Window & typeof globalThis; globalThis.document = globalThis.window.document; mockApi = null; + clipboardWrites = []; }); afterEach(async () => { @@ -230,6 +244,36 @@ describe("PlanTab", () => { expect(view.getByRole("button", { name: "Copy" }).hasAttribute("disabled")).toBe(true); }); + test("single-key shortcuts act while the tab has focus, not from a text field", async () => { + mockApi = { workspace: { getPlanContent: mock(() => Promise.resolve(planResult("# Plan"))) } }; + const view = renderWithApi(); + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Plan"); + }); + + const panel = view.getByTestId("plan-tab"); + fireEvent.keyDown(panel, { key: "y" }); + expect(clipboardWrites).toEqual(["# Plan"]); + + // A text field inside the tab keeps its letters. + const field = document.createElement("input"); + panel.appendChild(field); + fireEvent.keyDown(field, { key: "y" }); + expect(clipboardWrites).toEqual(["# Plan"]); + }); + + test("takes focus when opened by its shortcut, once", async () => { + mockApi = { workspace: { getPlanContent: mock(() => Promise.resolve(planResult("# Plan"))) } }; + const consumed = mock(() => undefined); + const view = renderWithApi( + + ); + await waitFor(() => { + expect(document.activeElement).toBe(view.getByTestId("plan-tab")); + }); + expect(consumed).toHaveBeenCalledTimes(1); + }); + test("renders API-unavailable state when not connected", async () => { mockApi = null; diff --git a/src/browser/features/RightSidebar/PlanTab.tsx b/src/browser/features/RightSidebar/PlanTab.tsx index 1b9e3283dd7..c07aa282e31 100644 --- a/src/browser/features/RightSidebar/PlanTab.tsx +++ b/src/browser/features/RightSidebar/PlanTab.tsx @@ -10,12 +10,17 @@ import { useOptionalWorkspaceSidebarState } from "@/browser/stores/WorkspaceStor import { showFeedbackToast } from "@/browser/utils/feedbackToast"; import { NO_RUNNABLE_PLAN_MESSAGE, runLatestPlanAction } from "@/browser/utils/latestPlanAction"; import { openInEditor } from "@/browser/utils/openInEditor"; +import { isEditableElement, KEYBINDS, matchesKeybind } from "@/browser/utils/ui/keybinds"; import { getPlanTabScrollTopKey } from "@/common/constants/storage"; +import { getErrorMessage } from "@/common/utils/errors"; import { TAB_ICONS } from "./Tabs/tabIcons"; import { usePlanFile } from "./usePlanFile"; interface PlanTabProps { workspaceId: string; + /** Set when a shortcut opened the tab: the panel takes focus so its single-key shortcuts work. */ + autoFocus?: boolean; + onAutoFocusConsumed?: () => void; } /** @@ -24,7 +29,12 @@ interface PlanTabProps { * from an empty body instead of showing the previous plan while its own loads. */ export const PlanTab: React.FC = (props) => ( - + ); /** The plan reader's wording for a workspace without a plan (getWorkspacePlanContent). */ @@ -37,7 +47,7 @@ function normalizeScrollTop(value: unknown): number { const ACTION_CLASS = "text-subtle hover:text-foreground inline-flex items-center gap-1 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50"; -function PlanTabBody(props: { workspaceId: string }) { +function PlanTabBody(props: PlanTabProps) { const { workspaceId } = props; const api = useLiveAPI(); const runtimeConfig = @@ -90,20 +100,59 @@ function PlanTabBody(props: { workspaceId: string }) { const handleOpenInEditor = async () => { if (path === null) return; - const result = await openInEditor({ - api, - workspaceId, - targetPath: path, - runtimeConfig, - isFile: true, - }); - if (!result.success) { - showFeedbackToast({ type: "error", message: result.error ?? "Failed to open editor" }); + try { + const result = await openInEditor({ + api, + workspaceId, + targetPath: path, + runtimeConfig, + isFile: true, + }); + if (!result.success) { + showFeedbackToast({ type: "error", message: result.error ?? "Failed to open editor" }); + } + } catch (error) { + // Editor discovery for a remote or devcontainer workspace rejects when the connection + // drops mid-call; the user still needs to hear why nothing opened. + showFeedbackToast({ type: "error", message: getErrorMessage(error) }); + } + }; + + const handleCopy = () => { + if (hasPlan) void copyToClipboard(content ?? ""); + }; + + // Opened by its shortcut: take focus so the single-key shortcuts below work at once. + const panelRef = useRef(null); + const { autoFocus, onAutoFocusConsumed } = props; + useEffect(() => { + if (autoFocus !== true) return; + panelRef.current?.focus(); + onAutoFocusConsumed?.(); + }, [autoFocus, onAutoFocusConsumed]); + + // Single-key shortcuts while focus is inside the tab, never from a text field. + const handleKeyDown = (event: React.KeyboardEvent) => { + if (isEditableElement(event.target)) return; + if (matchesKeybind(event, KEYBINDS.PLAN_TAB_EDIT)) { + if (path === null) return; + event.preventDefault(); + void handleOpenInEditor(); + } else if (matchesKeybind(event, KEYBINDS.PLAN_TAB_COPY)) { + if (!hasPlan) return; + event.preventDefault(); + handleCopy(); } }; return ( -
+
@@ -129,12 +178,7 @@ function PlanTabBody(props: { workspaceId: string }) { Edit - diff --git a/src/browser/features/RightSidebar/RightSidebar.tsx b/src/browser/features/RightSidebar/RightSidebar.tsx index aababd297a2..de5a27123d5 100644 --- a/src/browser/features/RightSidebar/RightSidebar.tsx +++ b/src/browser/features/RightSidebar/RightSidebar.tsx @@ -705,6 +705,9 @@ interface RightSidebarTabsetNodeProps { /** The Artifacts panel should take focus once it renders (opened via shortcut). */ autoFocusArtifacts: boolean; onArtifactsAutoFocusConsumed: () => void; + /** The Plan panel should take focus once it renders (opened via shortcut). */ + autoFocusPlan: boolean; + onPlanAutoFocusConsumed: () => void; // RightSidebar / GoalTab UI requests user-facing transitions only; // `budget_limited` is internal-only. onGoalSetStatus: ( @@ -953,6 +956,10 @@ const RightSidebarTabsetNode: React.FC = (props) => autoFocus: props.autoFocusArtifacts, onAutoFocusConsumed: props.onArtifactsAutoFocusConsumed, }, + plan: { + autoFocus: props.autoFocusPlan, + onAutoFocusConsumed: props.onPlanAutoFocusConsumed, + }, goal: { snapshot: props.goal, openCompleteInputRequest: props.goalCompleteInputRequest, @@ -1503,6 +1510,7 @@ const RightSidebarComponent: React.FC = ({ // panel claims focus once it renders, like terminals do with autoFocusTerminalSession. The // value is the pane whose copy claims it (Artifacts, like Review, can be open in two panes). const [artifactsFocusTabsetId, setArtifactsFocusTabsetId] = React.useState(null); + const [planFocusTabsetId, setPlanFocusTabsetId] = React.useState(null); const llmDebugLogsEnabled = useLlmDebugLogsEnabled(api); const desktopAvailable = useDesktopAvailable(api, desktopExperimentEnabled, workspaceId); @@ -1971,11 +1979,13 @@ const RightSidebarComponent: React.FC = ({ } e.preventDefault(); setCollapsed(false); - setLayout((prev) => selectOrAddTab(prev, "plan")); + const next = selectOrAddTab(getBaseLayout(), "plan"); + setLayout(() => next); + setPlanFocusTabsetId(next.focusedTabsetId); }; window.addEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler); - }, [setCollapsed, setLayout]); + }, [getBaseLayout, setCollapsed, setLayout]); // Auto-surface the Workflows tab when a run starts: the tab is the primary // run-detail surface (the chat card stays collapsed while it exists), but a @@ -2525,6 +2535,7 @@ const RightSidebarComponent: React.FC = ({ const focusPickedTool = (tabsetId: string, tool: TabType) => { if (tool === "review") setReviewFocusRequest((prev) => nextReviewFocusRequest(prev, tabsetId)); else if (tool === "artifacts") setArtifactsFocusTabsetId(tabsetId); + else if (tool === "plan") setPlanFocusTabsetId(tabsetId); else setTabToFocus(tool); }; @@ -2927,6 +2938,8 @@ const RightSidebarComponent: React.FC = ({ goalCompleteInputRequest={goalCompleteInputRequest} autoFocusArtifacts={artifactsAutoFocusTabsetId === node.id} onArtifactsAutoFocusConsumed={() => setArtifactsFocusTabsetId(null)} + autoFocusPlan={planFocusTabsetId === node.id} + onPlanAutoFocusConsumed={() => setPlanFocusTabsetId(null)} onGoalSetStatus={handleGoalSetStatus} onGoalUpdateObjective={handleGoalUpdateObjective} onGoalUpdateBudget={handleGoalUpdateBudget} diff --git a/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx b/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx index f029284fde1..f55102708b5 100644 --- a/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx +++ b/src/browser/features/RightSidebar/Tabs/tabRegistry.tsx @@ -131,6 +131,11 @@ export interface TabPanelContext { autoFocus: boolean; onAutoFocusConsumed: () => void; }; + plan: { + /** Set when a shortcut opened the tab: the panel takes focus so its single-key shortcuts work. */ + autoFocus: boolean; + onAutoFocusConsumed: () => void; + }; goal: { snapshot: GoalSnapshot | null; openCompleteInputRequest: number; @@ -194,7 +199,11 @@ const TAB_RENDERERS = { Label: PlanTabLabel, renderPanel: (ctx) => ( - + ), }, diff --git a/src/browser/features/Settings/Sections/KeybindsSection.tsx b/src/browser/features/Settings/Sections/KeybindsSection.tsx index 90513a655f4..716312df7fd 100644 --- a/src/browser/features/Settings/Sections/KeybindsSection.tsx +++ b/src/browser/features/Settings/Sections/KeybindsSection.tsx @@ -77,6 +77,8 @@ export const KEYBIND_LABELS: Record = { OPEN_STATS_DIALOG: "Open Stats tab (small viewports)", OPEN_ARTIFACTS_TAB: "Focus Artifacts tab, or hide the sidebar when focused", OPEN_PLAN_TAB: "Open Plan tab", + PLAN_TAB_EDIT: "Open the plan file in the editor (Plan tab)", + PLAN_TAB_COPY: "Copy the plan (Plan tab)", TOGGLE_AGENT_INTERFACE_VIEW: "Switch between status page and chat (Agent interface view)", TOGGLE_STATUS_TRANSCRIPT_PEEK: "Show or hide the transcript on the status page", STATUS_START_HERE: "Start here from the agent's last reply (status page)", @@ -282,9 +284,12 @@ export const KEYBIND_GROUPS: Array<{ "REVEAL_TIMELINE_EVENT", "OPEN_TIMELINE_DIALOG", "OPEN_STATS_DIALOG", - "OPEN_PLAN_TAB", ], }, + { + label: "Plan tab", + keys: ["OPEN_PLAN_TAB", "PLAN_TAB_EDIT", "PLAN_TAB_COPY"], + }, { label: "Artifacts", keys: [ diff --git a/src/browser/utils/ui/keybinds.ts b/src/browser/utils/ui/keybinds.ts index 3a9f6a0a4d3..39db935cb18 100644 --- a/src/browser/utils/ui/keybinds.ts +++ b/src/browser/utils/ui/keybinds.ts @@ -863,6 +863,13 @@ export const KEYBINDS = { /** Copy the active file's full contents to the clipboard in immersive review */ REVIEW_COPY_FILE: { key: "y" }, + // Plan tab shortcuts: only handled while focus is inside the Plan tab, like the Artifacts + // panel's single-key shortcuts. + /** Open the plan file in the external editor (Plan tab) */ + PLAN_TAB_EDIT: { key: "e" }, + /** Copy the plan to the clipboard (Plan tab) */ + PLAN_TAB_COPY: { key: "y" }, + /** Toggle plan annotation mode in propose_plan */ TOGGLE_PLAN_ANNOTATE: { key: "a", shift: true }, diff --git a/src/node/services/agentSkills/builtInSkillContent.generated.ts b/src/node/services/agentSkills/builtInSkillContent.generated.ts index 6c79a1c245d..637dc2d4f7d 100644 --- a/src/node/services/agentSkills/builtInSkillContent.generated.ts +++ b/src/node/services/agentSkills/builtInSkillContent.generated.ts @@ -5079,7 +5079,6 @@ export const BUILTIN_SKILL_FILES: Record> = { "| Toggle left sidebar | `Ctrl+P` |", "| Toggle right sidebar | `Ctrl+Shift+B` |", "| New right sidebar tab (lists the tools) | `Ctrl+Alt+N` |", - "| Open the Plan tab | `Ctrl+Shift+B` |", "| Close the right sidebar's active tab | `Ctrl+W` |", "", "The right sidebar shows only the tabs you open. A new tab lists the tools it can show (Stats, Review, Instructions, Plan, Goal, Terminal, and more); pick one to open it in that tab's place. The **+** button after the last tab opens a new tab. Closing the last tab closes the sidebar. The chevron at the right end of the tab strip lists your open tabs.", @@ -5094,6 +5093,16 @@ export const BUILTIN_SKILL_FILES: Record> = { "", "This separation keeps the switcher clean and fast while making all other commands easily accessible via `>`.", "", + "### Plan tab", + "", + "The shortcuts other than opening the tab apply while focus is inside the Plan tab.", + "", + "| Action | Shortcut |", + "| --------------------------------- | -------------- |", + "| Open the Plan tab | `Ctrl+Shift+B` |", + "| Open the plan file in your editor | `E` |", + "| Copy the plan | `Y` |", + "", "### Artifacts tab (experimental)", "", "These work when the **Artifacts** experiment is on. Shortcuts other than opening the tab only apply while focus is inside the Artifacts tab (inside an HTML or SVG preview, `Shift+F` and `Esc` only exit fullscreen). On narrow windows, where the right sidebar is hidden, `Ctrl+Shift+K` shows the sidebar full-screen on the Artifacts tab. The image zoom shortcuts apply while focus is on the image or its zoom controls.", From 9cf2e1832ff6c88d9f783655f5446e7c3d9d68e0 Mon Sep 17 00:00:00 2001 From: asm <113964+asm@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:40:27 -0700 Subject: [PATCH 04/11] =?UTF-8?q?=F0=9F=A4=96=20fix:=20move=20the=20Plan?= =?UTF-8?q?=20tab=20shortcut=20off=20the=20right=20sidebar=20toggle's=20ch?= =?UTF-8?q?ord?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upstream bound Ctrl+Shift+B to "Toggle right sidebar"; the Plan tab now opens with Ctrl+Alt+Shift+P (Cmd+Option+Shift+P on Mac), next to the other Ctrl+Alt+Shift workspace shortcuts. Co-Authored-By: Claude Fable 5.1 --- docs/agents/plan-mode.mdx | 2 +- docs/config/keybinds.mdx | 10 +++++----- src/browser/utils/ui/keybinds.ts | 2 +- .../agentSkills/builtInSkillContent.generated.ts | 12 ++++++------ 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/agents/plan-mode.mdx b/docs/agents/plan-mode.mdx index 8245ac6efdc..bd8c0d07db9 100644 --- a/docs/agents/plan-mode.mdx +++ b/docs/agents/plan-mode.mdx @@ -112,7 +112,7 @@ Availability: The right sidebar's **Plan** tab shows the plan file next to the chat. It reads the file again when a turn ends and when the window regains focus, so a plan the agent is writing, or one you edited in an external editor, stays current. Open it from a New tab in the sidebar, with -`/plan open`, with `Ctrl+Shift+B` (`Cmd+Shift+B` on Mac), or from the **Plan file** row in the +`/plan open`, with `Ctrl+Alt+Shift+P` (`Cmd+Option+Shift+P` on Mac), or from the **Plan file** row in the Stats tab's post-compaction context. The tab has the plan card's main actions: **Implement**, **Edit** (opens the file in your external editor) and **Copy**. `/plan` shows the plan in the chat instead. diff --git a/docs/config/keybinds.mdx b/docs/config/keybinds.mdx index 12973afa99a..630b71f9c14 100644 --- a/docs/config/keybinds.mdx +++ b/docs/config/keybinds.mdx @@ -101,11 +101,11 @@ This separation keeps the switcher clean and fast while making all other command The shortcuts other than opening the tab apply while focus is inside the Plan tab. -| Action | Shortcut | -| --------------------------------- | -------------- | -| Open the Plan tab | `Ctrl+Shift+B` | -| Open the plan file in your editor | `E` | -| Copy the plan | `Y` | +| Action | Shortcut | +| --------------------------------- | ------------------ | +| Open the Plan tab | `Ctrl+Alt+Shift+P` | +| Open the plan file in your editor | `E` | +| Copy the plan | `Y` | ### Artifacts tab (experimental) diff --git a/src/browser/utils/ui/keybinds.ts b/src/browser/utils/ui/keybinds.ts index 39db935cb18..614e2b73cb8 100644 --- a/src/browser/utils/ui/keybinds.ts +++ b/src/browser/utils/ui/keybinds.ts @@ -639,7 +639,7 @@ export const KEYBINDS = { STATUS_START_HERE: { key: "h", code: "KeyH", ctrl: true, alt: true, shift: true }, /** Open (or focus) the Plan tab in the right sidebar */ - OPEN_PLAN_TAB: { key: "B", ctrl: true, shift: true }, + OPEN_PLAN_TAB: { key: "p", code: "KeyP", ctrl: true, alt: true, shift: true }, // Artifacts tab shortcuts: only handled while focus is inside the Artifacts panel, // like the Review panel's single-key hunk navigation. diff --git a/src/node/services/agentSkills/builtInSkillContent.generated.ts b/src/node/services/agentSkills/builtInSkillContent.generated.ts index 637dc2d4f7d..b98521e9258 100644 --- a/src/node/services/agentSkills/builtInSkillContent.generated.ts +++ b/src/node/services/agentSkills/builtInSkillContent.generated.ts @@ -4148,7 +4148,7 @@ export const BUILTIN_SKILL_FILES: Record> = { "The right sidebar's **Plan** tab shows the plan file next to the chat. It reads the file again", "when a turn ends and when the window regains focus, so a plan the agent is writing, or one you", "edited in an external editor, stays current. Open it from a New tab in the sidebar, with", - "`/plan open`, with `Ctrl+Shift+B` (`Cmd+Shift+B` on Mac), or from the **Plan file** row in the", + "`/plan open`, with `Ctrl+Alt+Shift+P` (`Cmd+Option+Shift+P` on Mac), or from the **Plan file** row in the", "Stats tab's post-compaction context. The tab has the plan card's main actions: **Implement**,", "**Edit** (opens the file in your external editor) and **Copy**. `/plan` shows the plan in the", "chat instead.", @@ -5097,11 +5097,11 @@ export const BUILTIN_SKILL_FILES: Record> = { "", "The shortcuts other than opening the tab apply while focus is inside the Plan tab.", "", - "| Action | Shortcut |", - "| --------------------------------- | -------------- |", - "| Open the Plan tab | `Ctrl+Shift+B` |", - "| Open the plan file in your editor | `E` |", - "| Copy the plan | `Y` |", + "| Action | Shortcut |", + "| --------------------------------- | ------------------ |", + "| Open the Plan tab | `Ctrl+Alt+Shift+P` |", + "| Open the plan file in your editor | `E` |", + "| Copy the plan | `Y` |", "", "### Artifacts tab (experimental)", "", From f0fcdf24e99b99c1597e0b1f71b8f9afbc436d84 Mon Sep 17 00:00:00 2001 From: asm <113964+asm@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:49:16 -0700 Subject: [PATCH 05/11] =?UTF-8?q?=F0=9F=A4=96=20fix:=20Plan=20tab=20focus?= =?UTF-8?q?=20from=20the=20Stats=20row,=20one=20editor=20launch=20per=20pr?= =?UTF-8?q?ess,=20no=20client=20gate=20for=20/plan=20open?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The Stats tab's "Plan file" row asks the Plan tab to take focus (its button goes away with the tab switch); "/plan open" leaves focus in the chat input. OPEN_PLAN_TAB carries `focus`, and the sidebar arms its per-pane focus request on the event path too. - "/plan open" no longer needs a live client: the tab shows the reconnecting state itself. (Side chats never reach it: the side-chat gate refuses workspace-only commands before any handler.) - The Plan tab's E shortcut ignores key auto-repeat, and one editor launch runs at a time (the Edit button included). - PlanTab.test.tsx installs the shared test DOM like the sibling suites: the hand-rolled window swap left React's event delegation without the element classes it needs, so the shortcut tests only passed after another suite had installed them. Co-Authored-By: Claude Fable 5.1 --- .../features/RightSidebar/PlanTab.test.tsx | 53 +++++++++++++++---- src/browser/features/RightSidebar/PlanTab.tsx | 11 +++- .../RightSidebar/PostCompactionSection.tsx | 2 +- .../features/RightSidebar/RightSidebar.tsx | 8 ++- src/browser/utils/chatCommands.test.ts | 15 +++++- src/browser/utils/chatCommands.ts | 13 ++--- src/browser/utils/openPlanTab.ts | 14 +++-- src/common/constants/events.ts | 4 +- 8 files changed, 93 insertions(+), 27 deletions(-) diff --git a/src/browser/features/RightSidebar/PlanTab.test.tsx b/src/browser/features/RightSidebar/PlanTab.test.tsx index 6f9950a897c..cc89b7914e4 100644 --- a/src/browser/features/RightSidebar/PlanTab.test.tsx +++ b/src/browser/features/RightSidebar/PlanTab.test.tsx @@ -1,12 +1,14 @@ +import "../../../../tests/ui/dom"; import * as RealMarkdownCore from "../Messages/MarkdownCore"; import * as RealMarkdownRenderer from "../Messages/MarkdownRenderer"; import * as RealClipboard from "@/browser/utils/clipboard"; +import * as RealOpenInEditor from "@/browser/utils/openInEditor"; import { APIContext, APIProvider } from "@/browser/contexts/API"; import type { ReactElement, ReactNode } from "react"; import { PlanTab } from "./PlanTab"; import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; -import { GlobalWindow } from "happy-dom"; import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import { installDom } from "../../../../tests/ui/dom"; import type { APIClient } from "@/browser/contexts/API"; import { createTestApiClient, type TestApiOverrides } from "@/browser/testUtils"; import { CUSTOM_EVENTS, type CustomEventType } from "@/common/constants/events"; @@ -24,10 +26,13 @@ const realModules: Array<[string, Record]> = [ ["@/browser/features/Messages/MarkdownCore", { ...RealMarkdownCore }], ["@/browser/features/Messages/MarkdownRenderer", { ...RealMarkdownRenderer }], ["@/browser/utils/clipboard", { ...RealClipboard }], + ["@/browser/utils/openInEditor", { ...RealOpenInEditor }], ]; /** What the mocked clipboard received. */ let clipboardWrites: string[] = []; +/** The mocked openInEditor's pending launches, each settled through its resolver. */ +let editorLaunches: Array<(result: { success: boolean }) => void> = []; async function installModuleMocks() { await mock.module("@/browser/features/Messages/MarkdownCore", () => ({ @@ -49,6 +54,14 @@ async function installModuleMocks() { return Promise.resolve(); }, })); + + await mock.module("@/browser/utils/openInEditor", () => ({ + ...RealOpenInEditor, + openInEditor: () => + new Promise<{ success: boolean }>((resolve) => { + editorLaunches.push(resolve); + }), + })); } // Inject the client through the real provider (a module mock of contexts/API is process-wide). @@ -85,25 +98,24 @@ function planResult(content: string, path = "/tmp/plan.md"): GetPlanContentResul } describe("PlanTab", () => { - let originalWindow: typeof globalThis.window; - let originalDocument: typeof globalThis.document; + let cleanupDom: (() => void) | null = null; beforeEach(async () => { await installModuleMocks(); - originalWindow = globalThis.window; - originalDocument = globalThis.document; - globalThis.window = new GlobalWindow() as unknown as Window & typeof globalThis; - globalThis.document = globalThis.window.document; + // The shared DOM installer, as in the sibling suites: React's event delegation needs the + // window's element classes as globals, not only `window` and `document`. + cleanupDom = installDom(); mockApi = null; clipboardWrites = []; + editorLaunches = []; }); afterEach(async () => { cleanup(); await restoreModuleMocks(); mock.restore(); - globalThis.window = originalWindow; - globalThis.document = originalDocument; + cleanupDom?.(); + cleanupDom = null; }); test("shows the plan and its path once read", async () => { @@ -262,6 +274,29 @@ describe("PlanTab", () => { expect(clipboardWrites).toEqual(["# Plan"]); }); + test("the Edit shortcut launches one editor per press, none while a launch is pending", async () => { + mockApi = { workspace: { getPlanContent: mock(() => Promise.resolve(planResult("# Plan"))) } }; + const view = renderWithApi(); + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Plan"); + }); + + const panel = view.getByTestId("plan-tab"); + fireEvent.keyDown(panel, { key: "e" }); + expect(editorLaunches).toHaveLength(1); + // A held key auto-repeats, and a second press lands while the launch is pending. + fireEvent.keyDown(panel, { key: "e", repeat: true }); + fireEvent.keyDown(panel, { key: "e" }); + expect(editorLaunches).toHaveLength(1); + + await act(async () => { + editorLaunches[0]?.({ success: true }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + fireEvent.keyDown(panel, { key: "e" }); + expect(editorLaunches).toHaveLength(2); + }); + test("takes focus when opened by its shortcut, once", async () => { mockApi = { workspace: { getPlanContent: mock(() => Promise.resolve(planResult("# Plan"))) } }; const consumed = mock(() => undefined); diff --git a/src/browser/features/RightSidebar/PlanTab.tsx b/src/browser/features/RightSidebar/PlanTab.tsx index c07aa282e31..32466f353ea 100644 --- a/src/browser/features/RightSidebar/PlanTab.tsx +++ b/src/browser/features/RightSidebar/PlanTab.tsx @@ -98,8 +98,12 @@ function PlanTabBody(props: PlanTabProps) { } }; + // One editor launch at a time: a second press (or click) while one is in flight would open + // another editor window, or another placeholder window in a browser. + const editorLaunchRef = useRef(false); const handleOpenInEditor = async () => { - if (path === null) return; + if (path === null || editorLaunchRef.current) return; + editorLaunchRef.current = true; try { const result = await openInEditor({ api, @@ -115,6 +119,8 @@ function PlanTabBody(props: PlanTabProps) { // Editor discovery for a remote or devcontainer workspace rejects when the connection // drops mid-call; the user still needs to hear why nothing opened. showFeedbackToast({ type: "error", message: getErrorMessage(error) }); + } finally { + editorLaunchRef.current = false; } }; @@ -133,7 +139,8 @@ function PlanTabBody(props: PlanTabProps) { // Single-key shortcuts while focus is inside the tab, never from a text field. const handleKeyDown = (event: React.KeyboardEvent) => { - if (isEditableElement(event.target)) return; + // A held key auto-repeats; that is not another request. + if (event.repeat || isEditableElement(event.target)) return; if (matchesKeybind(event, KEYBINDS.PLAN_TAB_EDIT)) { if (path === null) return; event.preventDefault(); diff --git a/src/browser/features/RightSidebar/PostCompactionSection.tsx b/src/browser/features/RightSidebar/PostCompactionSection.tsx index eaef7e3c325..7f2d40dd55a 100644 --- a/src/browser/features/RightSidebar/PostCompactionSection.tsx +++ b/src/browser/features/RightSidebar/PostCompactionSection.tsx @@ -130,7 +130,7 @@ export const PostCompactionSection: React.FC = (prop