Merge origin/main into codex/connection-state-audit

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-16 23:38:01 -07:00
commit bd079220f8
11 files changed
+614 -310

No files matched your search

@@ -303,6 +303,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();
+6 -2
View File
@@ -678,6 +678,7 @@ interface MarkdownFileLinkProps {
iconPath: string;
displayPath: string;
workspaceRelativePath: string | null;
line?: number | undefined;
label: string;
copyMarkdown: string;
theme: "light" | "dark";
@@ -956,6 +957,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
iconPath,
displayPath,
workspaceRelativePath,
line,
label,
copyMarkdown,
theme,
@@ -981,8 +983,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(() => {
void onOpenInBrowser?.().catch((error) => {
@@ -1112,6 +1114,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 &&
@@ -1330,6 +1333,7 @@ function ChatMarkdown({
iconPath={fileLinkMeta.filePath}
displayPath={fileLinkMeta.displayPath}
workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
line={fileLinkMeta.line}
label={labelParts.join(" · ")}
copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`}
theme={resolvedTheme}
+7 -4
View File
@@ -2373,16 +2373,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Close plan sidebar"]'),
() =>
Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
(element) => element.textContent?.trim() === "Ship plan mode follow-up",
) ?? null,
"Unable to find persisted plan surface content.",
);
for (const viewport of [WIDE_FOOTER_VIEWPORT, COMPACT_FOOTER_VIEWPORT]) {
await mounted.setViewport(viewport);
await vi.waitFor(() => {
expect(
document.querySelectorAll<HTMLButtonElement>('button[aria-label="Close plan sidebar"]'),
).toHaveLength(1);
expect(document.body.textContent).toContain("Ship plan mode follow-up");
expect(
document.querySelector<HTMLElement>("[data-right-panel-tabbar]")?.textContent,
).toContain("Plan");
});
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF),
+163 -221
View File
@@ -184,7 +184,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 } from "./BranchToolbar.logic";
@@ -1126,7 +1126,6 @@ function ChatViewContent(props: ChatViewProps) {
>({});
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
@@ -1278,6 +1277,8 @@ function ChatViewContent(props: ChatViewProps) {
const activeRightPanelSurface = useRightPanelStore((state) =>
selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef),
);
const activeFileSurface =
activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;
const activePreviewState = usePreviewStateStore((state) =>
selectThreadPreviewState(state.byThreadKey, activeThreadRef),
);
@@ -1296,7 +1297,6 @@ function ChatViewContent(props: ChatViewProps) {
);
const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime();
const rightPanelOpen = rightPanelState.isOpen;
const rightPanelPlanOpen = rightPanelOpen && activeRightPanelSurface?.kind === "plan";
const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet;
const rightPanelMaximized =
canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey;
@@ -1331,6 +1331,7 @@ function ChatViewContent(props: ChatViewProps) {
reconcileTerminalIds,
terminalUiState.terminalIds,
]);
const planSidebarOpen = activeRightPanelKind === "plan";
useEffect(() => {
if (!activeThreadRef || !diffOpen) return;
@@ -2708,23 +2709,25 @@ function ChatViewContent(props: ChatViewProps) {
const toggleInteractionMode = useCallback(() => {
handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");
}, [handleInteractionModeChange, interactionMode]);
const togglePlanSidebar = useCallback(() => {
setPlanSidebarOpen((open) => {
if (open) {
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
} else {
planSidebarDismissedForTurnRef.current = null;
}
return !open;
});
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
const closePlanSidebar = useCallback(() => {
setMaximizedRightPanelThreadKey(null);
setPlanSidebarOpen(false);
const dismissPlanSidebarForCurrentTurn = useCallback(() => {
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
const togglePlanSidebar = useCallback(() => {
if (!activeThreadRef) return;
if (planSidebarOpen) {
dismissPlanSidebarForCurrentTurn();
} else {
planSidebarDismissedForTurnRef.current = null;
}
useRightPanelStore.getState().toggle(activeThreadRef, "plan");
}, [activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]);
const closePlanSidebar = useCallback(() => {
if (!activeThreadRef) return;
setMaximizedRightPanelThreadKey(null);
useRightPanelStore.getState().close(activeThreadRef);
dismissPlanSidebarForCurrentTurn();
}, [activeThreadRef, dismissPlanSidebarForCurrentTurn]);
const createBrowserSurface = useCallback(() => {
if (!activeThreadRef) return;
const activeTabId = activePreviewState.activeTabId;
@@ -2904,6 +2907,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);
@@ -2928,13 +2936,29 @@ 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 (rightPanelOpen) {
if (planSidebarOpen) {
closePlanSidebar();
} else {
closePreviewPanel();
}
return;
}
useRightPanelStore.getState().toggleVisibility(activeThreadRef);
}, [activeThreadRef, rightPanelOpen]);
}, [activeThreadRef, closePlanSidebar, closePreviewPanel, planSidebarOpen, rightPanelOpen]);
const toggleRightPanelMaximized = useCallback(() => {
if (!canMaximizeRightPanel) return;
setMaximizedRightPanelThreadKey((threadKey) =>
@@ -2944,6 +2968,9 @@ function ChatViewContent(props: ChatViewProps) {
const cleanupRightPanelSurfaces = useCallback(
(surfaces: readonly RightPanelSurface[]) => {
if (!activeThreadRef) return;
if (surfaces.some((surface) => surface.kind === "plan")) {
dismissPlanSidebarForCurrentTurn();
}
for (const surface of surfaces) {
if (surface.kind === "preview" && surface.resourceId) {
@@ -2962,10 +2989,6 @@ function ChatViewContent(props: ChatViewProps) {
}
}
}
if (surfaces.some((surface) => surface.kind === "plan")) {
closePlanSidebar();
}
if (diffOpen && surfaces.some((surface) => surface.kind === "diff")) {
void navigate({
to: "/$environmentId/$threadId",
@@ -2978,9 +3001,9 @@ function ChatViewContent(props: ChatViewProps) {
[
activeThreadRef,
closePreview,
closePlanSidebar,
closeTerminalMutation,
diffOpen,
dismissPlanSidebarForCurrentTurn,
environmentId,
navigate,
threadId,
@@ -3168,12 +3191,13 @@ function ChatViewContent(props: ChatViewProps) {
setShowScrollToBottom(false);
if (planSidebarOpenOnNextThreadRef.current) {
planSidebarOpenOnNextThreadRef.current = false;
setPlanSidebarOpen(true);
} else {
planSidebarOpenOnNextThreadRef.current = false;
setPlanSidebarOpen(false);
if (activeThreadRef) {
useRightPanelStore.getState().open(activeThreadRef, "plan");
}
}
planSidebarDismissedForTurnRef.current = null;
// activeThreadRef resets transitively with the active thread.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeThread?.id]);
// Auto-open the plan sidebar when plan/todo steps arrive for the current turn.
@@ -3186,10 +3210,13 @@ function ChatViewContent(props: ChatViewProps) {
if (latestTurnId && activePlan.turnId !== latestTurnId) return;
const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
if (planSidebarDismissedForTurnRef.current === turnKey) return;
setPlanSidebarOpen(true);
if (activeThreadRef) {
useRightPanelStore.getState().open(activeThreadRef, "plan");
}
}, [
activePlan,
activeLatestTurn?.turnId,
activeThreadRef,
autoOpenPlanSidebar,
planSidebarOpen,
sidebarProposedPlan?.turnId,
@@ -4170,7 +4197,9 @@ function ChatViewContent(props: ChatViewProps) {
// step-tracking activities that the sidebar will display.
if (nextInteractionMode === "default" && autoOpenPlanSidebar) {
planSidebarDismissedForTurnRef.current = null;
setPlanSidebarOpen(true);
if (activeThreadRef) {
useRightPanelStore.getState().open(activeThreadRef, "plan");
}
}
sendInFlightRef.current = false;
} catch (err) {
@@ -4505,24 +4534,105 @@ function ChatViewContent(props: ChatViewProps) {
return <NoActiveThreadState />;
}
const panelToggleControls = (
<PanelLayoutControls
terminalAvailable={activeProject !== null}
terminalOpen={terminalUiState.terminalOpen}
terminalShortcutLabel={shortcutLabelForCommand(keybindings, "terminal.toggle")}
rightPanelAvailable={activeProject !== null}
rightPanelOpen={rightPanelOpen}
rightPanelShortcutLabel={shortcutLabelForCommand(keybindings, "rightPanel.toggle")}
onToggleTerminal={toggleTerminalVisibility}
onToggleRightPanel={toggleRightPanel}
/>
);
const panelLayoutControls = (
<div className="workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]">
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
onToggle={toggleRightPanelMaximized}
/>
) : null}
{panelToggleControls}
</div>
);
const rightPanelContent = activeThreadRef ? (
activeRightPanelSurface?.kind === "preview" ? (
<Suspense fallback={null}>
<PreviewPanel
mode="embedded"
threadRef={activeThreadRef}
tabId={activeRightPanelSurface.resourceId}
configuredUrls={configuredPreviewUrls}
visible
/>
</Suspense>
) : activeRightPanelSurface?.kind === "terminal" ? (
<PersistentThreadTerminalPanel
threadRef={activeThreadRef}
surface={activeRightPanelSurface}
launchContext={activeTerminalLaunchContext ?? null}
focusRequestId={terminalFocusRequestId}
keybindings={keybindings}
onAddTerminalContext={addTerminalContextToDraft}
onSplitTerminal={splitPanelTerminal}
onSplitTerminalVertical={splitPanelTerminalVertical}
onNewTerminal={addTerminalSurface}
onActiveTerminalChange={activatePanelTerminal}
onCloseTerminal={closePanelTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
/>
) : activeRightPanelSurface?.kind === "diff" ? (
<Suspense fallback={null}>
<DiffPanel mode="embedded" composerDraftTarget={composerDraftTarget} />
</Suspense>
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
threadRef={activeThreadRef}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="embedded"
/>
) : (activeRightPanelSurface?.kind === "files" || activeRightPanelSurface?.kind === "file") &&
activeProject &&
activeWorkspaceRoot ? (
<Suspense fallback={null}>
<FilePreviewPanel
key={`${activeProject.environmentId}:${activeWorkspaceRoot}`}
environmentId={activeProject.environmentId}
cwd={activeWorkspaceRoot}
projectName={activeProject.title}
threadRef={activeThreadRef}
composerDraftTarget={composerDraftTarget}
keybindings={keybindings}
availableEditors={availableEditors}
relativePath={
activeRightPanelSurface.kind === "file" ? activeRightPanelSurface.relativePath : null
}
revealLine={activeFileSurface?.revealLine ?? null}
revealRequestId={activeFileSurface?.revealRequestId ?? 0}
onOpenFile={openFileSurface}
onPendingChange={handleFilePendingChange}
/>
</Suspense>
) : null
) : null;
return (
<div className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">
{isElectron && activeThreadRef ? (
<PreviewAutomationOwner threadRef={activeThreadRef} visible={previewPanelOpen} />
) : null}
<PanelLayoutControls
terminalAvailable={activeProject !== null}
terminalOpen={terminalUiState.terminalOpen}
terminalShortcutLabel={shortcutLabelForCommand(keybindings, "terminal.toggle")}
rightPanelAvailable={activeProject !== null}
rightPanelOpen={rightPanelOpen}
rightPanelShortcutLabel={shortcutLabelForCommand(keybindings, "rightPanel.toggle")}
rightPanelMaximized={rightPanelMaximized}
canMaximizeRightPanel={canMaximizeRightPanel}
onToggleTerminal={toggleTerminalVisibility}
onToggleRightPanel={toggleRightPanel}
onToggleRightPanelMaximized={toggleRightPanelMaximized}
/>
{rightPanelOpen && !shouldUsePlanSidebarSheet ? panelLayoutControls : null}
<div
className={cn(
"flex min-h-0 min-w-0 flex-col overflow-x-hidden",
@@ -4532,18 +4642,20 @@ function ChatViewContent(props: ChatViewProps) {
>
{/* Top bar */}
<header
data-chat-header
className={cn(
"border-b border-border",
isElectron
? cn(
"drag-region flex h-[52px] items-center px-3 sm:px-5 wco:h-[env(titlebar-area-height)]",
"workspace-topbar drag-region relative px-3 sm:px-5",
reserveTitleBarControlInset &&
!inlineRightPanelOwnsTitleBar &&
"wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
"wco:pr-[var(--workspace-native-controls-inset)]",
)
: "pb-2 pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-2 sm:pb-3 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-3",
: "workspace-topbar pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)]",
)}
>
{!rightPanelOpen ? panelLayoutControls : null}
<ChatHeader
activeThreadEnvironmentId={activeThread.environmentId}
activeThreadId={activeThread.id}
@@ -4557,17 +4669,12 @@ function ChatViewContent(props: ChatViewProps) {
}
keybindings={keybindings}
availableEditors={availableEditors}
terminalAvailable={activeProject !== null}
terminalOpen={terminalUiState.terminalOpen}
rightPanelAvailable={activeProject !== null}
rightPanelOpen={rightPanelOpen}
gitCwd={gitCwd}
onRunProjectScript={runProjectScript}
onAddProjectScript={saveProjectScript}
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
onToggleTerminal={toggleTerminalVisibility}
onToggleRightPanel={toggleRightPanel}
/>
</header>
@@ -4752,21 +4859,6 @@ function ChatViewContent(props: ChatViewProps) {
) : null}
</div>
{/* end chat column */}
{/* Plan sidebar */}
{planSidebarOpen && !rightPanelPlanOpen && !shouldUsePlanSidebarSheet ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="sidebar"
onClose={closePlanSidebar}
/>
) : null}
</div>
{/* end horizontal flex container */}
@@ -4788,21 +4880,6 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
{shouldUsePlanSidebarSheet && !rightPanelPlanOpen ? (
<RightPanelSheet open={planSidebarOpen} onClose={closePlanSidebar}>
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="sheet"
onClose={closePlanSidebar}
/>
</RightPanelSheet>
) : null}
</div>
{!shouldUsePlanSidebarSheet && rightPanelOpen && activeThreadRef ? (
@@ -4828,81 +4905,14 @@ function ChatViewContent(props: ChatViewProps) {
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
>
{activeRightPanelSurface?.kind === "preview" ? (
<Suspense fallback={null}>
<PreviewPanel
mode="embedded"
threadRef={activeThreadRef}
tabId={activeRightPanelSurface.resourceId}
configuredUrls={configuredPreviewUrls}
visible
/>
</Suspense>
) : activeRightPanelSurface?.kind === "terminal" ? (
<PersistentThreadTerminalPanel
threadRef={activeThreadRef}
surface={activeRightPanelSurface}
launchContext={activeTerminalLaunchContext ?? null}
focusRequestId={terminalFocusRequestId}
keybindings={keybindings}
onAddTerminalContext={addTerminalContextToDraft}
onSplitTerminal={splitPanelTerminal}
onSplitTerminalVertical={splitPanelTerminalVertical}
onNewTerminal={addTerminalSurface}
onActiveTerminalChange={activatePanelTerminal}
onCloseTerminal={closePanelTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
/>
) : activeRightPanelSurface?.kind === "diff" ? (
<DiffWorkerPoolProvider>
<Suspense fallback={null}>
<DiffPanel mode="embedded" composerDraftTarget={composerDraftTarget} />
</Suspense>
</DiffWorkerPoolProvider>
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="sheet"
onClose={() => closeRightPanelSurface(activeRightPanelSurface)}
/>
) : (activeRightPanelSurface?.kind === "files" ||
activeRightPanelSurface?.kind === "file") &&
activeProject ? (
<Suspense fallback={null}>
<FilePreviewPanel
key={`${activeProject.environmentId}:${activeProject.workspaceRoot}`}
environmentId={activeProject.environmentId}
cwd={activeProject.workspaceRoot}
projectName={activeProject.title}
threadRef={activeThreadRef}
composerDraftTarget={composerDraftTarget}
keybindings={keybindings}
availableEditors={availableEditors}
relativePath={
activeRightPanelSurface.kind === "file"
? activeRightPanelSurface.relativePath
: null
}
onOpenFile={openFileSurface}
onPendingChange={handleFilePendingChange}
/>
</Suspense>
) : null}
{rightPanelContent}
</RightPanelTabs>
) : null}
{shouldUsePlanSidebarSheet && rightPanelOpen && activeThreadRef ? (
<RightPanelSheet open onClose={closePreviewPanel}>
<RightPanelSheet open onClose={planSidebarOpen ? closePlanSidebar : closePreviewPanel}>
<RightPanelTabs
mode="sheet"
layoutControls={panelToggleControls}
surfaces={rightPanelState.surfaces}
activeSurfaceId={activeRightPanelSurface?.id ?? null}
pendingSurfaceIds={pendingFileSurfaceIds}
@@ -4922,75 +4932,7 @@ function ChatViewContent(props: ChatViewProps) {
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
>
{activeRightPanelSurface?.kind === "preview" ? (
<Suspense fallback={null}>
<PreviewPanel
mode="embedded"
threadRef={activeThreadRef}
tabId={activeRightPanelSurface.resourceId}
configuredUrls={configuredPreviewUrls}
visible
/>
</Suspense>
) : activeRightPanelSurface?.kind === "terminal" ? (
<PersistentThreadTerminalPanel
threadRef={activeThreadRef}
surface={activeRightPanelSurface}
launchContext={activeTerminalLaunchContext ?? null}
focusRequestId={terminalFocusRequestId}
keybindings={keybindings}
onAddTerminalContext={addTerminalContextToDraft}
onSplitTerminal={splitPanelTerminal}
onSplitTerminalVertical={splitPanelTerminalVertical}
onNewTerminal={addTerminalSurface}
onActiveTerminalChange={activatePanelTerminal}
onCloseTerminal={closePanelTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
/>
) : activeRightPanelSurface?.kind === "diff" ? (
<DiffWorkerPoolProvider>
<Suspense fallback={null}>
<DiffPanel mode="embedded" composerDraftTarget={composerDraftTarget} />
</Suspense>
</DiffWorkerPoolProvider>
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="sheet"
onClose={() => closeRightPanelSurface(activeRightPanelSurface)}
/>
) : (activeRightPanelSurface?.kind === "files" ||
activeRightPanelSurface?.kind === "file") &&
activeProject ? (
<Suspense fallback={null}>
<FilePreviewPanel
key={`${activeProject.environmentId}:${activeProject.workspaceRoot}`}
environmentId={activeProject.environmentId}
cwd={activeProject.workspaceRoot}
projectName={activeProject.title}
threadRef={activeThreadRef}
composerDraftTarget={composerDraftTarget}
keybindings={keybindings}
availableEditors={availableEditors}
relativePath={
activeRightPanelSurface.kind === "file"
? activeRightPanelSurface.relativePath
: null
}
onOpenFile={openFileSurface}
onPendingChange={handleFilePendingChange}
/>
</Suspense>
) : null}
{rightPanelContent}
</RightPanelTabs>
</RightPanelSheet>
) : null}
+5 -14
View File
@@ -1,6 +1,6 @@
import { memo, useState, useCallback } from "react";
import { useAtomSet } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
@@ -12,7 +12,6 @@ import {
ChevronRightIcon,
EllipsisIcon,
LoaderIcon,
PanelRightCloseIcon,
} from "lucide-react";
import { cn } from "~/lib/utils";
import type { ActivePlanState } from "../session-logic";
@@ -57,11 +56,11 @@ interface PlanSidebarProps {
activeProposedPlan: LatestProposedPlanState | null;
label?: string;
environmentId: EnvironmentId;
threadRef?: ScopedThreadRef | undefined;
markdownCwd: string | undefined;
workspaceRoot: string | undefined;
timestampFormat: TimestampFormat;
mode?: "sheet" | "sidebar";
onClose: () => void;
mode?: "sheet" | "sidebar" | "embedded";
}
const PlanSidebar = memo(function PlanSidebar({
@@ -69,11 +68,11 @@ const PlanSidebar = memo(function PlanSidebar({
activeProposedPlan,
label = "Plan",
environmentId,
threadRef,
markdownCwd,
workspaceRoot,
timestampFormat,
mode = "sidebar",
onClose,
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
@@ -183,15 +182,6 @@ const PlanSidebar = memo(function PlanSidebar({
</MenuPopup>
</Menu>
) : null}
<Button
size="icon-xs"
variant="ghost"
onClick={onClose}
aria-label={`Close ${label.toLowerCase()} sidebar`}
className="text-muted-foreground/50 hover:text-foreground/70"
>
<PanelRightCloseIcon className="size-3.5" />
</Button>
</div>
</div>
@@ -260,6 +250,7 @@ const PlanSidebar = memo(function PlanSidebar({
<ChatMarkdown
text={displayedPlanMarkdown ?? ""}
cwd={markdownCwd}
threadRef={threadRef}
isStreaming={false}
/>
</div>
+4 -2
View File
@@ -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<string>;
@@ -342,8 +343,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
>
<div
className={cn(
"px-2 pr-28",
props.mode === "inline" ? "workspace-topbar" : "flex h-10 shrink-0 items-center",
"workspace-topbar gap-1 pl-2",
props.mode === "inline" ? "pr-28" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
)}
data-right-panel-tabbar
@@ -457,6 +458,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
) : null}
</div>
</ScrollArea>
{props.layoutControls}
</div>
<div className="flex min-h-0 flex-1 flex-col">
{props.activeSurfaceId === null ? (
+4 -4
View File
@@ -88,15 +88,15 @@ export const ChatHeader = memo(function ChatHeader({
const rightPanelShortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle");
return (
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-2 overflow-hidden sm:flex-1 sm:flex-nowrap sm:gap-3">
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<Tooltip>
<TooltipTrigger
render={
<h2
aria-label={activeThreadTitle}
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
className="min-w-0 flex-1 truncate text-sm font-medium text-foreground"
>
{activeThreadTitle}
</h2>
@@ -108,7 +108,7 @@ export const ChatHeader = memo(function ChatHeader({
<div
data-chat-header-actions
className={cn(
"flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3",
"flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
rightPanelOpen ? "pr-0" : "pr-16",
)}
>
@@ -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 (
<div
className={cn("workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]")}
className="flex h-full shrink-0 items-center gap-1 [-webkit-app-region:no-drag]"
data-panel-layout-controls
>
{rightPanelOpen ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={rightPanelMaximized}
onPressedChange={onToggleRightPanelMaximized}
aria-label={rightPanelMaximized ? "Restore panel size" : "Maximize panel"}
variant="ghost"
size="sm"
disabled={!canMaximizeRightPanel}
>
{rightPanelMaximized ? (
<Minimize2Icon className="size-3.5" />
) : (
<Maximize2Icon className="size-3.5" />
)}
</Toggle>
}
/>
<TooltipPopup side="bottom">
{canMaximizeRightPanel
? rightPanelMaximized
? "Restore panel size"
: "Maximize panel"
: "Panel maximization is unavailable at this width"}
</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
@@ -115,3 +77,36 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
</div>
);
});
export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl({
maximized,
onToggle,
}: {
maximized: boolean;
onToggle: () => void;
}) {
const label = maximized ? "Restore panel size" : "Maximize panel";
return (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={maximized}
onPressedChange={onToggle}
aria-label={label}
variant="ghost"
size="sm"
>
{maximized ? (
<Minimize2Icon className="size-3.5" />
) : (
<Maximize2Icon className="size-3.5" />
)}
</Toggle>
}
/>
<TooltipPopup side="bottom">{label}</TooltipPopup>
</Tooltip>
);
});
@@ -4,10 +4,10 @@ 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 { useAtomSet } from "@effect/atom-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";
@@ -62,12 +62,176 @@ interface FilePreviewPanelProps {
composerDraftTarget: ScopedThreadRef | DraftId;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
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<FileOptions<unknown>["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<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
}
if (line === null) return;
root
.querySelector<HTMLElement>(`[data-line="${line}"]`)
?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
root
.querySelector<HTMLElement>(`[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<string, number>());
const [latestRequestIdsByPath] = useState(() => new Map<string, number>());
const [pendingFramesByPath] = useState(() => new Map<string, number>());
return useCallback<FilePostRender>(
(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<HTMLElement>(".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;
@@ -76,9 +240,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,
@@ -118,13 +289,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<FileCommentLineAnnotation[]>([]);
const [selectedRange, setSelectedRange] = useState<SelectedLineRange | null>(null);
const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
const selectedRange =
selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
const setSelectedRange = useCallback(
(range: SelectedLineRange | null) => {
setSelectionOverride({ revealRequestId, range });
},
[revealRequestId],
);
const surfaceRef = useRef<HTMLDivElement>(null);
const selectionFrameRef = useRef<number | null>(null);
const saveCoordinator = useFileSaveCoordinator({
environmentId,
cwd,
@@ -182,7 +364,7 @@ function EditableFileSurface({
});
});
},
[composerDraftTarget, removeReviewComment],
[composerDraftTarget, removeReviewComment, setSelectedRange],
);
const submitAnnotationEntry = useCallback(
@@ -217,7 +399,14 @@ function EditableFileSurface({
})),
);
},
[addReviewComment, composerDraftTarget, contents, lineAnnotations, relativePath],
[
addReviewComment,
composerDraftTarget,
contents,
lineAnnotations,
relativePath,
setSelectedRange,
],
);
const beginComment = useCallback((range: SelectedLineRange) => {
@@ -268,7 +457,7 @@ function EditableFileSurface({
isBlocked: () => hasOpenCommentForm,
onDismiss: () => setSelectedRange(null),
});
}, [editor, hasOpenCommentForm]);
}, [editor, hasOpenCommentForm, setSelectedRange]);
const handleLineSelectionEnd = useCallback(
(range: SelectedLineRange | null) => {
setSelectedRange(range);
@@ -276,7 +465,26 @@ function EditableFileSurface({
beginComment(range);
}
},
[beginComment],
[beginComment, setSelectedRange],
);
const handlePostRender = useCallback<FilePostRender>(
(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 (
@@ -305,6 +513,8 @@ function EditableFileSurface({
overflow: "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme,
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
onPostRender: handlePostRender,
}}
selectedLines={selectedRange}
lineAnnotations={lineAnnotations}
@@ -339,7 +549,10 @@ function RenderedMarkdownSurface({
contents,
threadRef,
onPendingChange,
}: Omit<EditableFileSurfaceProps, "resolvedTheme" | "composerDraftTarget"> & {
}: Omit<
EditableFileSurfaceProps,
"resolvedTheme" | "composerDraftTarget" | "revealLine" | "revealRequestId" | "onPostRender"
> & {
threadRef: ScopedThreadRef;
}) {
const saveCoordinator = useFileSaveCoordinator({
@@ -387,6 +600,8 @@ export default function FilePreviewPanel({
composerDraftTarget,
keybindings,
availableEditors,
revealLine,
revealRequestId,
onOpenFile,
onPendingChange,
}: FilePreviewPanelProps) {
@@ -397,10 +612,16 @@ export default function FilePreviewPanel({
const { open: openPreview } = usePreviewActions();
const file = useProjectFileQuery(environmentId, cwd, relativePath);
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
const [renderedMarkdownPath, setRenderedMarkdownPath] = useState<string | null>(null);
const [markdownView, setMarkdownView] = useState<{
path: string | null;
revealRequestId: number | null;
}>({ path: null, revealRequestId: null });
const breadcrumbRef = useRef<HTMLDivElement>(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;
@@ -408,6 +629,7 @@ export default function FilePreviewPanel({
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
[projectName, relativePath],
);
const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
useEffect(() => {
const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(
@@ -498,9 +720,12 @@ export default function FilePreviewPanel({
<Toggle
className="shrink-0"
pressed={renderMarkdown}
onPressedChange={(pressed) =>
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"
@@ -604,6 +829,8 @@ export default function FilePreviewPanel({
overflow: "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme,
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
onPostRender: onFilePostRender,
}}
className="min-h-full"
/>
@@ -617,6 +844,8 @@ export default function FilePreviewPanel({
composerDraftTarget={composerDraftTarget}
contents={file.data.contents}
resolvedTheme={resolvedTheme}
revealRequestId={revealRequestId}
onPostRender={onFilePostRender}
onPendingChange={onPendingChange}
/>
)
+88 -3
View File
@@ -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,
},
],
});
});
+54 -8
View File
@@ -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<string, ThreadRightPanelState>;
open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => 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<string, ThreadRightPanelState>;
} {
@@ -153,6 +170,20 @@ export function migratePersistedRightPanelState(persistedState: unknown): {
threadState && typeof threadState === "object" ? threadState : null;
const surfaces = Array.isArray(validThreadState?.surfaces)
? validThreadState.surfaces.flatMap<RightPanelSurface>((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<RightPanelStoreState>()(
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<RightPanelSurface, { kind: "file" }> =>
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) =>