From 3a5ec9464b4ba22be623abb3ceeaa28ab7c807e7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 16 Jun 2026 17:30:22 -0700 Subject: [PATCH 1/2] Render the plan surface in the inline right panel (#3118) Co-authored-by: codex --- apps/web/src/components/ChatView.browser.tsx | 187 ++++++++++++ apps/web/src/components/ChatView.tsx | 273 ++++++++---------- apps/web/src/components/PlanSidebar.tsx | 12 - apps/web/src/components/RightPanelTabs.tsx | 6 +- apps/web/src/components/chat/ChatHeader.tsx | 8 +- .../components/chat/PanelLayoutControls.tsx | 73 +++-- 6 files changed, 357 insertions(+), 202 deletions(-) diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 6f620d9a0a..90790a01b5 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -2110,6 +2110,48 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("keeps the compact chat header on one row", async () => { + const mounted = await mountChatView({ + viewport: COMPACT_FOOTER_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-compact-header" as MessageId, + targetText: "keep the compact header aligned", + }), + }); + + try { + const chatHeader = await waitForElement( + () => document.querySelector("[data-chat-header]"), + "Unable to find chat header.", + ); + const threadTitle = await waitForElement( + () => chatHeader.querySelector("h2"), + "Unable to find thread title.", + ); + const headerActions = await waitForElement( + () => document.querySelector("[data-chat-header-actions]"), + "Unable to find chat header actions.", + ); + + const headerRect = chatHeader.getBoundingClientRect(); + const titleRect = threadTitle.getBoundingClientRect(); + const actionsRect = headerActions.getBoundingClientRect(); + const headerCenter = headerRect.top + headerRect.height / 2; + + expect(headerRect.height).toBe(52); + expect(titleRect.top).toBeGreaterThanOrEqual(headerRect.top); + expect(titleRect.bottom).toBeLessThanOrEqual(headerRect.bottom); + expect(actionsRect.top).toBeGreaterThanOrEqual(headerRect.top); + expect(actionsRect.bottom).toBeLessThanOrEqual(headerRect.bottom); + expect(Math.abs(titleRect.top + titleRect.height / 2 - headerCenter)).toBeLessThanOrEqual(1); + expect(Math.abs(actionsRect.top + actionsRect.height / 2 - headerCenter)).toBeLessThanOrEqual( + 1, + ); + } finally { + await mounted.cleanup(); + } + }); + it("keeps panel toggles fixed and can maximize the right panel", async () => { const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, @@ -2276,6 +2318,151 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("renders the plan surface in the inline right panel", async () => { + useRightPanelStore.getState().open(THREAD_REF, "plan"); + + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-inline-plan-panel" as MessageId, + targetText: "show the inline plan panel", + }), + }); + + try { + await waitForElement( + () => + Array.from(document.querySelectorAll("p")).find( + (element) => element.textContent?.trim() === "No active plan yet.", + ) ?? null, + "Unable to find inline plan panel content.", + ); + + expect( + document.querySelector("[data-right-panel-tabbar]")?.textContent, + ).toContain("Plan"); + expect(document.body.textContent).toContain("Plans will appear here when generated."); + } finally { + await mounted.cleanup(); + } + }); + + it("renders the shared panel toggles in the responsive right-panel sheet", async () => { + useRightPanelStore.getState().open(THREAD_REF, "plan"); + useRightPanelStore.getState().openTerminal(THREAD_REF, DEFAULT_TERMINAL_ID); + useRightPanelStore.getState().activateSurface(THREAD_REF, "plan"); + const baseSnapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-responsive-plan-panel-controls" as MessageId, + targetText: "show responsive plan panel controls", + }); + const snapshot: OrchestrationReadModel = { + ...baseSnapshot, + threads: baseSnapshot.threads.map((thread) => + thread.id === THREAD_ID + ? { + ...thread, + activities: [ + { + id: EventId.make("activity-responsive-panel-plan"), + tone: "info", + kind: "turn.plan.updated", + summary: "Plan updated", + payload: { + explanation: "Claude Tasks", + plan: [{ step: "Keep terminal navigation available", status: "inProgress" }], + }, + turnId: null, + sequence: 1, + createdAt: isoAt(1_000), + }, + ], + } + : thread, + ), + }; + + const mounted = await mountChatView({ + viewport: COMPACT_FOOTER_VIEWPORT, + snapshot, + }); + + try { + const sheet = await waitForElement( + () => document.querySelector('[data-slot="sheet-popup"]'), + "Unable to find responsive right-panel sheet.", + ); + const controls = await waitForElement( + () => sheet.querySelector("[data-panel-layout-controls]"), + "Unable to find shared controls in the responsive right-panel sheet.", + ); + const tabbar = await waitForElement( + () => sheet.querySelector("[data-right-panel-tabbar]"), + "Unable to find responsive right-panel tabbar.", + ); + const controlButtons = Array.from(controls.querySelectorAll("button")); + const tabbarRect = tabbar.getBoundingClientRect(); + const controlsRect = controls.getBoundingClientRect(); + + expect(controlButtons.map((button) => button.getAttribute("aria-label"))).toEqual([ + "Toggle terminal drawer", + "Toggle right panel", + ]); + expect(tabbarRect.height).toBe(52); + expect(controlsRect.height).toBe(52); + expect(controlsRect.top).toBe(tabbarRect.top); + expect(window.innerWidth - controlsRect.right).toBe(12); + for (const button of controlButtons) { + const rect = button.getBoundingClientRect(); + const buttonCenter = rect.top + rect.height / 2; + const tabbarCenter = tabbarRect.top + tabbarRect.height / 2; + expect(rect.width).toBe(32); + expect(rect.height).toBe(32); + expect(Math.abs(buttonCenter - tabbarCenter)).toBeLessThanOrEqual(1); + } + expect( + controlButtons[1]!.getBoundingClientRect().left - + controlButtons[0]!.getBoundingClientRect().right, + ).toBe(4); + expect(sheet.querySelector('button[aria-label="Maximize panel"]')).toBeNull(); + expect(sheet.querySelector('button[aria-label="Close tasks sidebar"]')).toBeNull(); + + const terminalTab = Array.from( + sheet.querySelectorAll("[data-right-panel-tab-list] button"), + ).find((button) => button.textContent?.includes("Terminal")); + terminalTab?.click(); + + await vi.waitFor(() => { + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF) + .activeSurfaceId, + ).toBe(`terminal:${DEFAULT_TERMINAL_ID}`); + expect(sheet.querySelector('[data-terminal-owner="right-panel"]')).not.toBeNull(); + expect(sheet.textContent).not.toContain("Claude Tasks"); + }); + + sheet.querySelector('button[aria-label="Close Plan"]')?.click(); + + await vi.waitFor(() => { + const panelState = selectThreadRightPanelState( + useRightPanelStore.getState().byThreadKey, + THREAD_REF, + ); + expect(panelState.surfaces.some((surface) => surface.kind === "plan")).toBe(false); + expect(panelState.activeSurfaceId).toBe(`terminal:${DEFAULT_TERMINAL_ID}`); + }); + + controls.querySelector('button[aria-label="Toggle right panel"]')?.click(); + + await vi.waitFor(() => { + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF).isOpen, + ).toBe(false); + }); + } finally { + await mounted.cleanup(); + } + }); + it("loads file previews from the active thread worktree", async () => { const worktreePath = "/repo/worktrees/file-preview-thread"; const snapshot = createSnapshotForTargetUser({ diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 88186123da..5cd0583e78 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -170,7 +170,7 @@ import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; import { MessagesTimeline } from "./chat/MessagesTimeline"; import { ChatHeader } from "./chat/ChatHeader"; -import { PanelLayoutControls } from "./chat/PanelLayoutControls"; +import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls"; import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./BranchToolbar.logic"; @@ -1333,9 +1333,8 @@ function ChatViewContent(props: ChatViewProps) { const planSidebarOpen = activeRightPanelKind === "plan"; const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime(); const rightPanelOpen = rightPanelState.isOpen; - const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet; const rightPanelMaximized = - canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey; + rightPanelOpen && !shouldUsePlanSidebarSheet && maximizedRightPanelThreadKey === routeThreadKey; const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet; useEffect(() => { @@ -3036,23 +3035,25 @@ function ChatViewContent(props: ChatViewProps) { const toggleInteractionMode = useCallback(() => { handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan"); }, [handleInteractionModeChange, interactionMode]); + const dismissPlanSidebarForCurrentTurn = useCallback(() => { + planSidebarDismissedForTurnRef.current = + activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; + }, [activePlan?.turnId, sidebarProposedPlan?.turnId]); const togglePlanSidebar = useCallback(() => { if (!activeThreadRef) return; if (planSidebarOpen) { - planSidebarDismissedForTurnRef.current = - activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; + dismissPlanSidebarForCurrentTurn(); } else { planSidebarDismissedForTurnRef.current = null; } useRightPanelStore.getState().toggle(activeThreadRef, "plan"); - }, [activePlan?.turnId, activeThreadRef, planSidebarOpen, sidebarProposedPlan?.turnId]); + }, [activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]); const closePlanSidebar = useCallback(() => { if (!activeThreadRef) return; setMaximizedRightPanelThreadKey(null); useRightPanelStore.getState().close(activeThreadRef); - planSidebarDismissedForTurnRef.current = - activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; - }, [activePlan?.turnId, activeThreadRef, sidebarProposedPlan?.turnId]); + dismissPlanSidebarForCurrentTurn(); + }, [activeThreadRef, dismissPlanSidebarForCurrentTurn]); const closePreviewPanel = useCallback(() => { if (!activeThreadRef) return; setMaximizedRightPanelThreadKey(null); @@ -3061,6 +3062,11 @@ function ChatViewContent(props: ChatViewProps) { const activateRightPanelSurface = useCallback( (surface: RightPanelSurface) => { if (!activeThreadRef) return; + if (surface.kind === "plan") { + planSidebarDismissedForTurnRef.current = null; + } else if (planSidebarOpen) { + dismissPlanSidebarForCurrentTurn(); + } useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id); if (surface.kind === "preview" && surface.resourceId) { usePreviewStateStore.getState().setActiveTab(activeThreadRef, surface.resourceId); @@ -3085,17 +3091,31 @@ function ChatViewContent(props: ChatViewProps) { }); } }, - [activeThreadRef, diffOpen, environmentId, navigate, onDiffPanelOpen, threadId], + [ + activeThreadRef, + diffOpen, + dismissPlanSidebarForCurrentTurn, + environmentId, + navigate, + onDiffPanelOpen, + planSidebarOpen, + threadId, + ], ); const toggleRightPanel = useCallback(() => { if (!activeThreadRef) return; if (rightPanelOpen) { - setMaximizedRightPanelThreadKey(null); + if (planSidebarOpen) { + closePlanSidebar(); + } else { + closePreviewPanel(); + } + return; } useRightPanelStore.getState().toggleVisibility(activeThreadRef); - }, [activeThreadRef, rightPanelOpen]); + }, [activeThreadRef, closePlanSidebar, closePreviewPanel, planSidebarOpen, rightPanelOpen]); const toggleRightPanelMaximized = () => { - if (!canMaximizeRightPanel) return; + if (!rightPanelOpen || shouldUsePlanSidebarSheet) return; setMaximizedRightPanelThreadKey((threadKey) => threadKey === routeThreadKey ? null : routeThreadKey, ); @@ -3103,6 +3123,9 @@ function ChatViewContent(props: ChatViewProps) { const cleanupRightPanelSurfaces = useCallback( (surfaces: readonly RightPanelSurface[]) => { if (!activeThreadRef) return; + if (surfaces.some((surface) => surface.kind === "plan")) { + dismissPlanSidebarForCurrentTurn(); + } const api = readEnvironmentApi(activeThreadRef.environmentId); for (const surface of surfaces) { @@ -3133,7 +3156,14 @@ function ChatViewContent(props: ChatViewProps) { }); } }, - [activeThreadRef, diffOpen, environmentId, navigate, threadId], + [ + activeThreadRef, + diffOpen, + dismissPlanSidebarForCurrentTurn, + environmentId, + navigate, + threadId, + ], ); const syncActivePreviewSurface = useCallback(() => { if (!activeThreadRef) return; @@ -4654,7 +4684,7 @@ function ChatViewContent(props: ChatViewProps) { return ; } - const panelLayoutControls = ( + const panelToggleControls = ( ); + const panelLayoutControls = ( +
+ {rightPanelOpen && !shouldUsePlanSidebarSheet ? ( + + ) : null} + {panelToggleControls} +
+ ); + const rightPanelContent = activeThreadRef ? ( + activeRightPanelSurface?.kind === "preview" ? ( + + + + ) : activeRightPanelSurface?.kind === "terminal" ? ( + + ) : activeRightPanelSurface?.kind === "diff" ? ( + + + + ) : activeRightPanelSurface?.kind === "plan" ? ( + + ) : (activeRightPanelSurface?.kind === "files" || activeRightPanelSurface?.kind === "file") && + activeProject && + activeWorkspaceRoot ? ( + + + + ) : null + ) : null; return (
{isElectron && activeThreadRef ? ( ) : null} - {rightPanelOpen ? panelLayoutControls : null} + {rightPanelOpen && !shouldUsePlanSidebarSheet ? panelLayoutControls : null}
- {activeRightPanelSurface?.kind === "preview" ? ( - - - - ) : activeRightPanelSurface?.kind === "terminal" ? ( - - ) : activeRightPanelSurface?.kind === "diff" ? ( - - - - ) : (activeRightPanelSurface?.kind === "files" || - activeRightPanelSurface?.kind === "file") && - activeProject && - activeWorkspaceRoot ? ( - - - - ) : null} + {rightPanelContent} ) : null} {shouldUsePlanSidebarSheet && rightPanelOpen && activeThreadRef ? ( - + - {activeRightPanelSurface?.kind === "preview" ? ( - - - - ) : activeRightPanelSurface?.kind === "terminal" ? ( - - ) : activeRightPanelSurface?.kind === "diff" ? ( - - - - ) : activeRightPanelSurface?.kind === "plan" ? ( - - ) : (activeRightPanelSurface?.kind === "files" || - activeRightPanelSurface?.kind === "file") && - activeProject && - activeWorkspaceRoot ? ( - - - - ) : null} + {rightPanelContent} ) : null} diff --git a/apps/web/src/components/PlanSidebar.tsx b/apps/web/src/components/PlanSidebar.tsx index 498f1912c7..f7aada1df5 100644 --- a/apps/web/src/components/PlanSidebar.tsx +++ b/apps/web/src/components/PlanSidebar.tsx @@ -11,7 +11,6 @@ import { ChevronRightIcon, EllipsisIcon, LoaderIcon, - PanelRightCloseIcon, } from "lucide-react"; import { cn } from "~/lib/utils"; import type { ActivePlanState } from "../session-logic"; @@ -61,7 +60,6 @@ interface PlanSidebarProps { workspaceRoot: string | undefined; timestampFormat: TimestampFormat; mode?: "sheet" | "sidebar" | "embedded"; - onClose: () => void; } const PlanSidebar = memo(function PlanSidebar({ @@ -74,7 +72,6 @@ const PlanSidebar = memo(function PlanSidebar({ workspaceRoot, timestampFormat, mode = "sidebar", - onClose, }: PlanSidebarProps) { const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false); const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false); @@ -182,15 +179,6 @@ const PlanSidebar = memo(function PlanSidebar({ ) : null} -
diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index b5c419a088..ead306f7c9 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -27,6 +27,7 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon"; interface RightPanelTabsProps { mode: PreviewPanelMode; maximized?: boolean; + layoutControls?: ReactNode; surfaces: readonly RightPanelSurface[]; activeSurfaceId: string | null; pendingSurfaceIds: ReadonlySet; @@ -342,8 +343,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) { >
+ {props.layoutControls}
{props.activeSurfaceId === null ? ( diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index db694644a0..2bfc204cec 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -72,15 +72,15 @@ export const ChatHeader = memo(function ChatHeader({ primaryEnvironmentId, }); return ( -
-
+
+
{activeThreadTitle} @@ -92,7 +92,7 @@ export const ChatHeader = memo(function ChatHeader({
diff --git a/apps/web/src/components/chat/PanelLayoutControls.tsx b/apps/web/src/components/chat/PanelLayoutControls.tsx index 3b7fbf4ad9..deb7b3ee9a 100644 --- a/apps/web/src/components/chat/PanelLayoutControls.tsx +++ b/apps/web/src/components/chat/PanelLayoutControls.tsx @@ -1,8 +1,6 @@ import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon } from "lucide-react"; import { memo } from "react"; -import { cn } from "~/lib/utils"; - import { Toggle } from "../ui/toggle"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -13,11 +11,8 @@ interface PanelLayoutControlsProps { rightPanelAvailable: boolean; rightPanelOpen: boolean; rightPanelShortcutLabel: string | null; - rightPanelMaximized: boolean; - canMaximizeRightPanel: boolean; onToggleTerminal: () => void; onToggleRightPanel: () => void; - onToggleRightPanelMaximized: () => void; } export const PanelLayoutControls = memo(function PanelLayoutControls({ @@ -27,47 +22,14 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({ rightPanelAvailable, rightPanelOpen, rightPanelShortcutLabel, - rightPanelMaximized, - canMaximizeRightPanel, onToggleTerminal, onToggleRightPanel, - onToggleRightPanelMaximized, }: PanelLayoutControlsProps) { return (
- {rightPanelOpen ? ( - - - {rightPanelMaximized ? ( - - ) : ( - - )} - - } - /> - - {canMaximizeRightPanel - ? rightPanelMaximized - ? "Restore panel size" - : "Maximize panel" - : "Panel maximization is unavailable at this width"} - - - ) : null} ); }); + +export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl({ + maximized, + onToggle, +}: { + maximized: boolean; + onToggle: () => void; +}) { + const label = maximized ? "Restore panel size" : "Maximize panel"; + return ( + + + {maximized ? ( + + ) : ( + + )} + + } + /> + {label} + + ); +}); From b489ea52a85b6e6d698523a696f42d7fc730015f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 16 Jun 2026 22:40:22 -0700 Subject: [PATCH 2/2] Improve inline panel, file preview, and MCP session handling (#3121) --- .../src/components/ChatMarkdown.browser.tsx | 7 + apps/web/src/components/ChatMarkdown.tsx | 8 +- apps/web/src/components/ChatView.browser.tsx | 92 ++++++- apps/web/src/components/ChatView.tsx | 4 + .../src/components/files/FilePreviewPanel.tsx | 255 +++++++++++++++++- apps/web/src/rightPanelStore.test.ts | 91 ++++++- apps/web/src/rightPanelStore.ts | 62 ++++- 7 files changed, 489 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx index 7ef3409766..7d5fddb6e2 100644 --- a/apps/web/src/components/ChatMarkdown.browser.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.tsx @@ -288,6 +288,13 @@ describe("ChatMarkdown", () => { ).toMatchObject({ isOpen: true, activeSurfaceId: "file:apps/web/src/components/ChatMarkdown.tsx", + surfaces: [ + expect.objectContaining({ + relativePath: "apps/web/src/components/ChatMarkdown.tsx", + revealLine: 978, + revealRequestId: 1, + }), + ], }); expect(openInPreferredEditorMock).not.toHaveBeenCalled(); expect(openFileInPreviewMock).not.toHaveBeenCalled(); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index bfb9cbd77e..bc14e30836 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -671,6 +671,7 @@ interface MarkdownFileLinkProps { iconPath: string; displayPath: string; workspaceRelativePath: string | null; + line?: number | undefined; label: string; copyMarkdown: string; theme: "light" | "dark"; @@ -995,6 +996,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ iconPath, displayPath, workspaceRelativePath, + line, label, copyMarkdown, theme, @@ -1027,8 +1029,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ handleOpenInEditor(); return; } - useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath); - }, [handleOpenInEditor, threadRef, workspaceRelativePath]); + useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath, line); + }, [handleOpenInEditor, line, threadRef, workspaceRelativePath]); const handleOpenInBrowser = useCallback(() => { if (!threadRef) return; @@ -1169,6 +1171,7 @@ function areMarkdownFileLinkPropsEqual( previous.iconPath === next.iconPath && previous.displayPath === next.displayPath && previous.workspaceRelativePath === next.workspaceRelativePath && + previous.line === next.line && previous.label === next.label && previous.copyMarkdown === next.copyMarkdown && previous.theme === next.theme && @@ -1331,6 +1334,7 @@ function ChatMarkdown({ iconPath={fileLinkMeta.filePath} displayPath={fileLinkMeta.displayPath} workspaceRelativePath={fileLinkMeta.workspaceRelativePath} + line={fileLinkMeta.line} label={labelParts.join(" ยท ")} copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`} theme={resolvedTheme} diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 90790a01b5..0bb881a8fa 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -2700,13 +2700,97 @@ describe("ChatView timeline estimator parity (full app)", () => { expect(fileTree.shadowRoot?.activeElement).toBe(fileSearchInput); expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe(""); - useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts"); - const codeVirtualizer = await waitForElement( - () => document.querySelector(".file-preview-virtualizer"), - "Unable to find the virtualized file preview.", + const previousCodeVirtualizer = document.querySelector( + ".file-preview-virtualizer", ); + useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts", 4_000); + const codeVirtualizer = await waitForElement(() => { + const current = document.querySelector(".file-preview-virtualizer"); + return current !== previousCodeVirtualizer ? current : null; + }, "Unable to find the virtualized file preview."); expect(codeVirtualizer.querySelector("diffs-container")).not.toBeNull(); expect(codeVirtualizer.classList.contains("overflow-auto")).toBe(true); + await vi.waitFor( + () => { + const fileHost = codeVirtualizer.querySelector("diffs-container"); + const targetLine = fileHost?.shadowRoot?.querySelector('[data-line="4000"]'); + const targetLineNumber = fileHost?.shadowRoot?.querySelector( + '[data-column-number="4000"]', + ); + const previousLine = + fileHost?.shadowRoot?.querySelector('[data-line="3999"]'); + const previousLineNumber = fileHost?.shadowRoot?.querySelector( + '[data-column-number="3999"]', + ); + expect(codeVirtualizer.scrollTop).toBeGreaterThan(0); + expect(targetLine).not.toBeNull(); + expect(previousLine).not.toBeNull(); + expect(targetLine?.hasAttribute("data-file-link-reveal")).toBe(true); + expect(targetLineNumber?.hasAttribute("data-file-link-reveal")).toBe(true); + expect(targetLine?.hasAttribute("data-selected-line")).toBe(false); + expect(targetLineNumber?.hasAttribute("data-selected-line")).toBe(false); + expect(targetLineNumber?.querySelector("[data-gutter-utility-slot]")).toBeNull(); + expect(window.getComputedStyle(targetLine!).backgroundColor).not.toBe( + window.getComputedStyle(previousLine!).backgroundColor, + ); + expect(window.getComputedStyle(targetLineNumber!).backgroundColor).not.toBe( + window.getComputedStyle(previousLineNumber!).backgroundColor, + ); + + const viewportRect = codeVirtualizer.getBoundingClientRect(); + const lineRect = targetLine!.getBoundingClientRect(); + expect(lineRect.top).toBeGreaterThanOrEqual(viewportRect.top); + expect(lineRect.bottom).toBeLessThanOrEqual(viewportRect.bottom); + }, + { timeout: 8_000, interval: 16 }, + ); + + const fileHost = codeVirtualizer.querySelector("diffs-container"); + const targetLineNumber = + fileHost?.shadowRoot?.querySelector('[data-column-number="4000"]') ?? null; + const previousLineNumber = + fileHost?.shadowRoot?.querySelector('[data-column-number="3999"]') ?? null; + expect(targetLineNumber).not.toBeNull(); + expect(previousLineNumber).not.toBeNull(); + + targetLineNumber!.dispatchEvent( + new PointerEvent("pointermove", { + bubbles: true, + cancelable: true, + composed: true, + pointerType: "mouse", + }), + ); + await vi.waitFor(() => { + expect(targetLineNumber?.querySelector("[data-gutter-utility-slot]")).not.toBeNull(); + }); + + previousLineNumber!.dispatchEvent( + new PointerEvent("pointermove", { + bubbles: true, + cancelable: true, + composed: true, + pointerType: "mouse", + }), + ); + await vi.waitFor(() => { + expect(targetLineNumber?.querySelector("[data-gutter-utility-slot]")).toBeNull(); + expect(previousLineNumber?.querySelector("[data-gutter-utility-slot]")).not.toBeNull(); + }); + + codeVirtualizer.scrollTop = 0; + useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts", 4_000); + await vi.waitFor( + () => { + const fileHost = codeVirtualizer.querySelector("diffs-container"); + const targetLine = fileHost?.shadowRoot?.querySelector('[data-line="4000"]'); + expect(targetLine).not.toBeNull(); + expect(targetLine?.hasAttribute("data-file-link-reveal")).toBe(true); + expect(targetLine?.hasAttribute("data-selected-line")).toBe(false); + expect(codeVirtualizer.scrollTop).toBeGreaterThan(0); + }, + { timeout: 8_000, interval: 16 }, + ); } finally { await mounted.cleanup(); } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 5cd0583e78..52f2594551 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1292,6 +1292,8 @@ function ChatViewContent(props: ChatViewProps) { const activeRightPanelSurface = useRightPanelStore((store) => selectActiveRightPanelSurface(store.byThreadKey, activeThreadRef), ); + const activeFileSurface = + activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null; const activePreviewState = usePreviewStateStore((state) => selectThreadPreviewState(state.byThreadKey, activeThreadRef), ); @@ -4768,6 +4770,8 @@ function ChatViewContent(props: ChatViewProps) { relativePath={ activeRightPanelSurface.kind === "file" ? activeRightPanelSurface.relativePath : null } + revealLine={activeFileSurface?.revealLine ?? null} + revealRequestId={activeFileSurface?.revealRequestId ?? 0} onOpenFile={openFileSurface} onPendingChange={handleFilePendingChange} /> diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index d3d24a79bd..501b8355a0 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -4,9 +4,9 @@ import type { ResolvedKeybindingsConfig, ScopedThreadRef, } from "@t3tools/contracts"; -import type { SelectedLineRange } from "@pierre/diffs"; +import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs"; import { Editor } from "@pierre/diffs/editor"; -import { EditorProvider, File, Virtualizer } from "@pierre/diffs/react"; +import { EditorProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react"; import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -59,12 +59,176 @@ interface FilePreviewPanelProps { composerDraftTarget: ScopedThreadRef | DraftId; keybindings: ResolvedKeybindingsConfig; availableEditors: ReadonlyArray; + revealLine: number | null; + revealRequestId: number; onOpenFile: (relativePath: string) => void; onPendingChange: (relativePath: string, pending: boolean) => void; } const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen"; const FILE_SAVE_DEBOUNCE_MS = 500; +const FILE_LINK_REVEAL_ATTRIBUTE = "data-file-link-reveal"; +const FILE_LINK_REVEAL_UNSAFE_CSS = ` + [${FILE_LINK_REVEAL_ATTRIBUTE}][data-line] { + background-color: light-dark( + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 82%, + var(--diffs-bg-selection-override, var(--diffs-selection-base)) + ), + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 75%, + var(--diffs-bg-selection-override, var(--diffs-selection-base)) + ) + ) !important; + } + + [${FILE_LINK_REVEAL_ATTRIBUTE}][data-column-number] { + background-color: light-dark( + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 75%, + var(--diffs-bg-selection-number-override, var(--diffs-selection-base)) + ), + color-mix( + in lab, + var(--diffs-computed-diff-line-bg) 60%, + var(--diffs-bg-selection-number-override, var(--diffs-selection-base)) + ) + ) !important; + color: var(--diffs-selection-number-fg) !important; + } +`; +type FilePostRender = NonNullable["onPostRender"]>; + +function clampFileLine(contents: string, requestedLine: number): number { + let lineCount = 1; + for (let index = 0; index < contents.length; index += 1) { + const character = contents.charCodeAt(index); + if (character === 10) { + lineCount += 1; + } else if (character === 13) { + lineCount += 1; + if (contents.charCodeAt(index + 1) === 10) index += 1; + } + } + return Math.min(Math.max(1, requestedLine), lineCount); +} + +function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void { + const root = fileContainer.shadowRoot ?? fileContainer; + for (const element of root.querySelectorAll(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) { + element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE); + } + if (line === null) return; + + root + .querySelector(`[data-line="${line}"]`) + ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, ""); + root + .querySelector(`[data-column-number="${line}"]`) + ?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, ""); +} + +function useFileLineReveal( + relativePath: string | null, + revealLine: number | null, + revealRequestId: number, +): FilePostRender { + const [handledRequestIdsByPath] = useState(() => new Map()); + const [latestRequestIdsByPath] = useState(() => new Map()); + const [pendingFramesByPath] = useState(() => new Map()); + + return useCallback( + (fileContainer, instance, phase) => { + if (relativePath === null) return; + + const cancelPendingReveal = () => { + const frameId = pendingFramesByPath.get(relativePath); + if (frameId !== undefined) { + cancelAnimationFrame(frameId); + pendingFramesByPath.delete(relativePath); + } + }; + + if (phase === "unmount") { + cancelPendingReveal(); + return; + } + + const targetLine = + revealLine === null ? null : clampFileLine(instance.file?.contents ?? "", revealLine); + updateFileLinkReveal(fileContainer, targetLine); + + if (!(instance instanceof VirtualizedFile)) return; + + if (latestRequestIdsByPath.get(relativePath) !== revealRequestId) { + cancelPendingReveal(); + latestRequestIdsByPath.set(relativePath, revealRequestId); + } + + if (targetLine === null) { + fileContainer.style.minHeight = ""; + return; + } + + const scrollContainer = fileContainer.closest(".file-preview-virtualizer"); + if (!scrollContainer) return; + fileContainer.style.minHeight = `${Math.ceil( + Math.max(instance.height, scrollContainer.clientHeight), + )}px`; + + if ( + handledRequestIdsByPath.get(relativePath) === revealRequestId || + pendingFramesByPath.has(relativePath) + ) { + return; + } + + const reveal = () => { + pendingFramesByPath.delete(relativePath); + if ( + latestRequestIdsByPath.get(relativePath) !== revealRequestId || + !fileContainer.isConnected + ) { + return; + } + + const linePosition = instance.getLinePosition(targetLine); + if (!linePosition) return; + + const fileTop = + scrollContainer.scrollTop + + fileContainer.getBoundingClientRect().top - + scrollContainer.getBoundingClientRect().top; + const centeredTop = Math.max( + 0, + fileTop + + linePosition.top - + Math.max(0, (scrollContainer.clientHeight - linePosition.height) / 2), + ); + const maxScrollTop = Math.max( + 0, + scrollContainer.scrollHeight - scrollContainer.clientHeight, + ); + + scrollContainer.scrollTop = Math.min(centeredTop, maxScrollTop); + handledRequestIdsByPath.set(relativePath, revealRequestId); + }; + + pendingFramesByPath.set(relativePath, requestAnimationFrame(reveal)); + }, + [ + handledRequestIdsByPath, + latestRequestIdsByPath, + pendingFramesByPath, + relativePath, + revealLine, + revealRequestId, + ], + ); +} interface EditableFileSurfaceProps { environmentId: EnvironmentId; @@ -73,9 +237,16 @@ interface EditableFileSurfaceProps { composerDraftTarget: ScopedThreadRef | DraftId; contents: string; resolvedTheme: "light" | "dark"; + revealRequestId: number; + onPostRender: FilePostRender; onPendingChange: (relativePath: string, pending: boolean) => void; } +interface FileSelectionOverride { + revealRequestId: number; + range: SelectedLineRange | null; +} + function useFileSaveCoordinator({ environmentId, cwd, @@ -115,13 +286,24 @@ function EditableFileSurface({ composerDraftTarget, contents, resolvedTheme, + revealRequestId, + onPostRender, onPendingChange, }: EditableFileSurfaceProps) { const addReviewComment = useComposerDraftStore((store) => store.addReviewComment); const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment); const [lineAnnotations, setLineAnnotations] = useState([]); - const [selectedRange, setSelectedRange] = useState(null); + const [selectionOverride, setSelectionOverride] = useState(null); + const selectedRange = + selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null; + const setSelectedRange = useCallback( + (range: SelectedLineRange | null) => { + setSelectionOverride({ revealRequestId, range }); + }, + [revealRequestId], + ); const surfaceRef = useRef(null); + const selectionFrameRef = useRef(null); const saveCoordinator = useFileSaveCoordinator({ environmentId, cwd, @@ -179,7 +361,7 @@ function EditableFileSurface({ }); }); }, - [composerDraftTarget, removeReviewComment], + [composerDraftTarget, removeReviewComment, setSelectedRange], ); const submitAnnotationEntry = useCallback( @@ -214,7 +396,14 @@ function EditableFileSurface({ })), ); }, - [addReviewComment, composerDraftTarget, contents, lineAnnotations, relativePath], + [ + addReviewComment, + composerDraftTarget, + contents, + lineAnnotations, + relativePath, + setSelectedRange, + ], ); const beginComment = useCallback((range: SelectedLineRange) => { @@ -265,7 +454,7 @@ function EditableFileSurface({ isBlocked: () => hasOpenCommentForm, onDismiss: () => setSelectedRange(null), }); - }, [editor, hasOpenCommentForm]); + }, [editor, hasOpenCommentForm, setSelectedRange]); const handleLineSelectionEnd = useCallback( (range: SelectedLineRange | null) => { setSelectedRange(range); @@ -273,7 +462,26 @@ function EditableFileSurface({ beginComment(range); } }, - [beginComment], + [beginComment, setSelectedRange], + ); + + const handlePostRender = useCallback( + (fileContainer, instance, phase) => { + onPostRender(fileContainer, instance, phase); + + if (selectionFrameRef.current !== null) { + cancelAnimationFrame(selectionFrameRef.current); + selectionFrameRef.current = null; + } + if (phase === "unmount") return; + + selectionFrameRef.current = requestAnimationFrame(() => { + selectionFrameRef.current = null; + if (!fileContainer.isConnected) return; + instance.setSelectedLines(selectedRange, { notify: false }); + }); + }, + [onPostRender, selectedRange], ); return ( @@ -302,6 +510,8 @@ function EditableFileSurface({ overflow: "scroll", theme: resolveDiffThemeName(resolvedTheme), themeType: resolvedTheme, + unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, + onPostRender: handlePostRender, }} selectedLines={selectedRange} lineAnnotations={lineAnnotations} @@ -336,7 +546,10 @@ function RenderedMarkdownSurface({ contents, threadRef, onPendingChange, -}: Omit & { +}: Omit< + EditableFileSurfaceProps, + "resolvedTheme" | "composerDraftTarget" | "revealLine" | "revealRequestId" | "onPostRender" +> & { threadRef: ScopedThreadRef; }) { const saveCoordinator = useFileSaveCoordinator({ @@ -384,6 +597,8 @@ export default function FilePreviewPanel({ composerDraftTarget, keybindings, availableEditors, + revealLine, + revealRequestId, onOpenFile, onPendingChange, }: FilePreviewPanelProps) { @@ -391,10 +606,16 @@ export default function FilePreviewPanel({ const primaryEnvironmentId = usePrimaryEnvironmentId(); const file = useProjectFileQuery(environmentId, cwd, relativePath); const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen); - const [renderedMarkdownPath, setRenderedMarkdownPath] = useState(null); + const [markdownView, setMarkdownView] = useState<{ + path: string | null; + revealRequestId: number | null; + }>({ path: null, revealRequestId: null }); const breadcrumbRef = useRef(null); const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false; - const renderMarkdown = isMarkdown && renderedMarkdownPath === relativePath; + const renderMarkdown = + isMarkdown && + markdownView.path === relativePath && + (revealLine === null || markdownView.revealRequestId === revealRequestId); const canOpenInBrowser = relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath); const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null; @@ -402,6 +623,7 @@ export default function FilePreviewPanel({ () => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []), [projectName, relativePath], ); + const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId); useEffect(() => { const currentCrumb = breadcrumbRef.current?.querySelector( @@ -485,9 +707,12 @@ export default function FilePreviewPanel({ - setRenderedMarkdownPath(pressed ? relativePath : null) - } + onPressedChange={(pressed) => { + setMarkdownView({ + path: pressed ? relativePath : null, + revealRequestId: pressed ? revealRequestId : null, + }); + }} aria-label={renderMarkdown ? "Show markdown source" : "Show rendered markdown"} variant="ghost" size="sm" @@ -591,6 +816,8 @@ export default function FilePreviewPanel({ overflow: "scroll", theme: resolveDiffThemeName(resolvedTheme), themeType: resolvedTheme, + unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, + onPostRender: onFilePostRender, }} className="min-h-full" /> @@ -604,6 +831,8 @@ export default function FilePreviewPanel({ composerDraftTarget={composerDraftTarget} contents={file.data.contents} resolvedTheme={resolvedTheme} + revealRequestId={revealRequestId} + onPostRender={onFilePostRender} onPendingChange={onPendingChange} /> ) diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index bf15164d51..2995defc12 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -73,6 +73,36 @@ describe("rightPanelStore", () => { }); }); + it("upgrades saved file surfaces with neutral reveal state", () => { + expect( + migratePersistedRightPanelState({ + byThreadKey: { + "env-1:thread-A": { + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [{ id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" }], + }, + }, + }), + ).toEqual({ + byThreadKey: { + "env-1:thread-A": { + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 0, + }, + ], + }, + }, + }); + }); + it("open sets the active panel for a thread", () => { useRightPanelStore.getState().open(refA, "preview"); expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview"); @@ -108,8 +138,55 @@ describe("rightPanelStore", () => { isOpen: true, activeSurfaceId: "file:README.md", surfaces: [ - { id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" }, - { id: "file:README.md", kind: "file", relativePath: "README.md" }, + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 2, + }, + { + id: "file:README.md", + kind: "file", + relativePath: "README.md", + revealLine: null, + revealRequestId: 1, + }, + ], + }); + }); + + it("updates line reveal requests when reopening a file surface", () => { + useRightPanelStore.getState().openFile(refA, "src/index.ts", 42); + useRightPanelStore.getState().openFile(refA, "src/index.ts", 87); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: 87, + revealRequestId: 2, + }, + ], + }); + + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 3, + }, ], }); }); @@ -314,7 +391,15 @@ describe("rightPanelStore", () => { expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ isOpen: true, activeSurfaceId: "file:src/index.ts", - surfaces: [{ id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" }], + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 1, + }, + ], }); }); diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 40164ffdd9..08f0c0cfd5 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -30,11 +30,17 @@ export type RightPanelSurface = } | { id: "diff"; kind: "diff" } | { id: "files"; kind: "files" } - | { id: `file:${string}`; kind: "file"; relativePath: string } + | { + id: `file:${string}`; + kind: "file"; + relativePath: string; + revealLine: number | null; + revealRequestId: number; + } | { id: "plan"; kind: "plan" }; const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2"; -const RIGHT_PANEL_STORAGE_VERSION = 6; +const RIGHT_PANEL_STORAGE_VERSION = 7; export interface ThreadRightPanelState { isOpen: boolean; @@ -46,7 +52,7 @@ interface RightPanelStoreState { byThreadKey: Record; open: (ref: ScopedThreadRef, kind: Exclude) => void; openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void; - openFile: (ref: ScopedThreadRef, relativePath: string) => void; + openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void; openTerminal: (ref: ScopedThreadRef, terminalId: string) => void; splitTerminal: ( ref: ScopedThreadRef, @@ -94,10 +100,16 @@ const browserSurface = (tabId: string | null): RightPanelSurface => ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId } : { id: "browser:new", kind: "preview", resourceId: null }; -const fileSurface = (relativePath: string): RightPanelSurface => ({ +const fileSurface = ( + relativePath: string, + revealLine: number | null, + revealRequestId: number, +): RightPanelSurface => ({ id: `file:${relativePath}`, kind: "file", relativePath, + revealLine, + revealRequestId, }); const terminalSurface = (terminalId: string): RightPanelSurface => ({ @@ -136,6 +148,11 @@ const updateThread = ( return { ...byThreadKey, [threadKey]: next }; }; +function normalizeRevealLine(line: number | undefined): number | null { + if (line === undefined || !Number.isFinite(line)) return null; + return Math.max(1, Math.trunc(line)); +} + export function migratePersistedRightPanelState(persistedState: unknown): { byThreadKey: Record; } { @@ -153,6 +170,20 @@ export function migratePersistedRightPanelState(persistedState: unknown): { threadState && typeof threadState === "object" ? threadState : null; const surfaces = Array.isArray(validThreadState?.surfaces) ? validThreadState.surfaces.flatMap((surface) => { + if (surface.kind === "file") { + const revealLine = + typeof surface.revealLine === "number" && + Number.isFinite(surface.revealLine) + ? Math.max(1, Math.trunc(surface.revealLine)) + : null; + const revealRequestId = + typeof surface.revealRequestId === "number" && + Number.isSafeInteger(surface.revealRequestId) && + surface.revealRequestId >= 0 + ? surface.revealRequestId + : 0; + return [{ ...surface, revealLine, revealRequestId }]; + } if (surface.kind !== "terminal") return [surface]; if ( !("resourceId" in surface) || @@ -228,16 +259,31 @@ export const useRightPanelStore = create()( return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface); }), })), - openFile: (ref, relativePath) => + openFile: (ref, relativePath, line) => set((state) => ({ byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { const withoutStandaloneExplorer = current.surfaces.filter( (surface) => surface.kind !== "files", ); - return upsertSurface( - { ...current, surfaces: withoutStandaloneExplorer }, - fileSurface(relativePath), + const surfaceId = `file:${relativePath}` as const; + const existing = withoutStandaloneExplorer.find( + (surface): surface is Extract => + surface.id === surfaceId && surface.kind === "file", ); + const surface = fileSurface( + relativePath, + normalizeRevealLine(line), + (existing?.revealRequestId ?? 0) + 1, + ); + return { + isOpen: true, + activeSurfaceId: surface.id, + surfaces: existing + ? withoutStandaloneExplorer.map((entry) => + entry.id === surface.id ? surface : entry, + ) + : [...withoutStandaloneExplorer, surface], + }; }), })), openTerminal: (ref, terminalId) =>