diff --git a/docs/agents/plan-mode.mdx b/docs/agents/plan-mode.mdx index 0402c626ed0..dd115467748 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+Alt+Shift+L` (`Cmd+Option+Shift+L` 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..8f19f140e6f 100644 --- a/docs/config/keybinds.mdx +++ b/docs/config/keybinds.mdx @@ -85,7 +85,7 @@ While a workspace's actions menu (`⋮` in the sidebar row, `…` in the header) | New right sidebar tab (lists the tools) | `Ctrl+Alt+N` | | 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 @@ -97,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+Alt+Shift+L` | +| 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/WorkspaceMenuBar/WorkspaceMenuBar.test.tsx b/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.test.tsx index c146aaedd7b..c90bd3eec9e 100644 --- a/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.test.tsx +++ b/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.test.tsx @@ -933,6 +933,44 @@ describe("WorkspaceMenuBar archive confirmations", () => { expect(shown).toEqual(["artifacts"]); }); + it("the Plan shortcut shows the Plan tab and asks its panel for focus, but not from the palette", () => { + narrow(); + const requests: unknown[] = []; + const record = (event: Event) => requests.push((event as CustomEvent).detail); + window.addEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, record); + const palette = document.createElement("div"); + palette.setAttribute("cmdk-root", ""); + const paletteInput = document.createElement("input"); + palette.append(paletteInput); + document.body.append(palette); + const { shown } = renderRecording(); + // Happy DOM reports AltGraph whenever Alt is down, which the shortcut ignores as AltGr text. + const press = (target: Element | Window) => { + const event = new window.KeyboardEvent("keydown", { + key: "L", + code: "KeyL", + ctrlKey: true, + altKey: true, + shiftKey: true, + bubbles: true, + cancelable: true, + }); + Object.defineProperty(event, "getModifierState", { value: () => false }); + act(() => { + fireEvent(target, event); + }); + }; + + press(paletteInput); + press(window); + window.removeEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, record); + palette.remove(); + + expect(shown).toEqual(["plan"]); + // RightSidebar focuses the panel on this request, as after the wide-layout shortcut. + expect(requests).toEqual([{ workspaceId, focus: true }]); + }); + it("leave keys alone while the sidebar is visible or a modal is open", () => { stubMatchMedia(() => false); const { shown, view } = renderRecording(); diff --git a/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx b/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx index 4bd949cad7b..00f350b0c70 100644 --- a/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx +++ b/src/browser/components/WorkspaceMenuBar/WorkspaceMenuBar.tsx @@ -20,13 +20,16 @@ import { Checkbox } from "../Checkbox/Checkbox"; import { formatKeybind, isBrowserViewportFocused, + isCommandPaletteTarget, isDesktopViewportFocused, isDialogOpen, isEditableElement, isTerminalFocused, KEYBINDS, matchesKeybind, + matchesOpenPlanTabKeybind, } from "@/browser/utils/ui/keybinds"; +import { openPlanTab } from "@/browser/utils/openPlanTab"; import { useRuntimeStatus, useRuntimeStatusStoreRaw } from "@/browser/stores/RuntimeStatusStore"; import { useWorkspaceSidebarState } from "@/browser/stores/WorkspaceStore"; import { hasWorkspaceRepository } from "@/browser/utils/workspaceCapabilities"; @@ -444,6 +447,41 @@ 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 ( + !matchesOpenPlanTabKeybind(e) || + isDialogOpen() || + !isTimelineSidebarHidden() || + // The command palette renders no modal dialog but keeps its keystrokes. + isCommandPaletteTarget(e.target) || + isTerminalFocused(e.target) || + isDesktopViewportFocused(e.target) + ) { + return; + } + e.preventDefault(); + // Through the event, so RightSidebar asks the panel for focus as after the wide-layout + // shortcut: the full-screen view alone would focus the tab label, outside the panel's + // single-key shortcuts. The listener below shows the view. + openPlanTab(workspaceId, { focus: true }); + }; + 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..53946ac7432 100644 --- a/src/browser/components/WorkspaceShell/deferredSidebarInput.ts +++ b/src/browser/components/WorkspaceShell/deferredSidebarInput.ts @@ -5,6 +5,7 @@ import { KEYBINDS, matchesKeybind, matchesNewSidebarTabKeybind, + matchesOpenPlanTabKeybind, } from "@/browser/utils/ui/keybinds"; import { isWorkspaceRightSidebarHidden } from "@/browser/features/RightSidebar/rightSidebarVisibility"; @@ -16,6 +17,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, @@ -40,6 +42,7 @@ export function holdSidebarInput(held: HeldSidebarInput[]): () => void { const sidebarKey = SIDEBAR_KEYBINDS.some((keybind) => matchesKeybind(e, keybind)) || matchesNewSidebarTabKeybind(e) || // its own matcher: AltGr does not count + matchesOpenPlanTabKeybind(e) || // likewise // Shift+I types a letter in a text field, where the sidebar ignores it. (matchesKeybind(e, KEYBINDS.TOGGLE_REVIEW_IMMERSIVE) && !isEditableElement(e.target)); if (!sidebarKey) return; @@ -78,11 +81,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]")) @@ -103,7 +108,8 @@ export function guardSidebarKeys(): () => void { const guard = (e: KeyboardEvent) => { const sidebarKey = SIDEBAR_KEYBINDS.some((keybind) => matchesKeybind(e, keybind)) || - matchesNewSidebarTabKeybind(e); + matchesNewSidebarTabKeybind(e) || + matchesOpenPlanTabKeybind(e); if (sidebarKey) e.preventDefault(); }; window.addEventListener("keydown", guard); 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..d04bf51ec39 --- /dev/null +++ b/src/browser/features/RightSidebar/PlanTab.stories.tsx @@ -0,0 +1,98 @@ +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 }> = (props) => { + const clientRef = useRef(null); + clientRef.current ??= props.setup(); + + return ( + + + {props.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..7e873ab0b35 --- /dev/null +++ b/src/browser/features/RightSidebar/PlanTab.test.tsx @@ -0,0 +1,440 @@ +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, spyOn, test } from "bun:test"; +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"; +import { readPersistedState, updatePersistedState } from "@/browser/hooks/usePersistedState"; +import { getPlanTabScrollTopKey } from "@/common/constants/storage"; + +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 }], + ["@/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", () => ({ + MarkdownCore: (props: { content: string }) => ( +
{props.content}
+ ), + })); + + await mock.module("@/browser/features/Messages/MarkdownRenderer", () => ({ + PlanMarkdownContainer: (props: { children: ReactNode }) => ( +
{props.children}
+ ), + })); + + await mock.module("@/browser/utils/clipboard", () => ({ + ...RealClipboard, + copyToClipboard: (text: string) => { + clipboardWrites.push(text); + 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). +// 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 cleanupDom: (() => void) | null = null; + + beforeEach(async () => { + await installModuleMocks(); + // 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(); + cleanupDom?.(); + cleanupDom = null; + }); + + 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("restores the scroll offset once a body mounted in a hidden sidebar becomes visible", async () => { + updatePersistedState(getPlanTabScrollTopKey("workspace-1"), 120, 0); + mockApi = { workspace: { getPlanContent: mock(() => Promise.resolve(planResult("# Plan"))) } }; + // The narrow layout hides the sidebar with display: none: no layout box until it shows. + let visible = false; + const clientRects = spyOn(HTMLElement.prototype, "getClientRects").mockImplementation(function ( + this: HTMLElement + ) { + const hidden = !visible && this.dataset.testid === "plan-tab-body"; + // Only the list length matters: an empty list means no layout box. + return (hidden ? [] : [{ width: 100, height: 100 }]) as unknown as DOMRectList; + }); + const observed: Array<() => void> = []; + const RealResizeObserver = globalThis.ResizeObserver; + globalThis.ResizeObserver = class { + constructor(private readonly callback: ResizeObserverCallback) {} + observe = () => { + observed.push(() => this.callback([], this as unknown as ResizeObserver)); + }; + unobserve = () => undefined; + disconnect = () => undefined; + } as unknown as typeof ResizeObserver; + try { + const view = renderWithApi(); + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Plan"); + }); + const body = view.getByTestId("plan-tab-body"); + expect(body.scrollTop).toBe(0); + + // Shown full-screen: the same body, now with a layout box. + visible = true; + act(() => observed.forEach((notify) => notify())); + expect(body.scrollTop).toBe(120); + } finally { + clientRects.mockRestore(); + globalThis.ResizeObserver = RealResizeObserver; + } + }); + + 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("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("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); + const view = renderWithApi( + + ); + await waitFor(() => { + expect(document.activeElement).toBe(view.getByTestId("plan-tab")); + }); + expect(consumed).toHaveBeenCalledTimes(1); + }); + + test("leaves focus in the command palette when asked to take it", async () => { + mockApi = { workspace: { getPlanContent: mock(() => Promise.resolve(planResult("# Plan"))) } }; + const palette = document.createElement("div"); + palette.setAttribute("cmdk-root", ""); + const paletteInput = document.createElement("input"); + palette.append(paletteInput); + document.body.append(palette); + paletteInput.focus(); + try { + const consumed = mock(() => undefined); + const view = renderWithApi( + + ); + await waitFor(() => { + expect(view.getByTestId("plan-markdown-core").textContent).toContain("# Plan"); + }); + // The request is consumed, so the panel does not take focus later either. + expect(consumed).toHaveBeenCalledTimes(1); + expect(document.activeElement).toBe(paletteInput); + } finally { + palette.remove(); + } + }); + + 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 a failure or none to 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; message: string }> = []; + const onToast = (event: Event) => { + toasts.push((event as CustomEventType).detail); + }; + const requests: string[] = []; + let nextOutcome: string | null = null; + const planCard = (event: Event) => { + const { detail } = event as CustomEventType; + requests.push(detail.workspaceId); + detail.handled = true; + detail.outcome = Promise.resolve(nextOutcome); + }; + 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. + await act(async () => { + fireEvent.click(view.getByRole("button", { name: "Implement" })); + await Promise.resolve(); + }); + expect(requests).toEqual(["workspace-1"]); + expect(toasts).toEqual([]); + + // The action fails after it started: the card's alert can be covered (the narrow + // layout's full-screen sidebar), so the tab reports the failure too. + nextOutcome = "Model openai:gpt-5.2 is not allowed"; + fireEvent.click(view.getByRole("button", { name: "Implement" })); + await waitFor(() => { + expect(toasts).toEqual([{ type: "error", message: "Model openai:gpt-5.2 is not allowed" }]); + }); + + // No card can run it (none rendered, or its action disabled): the tab says so. + toasts.length = 0; + 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..225a4083fcb --- /dev/null +++ b/src/browser/features/RightSidebar/PlanTab.tsx @@ -0,0 +1,270 @@ +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 { + isCommandPaletteTarget, + 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; +} + +/** + * 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: PlanTabProps) { + 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. 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. A body mounted in a hidden sidebar (the narrow + // layout's `display: none`, shown full-screen later without a remount) has no layout box, and + // setting scrollTop there does nothing: the restore then waits until the body gets one. + const bodyRef = useRef(null); + const [savedScrollTop] = useState(() => + normalizeScrollTop(readPersistedState(getPlanTabScrollTopKey(workspaceId), 0)) + ); + const scrollTopRef = useRef(savedScrollTop); + useEffect(() => { + const body = bodyRef.current; + if (!hasPlan || body == null) return; + const restore = () => { + body.scrollTop = scrollTopRef.current; + }; + if (body.getClientRects().length > 0 || typeof ResizeObserver === "undefined") { + restore(); + return; + } + const observer = new ResizeObserver(() => { + if (body.getClientRects().length === 0) return; + observer.disconnect(); + restore(); + }); + observer.observe(body); + return () => observer.disconnect(); + }, [hasPlan]); + useEffect(() => { + return () => { + updatePersistedState(getPlanTabScrollTopKey(workspaceId), scrollTopRef.current, 0); + }; + }, [workspaceId]); + + const handleImplement = async () => { + const outcome = runLatestPlanAction(workspaceId); + if (outcome === null) { + showFeedbackToast({ type: "error", message: NO_RUNNABLE_PLAN_MESSAGE }); + return; + } + // The plan card shows a failure under itself, but the narrow layout's full-screen sidebar + // covers the transcript: without this the button would seem to do nothing. + const error = await outcome; + if (error !== null) showFeedbackToast({ type: "error", message: error }); + }; + + // 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 || editorLaunchRef.current) return; + editorLaunchRef.current = true; + 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) }); + } finally { + editorLaunchRef.current = false; + } + }; + + const handleCopy = () => { + if (hasPlan) void copyToClipboard(content ?? ""); + }; + + // Opened by its shortcut: take focus so the single-key shortcuts below work at once. Never + // from the command palette, which renders no modal dialog but keeps its keystrokes: checked + // here, where focus moves, so every way of requesting it (the open shortcut, a Ctrl/Cmd+1-9 + // tab switch, the Stats row) is covered. + const panelRef = useRef(null); + const { autoFocus, onAutoFocusConsumed } = props; + useEffect(() => { + if (autoFocus !== true) return; + if (!isCommandPaletteTarget(document.activeElement)) 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) => { + // 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(); + void handleOpenInEditor(); + } else if (matchesKeybind(event, KEYBINDS.PLAN_TAB_COPY)) { + if (!hasPlan) return; + event.preventDefault(); + handleCopy(); + } + }; + + 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..7f2d40dd55a 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..f42d9431840 100644 --- a/src/browser/features/RightSidebar/RightSidebar.tsx +++ b/src/browser/features/RightSidebar/RightSidebar.tsx @@ -69,6 +69,7 @@ import { isDesktopViewportFocused, isTerminalFocused, matchesNewSidebarTabKeybind, + matchesOpenPlanTabKeybind, } from "@/browser/utils/ui/keybinds"; import { Button } from "@/browser/components/Button/Button"; import { NARROW_VIEWPORT_MAX_WIDTH_PX } from "@/constants/layout"; @@ -705,6 +706,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 +957,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 +1511,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); @@ -1848,6 +1857,23 @@ 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); + const next = selectOrAddTab(getBaseLayout(), "plan"); + setLayout(() => next); + // The Plan file row goes away with the Stats tab it sits in, so the panel claims focus + // (as after the shortcut); focus stays in the chat input after "/plan open". + if (detail.focus) setPlanFocusTabsetId(next.focusedTabsetId); + }; + window.addEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, handleOpenPlanTab); + return () => window.removeEventListener(CUSTOM_EVENTS.OPEN_PLAN_TAB, handleOpenPlanTab); + }, [getBaseLayout, setCollapsed, setLayout, workspaceId]); + const [tabToFocus, setTabToFocus] = React.useState(null); const sidebarContainerRef = React.useRef(null); @@ -1939,6 +1965,36 @@ 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 ( + !matchesOpenPlanTabKeybind(e) || + (container != null && isRightSidebarResponsivelyHidden(container)) || + isDialogOpen() || + // The command palette renders no modal dialog but keeps its keystrokes: focusing the + // panel behind it would take its typing. + isCommandPaletteTarget(e.target) || + // Remote desktops, browsers and terminals own their keystrokes. + isTerminalFocused(e.target) || + isDesktopViewportFocused(e.target) || + isBrowserViewportFocused(e.target) + ) { + return; + } + e.preventDefault(); + setCollapsed(false); + const next = selectOrAddTab(getBaseLayout(), "plan"); + setLayout(() => next); + setPlanFocusTabsetId(next.focusedTabsetId); + }; + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }, [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 // background-added tab with a small badge is easy to miss. Only a mounted @@ -2052,6 +2108,9 @@ const RightSidebarComponent: React.FC = ({ setReviewFocusRequest((prev) => nextReviewFocusRequest(prev, target.tabsetId)); } else if (target?.tab === "artifacts") { setArtifactsFocusTabsetId(target.tabsetId); + } else if (target?.tab === "plan") { + // Its single-key shortcuts, too, need focus inside the panel. + setPlanFocusTabsetId(target.tabsetId); } // A per-iteration copy: React Compiler can't lower `i++` on a variable a closure captures. @@ -2487,6 +2546,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); }; @@ -2562,6 +2622,7 @@ const RightSidebarComponent: React.FC = ({ costs: true, review: canReviewDiffs, instructions: true, + plan: true, goal: true, workflows: true, timeline: true, @@ -2888,6 +2949,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/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..f55102708b5 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) ); @@ -127,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; @@ -186,6 +195,18 @@ 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..34570ae8d5d --- /dev/null +++ b/src/browser/features/RightSidebar/usePlanFile.ts @@ -0,0 +1,93 @@ +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. A read that fails clears it. 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") { + // The plan is gone or unreadable now (deleted after it was shown, a runtime that went + // away): nothing stale stays behind the error, so the actions disable, and the next read + // starts from the loading state. + setError(read.error); + setContent(null); + setPath(null); + hasPlanRef.current = false; + 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..716312df7fd 100644 --- a/src/browser/features/Settings/Sections/KeybindsSection.tsx +++ b/src/browser/features/Settings/Sections/KeybindsSection.tsx @@ -76,6 +76,9 @@ 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", + 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)", @@ -283,6 +286,10 @@ export const KEYBIND_GROUPS: Array<{ "OPEN_STATS_DIALOG", ], }, + { + label: "Plan tab", + keys: ["OPEN_PLAN_TAB", "PLAN_TAB_EDIT", "PLAN_TAB_COPY"], + }, { label: "Artifacts", keys: [ diff --git a/src/browser/features/Tools/ProposePlanToolCall.test.tsx b/src/browser/features/Tools/ProposePlanToolCall.test.tsx index 56838a46206..5143e2ee22e 100644 --- a/src/browser/features/Tools/ProposePlanToolCall.test.tsx +++ b/src/browser/features/Tools/ProposePlanToolCall.test.tsx @@ -1001,6 +1001,31 @@ describe("ProposePlanToolCall", () => { window.dispatchEvent(request); expect(request.detail.handled).toBe(true); await waitFor(() => expect(sendMessageCalls).toHaveLength(1)); + expect(await request.detail.outcome).toBeNull(); + }); + + test("a palette request's outcome settles with the action's failure", async () => { + startInPlanMode(); + mockApi = createMockApi({ + sendMessage: () => + Promise.resolve({ + success: false, + error: { type: "invalid_model_string", message: "Model openai:gpt-5.2 is not allowed" }, + }), + }); + const view = renderCompletedPlan(); + + const request = createCustomEvent(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, { + workspaceId: WORKSPACE_ID, + handled: false, + }); + window.dispatchEvent(request); + expect(request.detail.handled).toBe(true); + expect(await request.detail.outcome).toContain("Model openai:gpt-5.2 is not allowed"); + // The card still shows it under itself. + await waitFor(() => + expect(view.getByRole("alert").textContent).toContain("Model openai:gpt-5.2 is not allowed") + ); }); }); diff --git a/src/browser/features/Tools/ProposePlanToolCall.tsx b/src/browser/features/Tools/ProposePlanToolCall.tsx index 4eb1e66d6ba..06387ced51f 100644 --- a/src/browser/features/Tools/ProposePlanToolCall.tsx +++ b/src/browser/features/Tools/ProposePlanToolCall.tsx @@ -576,11 +576,13 @@ export const ProposePlanToolCall: React.FC = (props) = : formatted.message; }; - const handleImplement = async () => { - if (!workspaceId || !api) return; - if (isImplementingRef.current) return; + // Both plan actions settle with their failure message (null when nothing failed), which a + // Plan tab request reports too (RUN_LATEST_PLAN_ACTION's `outcome`). + const handleImplement = async (): Promise => { + if (!workspaceId || !api) return null; + if (isImplementingRef.current) return null; // The button is disabled while hydrating; this covers a click racing the barrier closing. - if (!isTranscriptMutationAllowed(workspaceId)) return; + if (!isTranscriptMutationAllowed(workspaceId)) return null; isImplementingRef.current = true; if (isMountedRef.current) { @@ -596,9 +598,12 @@ export const ProposePlanToolCall: React.FC = (props) = replacementErrorContext: "Failed to replace chat history before implementing:", }); if (isMountedRef.current) setPlanActionError(error); + return error; } catch (error) { // The user retries after reading why it failed. - if (isMountedRef.current) setPlanActionError(getErrorMessage(error)); + const message = getErrorMessage(error); + if (isMountedRef.current) setPlanActionError(message); + return message; } finally { isImplementingRef.current = false; if (isMountedRef.current) { @@ -606,10 +611,10 @@ export const ProposePlanToolCall: React.FC = (props) = } } }; - const handleContinueInAuto = async () => { - if (!workspaceId || !api) return; - if (isContinuingInAutoRef.current) return; - if (!isTranscriptMutationAllowed(workspaceId)) return; + const handleContinueInAuto = async (): Promise => { + if (!workspaceId || !api) return null; + if (isContinuingInAutoRef.current) return null; + if (!isTranscriptMutationAllowed(workspaceId)) return null; isContinuingInAutoRef.current = true; if (isMountedRef.current) { @@ -625,8 +630,11 @@ export const ProposePlanToolCall: React.FC = (props) = replacementErrorContext: "Failed to replace chat history before continuing in auto:", }); if (isMountedRef.current) setPlanActionError(error); + return error; } catch (error) { - if (isMountedRef.current) setPlanActionError(getErrorMessage(error)); + const message = getErrorMessage(error); + if (isMountedRef.current) setPlanActionError(message); + return message; } finally { isContinuingInAutoRef.current = false; if (isMountedRef.current) { @@ -753,11 +761,10 @@ export const ProposePlanToolCall: React.FC = (props) = const selectedWorkspaceId = workspaceContext?.selectedWorkspace?.workspaceId; useEffect(() => { if (!primaryPlanAction || !workspaceId) return; - const runIfEnabled = (): boolean => { - const { disabled, onClick } = primaryPlanAction; - if (disabled || !onClick) return false; - onClick(); - return true; + // The button's own enablement, then its handler (Continue in Auto when it is the Auto button). + const runIfEnabled = (): Promise | null => { + if (primaryPlanAction.disabled) return null; + return implementButton ? handleImplement() : handleContinueInAuto(); }; const handleKeyDown = (event: KeyboardEvent) => { if (!matchesKeybind(event, KEYBINDS.RUN_LATEST_PLAN_ACTION)) return; @@ -778,12 +785,15 @@ export const ProposePlanToolCall: React.FC = (props) = if (isTypingInNonEmptyField(document.activeElement)) return; event.preventDefault(); if (event.repeat) return; - runIfEnabled(); + void runIfEnabled(); }; const handlePaletteRequest = (event: Event) => { const { detail } = event as CustomEventType; if (detail.workspaceId !== workspaceId) return; - if (runIfEnabled()) detail.handled = true; + const outcome = runIfEnabled(); + if (outcome === null) return; + detail.handled = true; + detail.outcome = outcome; }; window.addEventListener("keydown", handleKeyDown); window.addEventListener(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, handlePaletteRequest); diff --git a/src/browser/utils/chatCommands.test.ts b/src/browser/utils/chatCommands.test.ts index 8efd42724b9..fc3862c16b9 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,41 @@ 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"], - }) - ) + 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" } }) ); - expectDisposition(settled.result, "consume"); - expectToast(settled.result.actions, { - type: "error", - message: "No plan found for this workspace", + 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", }); - expect(getInfo).not.toHaveBeenCalled(); + // 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", focus: false }, + }) + ); + expect(getPlanContent).not.toHaveBeenCalled(); }); - test("plan open surfaces an editor-open failure as an error toast", 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" }, + test("plan open needs no client: the tab shows the reconnecting state itself", async () => { + ensureWindowDispatchEvent(); + const result = await processSlashCommand({ type: "plan-open" }, createEnv({ api: null })); + 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); - } - } + expect(window.dispatchEvent).toHaveBeenCalledWith( + expect.objectContaining({ type: CUSTOM_EVENTS.OPEN_PLAN_TAB }) + ); }); }); diff --git a/src/browser/utils/chatCommands.ts b/src/browser/utils/chatCommands.ts index f04b8815d28..1c4318878b6 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, @@ -1053,8 +1053,9 @@ export async function processSlashCommand( return handlePlanShowCommand({ ...env, api: client, workspaceId: env.workspaceId }); case "plan-open": if (!env.workspaceId) throw new Error("Workspace ID required"); - if (!client) return notConnected(); - return handlePlanOpenCommand({ ...env, api: client, workspaceId: env.workspaceId }); + // No client needed: the tab shows the reconnecting state itself. (A side chat never + // gets here: the side-chat gate above refuses workspace-only commands.) + return handlePlanOpenCommand(env.workspaceId); case "goal-show": case "goal-set": case "goal-budget": @@ -2054,54 +2055,12 @@ 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", - }), - ]); - } - }); +function handlePlanOpenCommand(workspaceId: string): CommandResult { + // The Plan tab shows the plan, or that there is none yet (or that the backend is away); + // opening it in an editor is one of the tab's actions. + openPlanTab(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..c67c67fe6f9 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) === null) { 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..97db736cdf8 --- /dev/null +++ b/src/browser/utils/latestPlanAction.ts @@ -0,0 +1,20 @@ +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). Returns null when no card + * could run it, and the caller says so (NO_RUNNABLE_PLAN_MESSAGE); otherwise the action's + * outcome: its failure message, or null once it started. + */ +export function runLatestPlanAction(workspaceId: string): Promise | null { + const request = createCustomEvent(CUSTOM_EVENTS.RUN_LATEST_PLAN_ACTION, { + workspaceId, + handled: false, + }); + window.dispatchEvent(request); + if (!request.detail.handled) return null; + return request.detail.outcome ?? Promise.resolve(null); +} diff --git a/src/browser/utils/openPlanTab.ts b/src/browser/utils/openPlanTab.ts new file mode 100644 index 00000000000..dbb703e9e11 --- /dev/null +++ b/src/browser/utils/openPlanTab.ts @@ -0,0 +1,14 @@ +import { CUSTOM_EVENTS, createCustomEvent } from "@/common/constants/events"; + +/** + * Open 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 as well. With `focus`, the panel takes focus once it renders, so + * its single-key shortcuts work for a keyboard user whose control went away with the tab + * switch (the Stats tab's Plan file row); "/plan open" leaves focus in the chat input. + */ +export function openPlanTab(workspaceId: string, options?: { focus?: boolean }): void { + window.dispatchEvent( + createCustomEvent(CUSTOM_EVENTS.OPEN_PLAN_TAB, { workspaceId, focus: options?.focus === true }) + ); +} 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..9b9718b9f57 100644 --- a/src/browser/utils/ui/keybinds.test.ts +++ b/src/browser/utils/ui/keybinds.test.ts @@ -5,6 +5,7 @@ import { isMac, matchesKeybind, matchesNewSidebarTabKeybind, + matchesOpenPlanTabKeybind, isKeybindDeprecated, KEYBINDS, getSideChatPaneWorkspaceId, @@ -53,6 +54,21 @@ describe("NEW_SIDEBAR_TAB keybind", () => { }); }); +describe("OPEN_PLAN_TAB keybind", () => { + test("matches Ctrl+Alt+Shift+L but not the same chord produced by AltGr", () => { + globalThis.window = { api: { platform: "linux" } } as unknown as Window & typeof globalThis; + const chord = { key: "L", code: "KeyL", ctrlKey: true, altKey: true, shiftKey: true }; + + expect(matchesOpenPlanTabKeybind(createEvent(chord))).toBe(true); + // AltGr+Shift reports Ctrl+Alt+Shift on Windows/Linux layouts, where it types a character. + expect( + matchesOpenPlanTabKeybind( + createEvent({ ...chord, getModifierState: (key: string) => key === "AltGraph" }) + ) + ).toBe(false); + }); +}); + describe("Cmd/Ctrl+Option/Alt+Shift chords: workspace actions menu (#6328), sandbox approvals", () => { const keys = [ ["FORK_WORKSPACE", "KeyB", "\u222b"], @@ -455,6 +471,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..bdea7c2447b 100644 --- a/src/browser/utils/ui/keybinds.ts +++ b/src/browser/utils/ui/keybinds.ts @@ -64,6 +64,11 @@ export function matchesNewSidebarTabKeybind(event: React.KeyboardEvent | Keyboar return !isAltGraphPressed(event) && matchesKeybind(event, KEYBINDS.NEW_SIDEBAR_TAB); } +/** OPEN_PLAN_TAB is a Ctrl/Cmd+Alt+Shift chord, so it ignores AltGr input like NEW_SIDEBAR_TAB. */ +export function matchesOpenPlanTabKeybind(event: React.KeyboardEvent | KeyboardEvent): boolean { + return !isAltGraphPressed(event) && matchesKeybind(event, KEYBINDS.OPEN_PLAN_TAB); +} + export function matchesKeybind( event: React.KeyboardEvent | KeyboardEvent, keybind: Keybind @@ -638,6 +643,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: "l", code: "KeyL", 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. /** Toggle fullscreen for the selected artifact */ @@ -860,6 +868,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/common/constants/events.ts b/src/common/constants/events.ts index 62fc2ca636a..7245dbdfdc7 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; focus: boolean } + */ + 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 } @@ -230,6 +236,12 @@ export interface CustomEventPayloads { workspaceId: string; /** Set synchronously by the plan card that started the action. */ handled: boolean; + /** + * Set with `handled`: settles with the action's failure message, or null when it started. + * The card shows a failure under itself; a caller that can cover the transcript (the narrow + * layout's full-screen Plan tab) reports it too. + */ + outcome?: Promise; }; [CUSTOM_EVENTS.FOCUS_BACKGROUND_PROCESSES]: { workspaceId: string; @@ -283,6 +295,11 @@ export interface CustomEventPayloads { workspaceId: string; openCompleteInput?: boolean; }; + [CUSTOM_EVENTS.OPEN_PLAN_TAB]: { + workspaceId: string; + /** The panel takes focus once it renders (see openPlanTab). */ + focus: boolean; + }; [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..b0581045c2b 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+Alt+Shift+L` (`Cmd+Option+Shift+L` 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.", @@ -5073,7 +5081,7 @@ export const BUILTIN_SKILL_FILES: Record> = { "| New right sidebar tab (lists the tools) | `Ctrl+Alt+N` |", "| 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", "", @@ -5085,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+Alt+Shift+L` |", + "| 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.",