Improve inline panel, file preview, and MCP session handling (#3121)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-06-16 22:40:22 -07:00
1 parent 3a5ec9464b
commit b489ea52a8
7 files changed
+489 -30

No files matched your search

@@ -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();
+6 -2
View File
@@ -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}
+88 -4
View File
@@ -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<HTMLElement>(".file-preview-virtualizer"),
"Unable to find the virtualized file preview.",
const previousCodeVirtualizer = document.querySelector<HTMLElement>(
".file-preview-virtualizer",
);
useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts", 4_000);
const codeVirtualizer = await waitForElement(() => {
const current = document.querySelector<HTMLElement>(".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<HTMLElement>("diffs-container");
const targetLine = fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-line="4000"]');
const targetLineNumber = fileHost?.shadowRoot?.querySelector<HTMLElement>(
'[data-column-number="4000"]',
);
const previousLine =
fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-line="3999"]');
const previousLineNumber = fileHost?.shadowRoot?.querySelector<HTMLElement>(
'[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<HTMLElement>("diffs-container");
const targetLineNumber =
fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-column-number="4000"]') ?? null;
const previousLineNumber =
fileHost?.shadowRoot?.querySelector<HTMLElement>('[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<HTMLElement>("diffs-container");
const targetLine = fileHost?.shadowRoot?.querySelector<HTMLElement>('[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();
}
+4
View File
@@ -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}
/>
@@ -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<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;
@@ -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<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,
@@ -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<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 (
@@ -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<EditableFileSurfaceProps, "resolvedTheme" | "composerDraftTarget"> & {
}: 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<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;
@@ -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<HTMLElement>(
@@ -485,9 +707,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"
@@ -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}
/>
)
+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) =>