fix(webui): reuse preview tabs for resolved file aliases

This commit is contained in:
Xubin Ren committed 2026-10-18 00:14:36 +08:00
1 parent 0869c928a2
commit 61666c495a
5 files changed
+95 -4

No files matched your search

+7 -1
View File
@@ -10,6 +10,7 @@ interface FilePreviewPanelProps {
loadPreview?: (path: string) => Promise<FilePreviewPayload>;
initialPreview?: FilePreviewPayload;
onOpenFilePreview?: (path: string) => void;
onResolvePath?: (path: string, canonicalPath: string) => void;
}
export function FilePreviewPanel({
@@ -19,6 +20,7 @@ export function FilePreviewPanel({
loadPreview,
initialPreview,
onOpenFilePreview,
onResolvePath,
}: FilePreviewPanelProps) {
const [state, setState] = useState<FilePreviewPanelState>(() => initialPreview
? { status: "ready", payload: initialPreview } : { status: "loading" });
@@ -30,6 +32,8 @@ export function FilePreviewPanel({
// when a session/path/loader change actually starts another request.
const tokenRef = useRef(token);
tokenRef.current = token;
const onResolvePathRef = useRef(onResolvePath);
onResolvePathRef.current = onResolvePath;
useEffect(() => {
let cancelled = false;
@@ -40,8 +44,10 @@ export function FilePreviewPanel({
: (previous.status === "loading" ? previous : { status: "loading" }));
(loadPreview?.(path) ?? fetchFilePreview(tokenRef.current, sessionKey, path))
.then((payload) => {
if (!cancelled) setState(previous => previous.status === "ready" && previous.payload === payload
if (cancelled) return;
setState(previous => previous.status === "ready" && previous.payload === payload
? previous : { status: "ready", payload });
onResolvePathRef.current?.(path, payload.path);
})
.catch((error: unknown) => {
if (!cancelled) setState({ status: "error",
+2 -1
View File
@@ -843,7 +843,7 @@ export function ThreadShell({
} | null>(null);
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
const { state: previewState, openFile, openWeb, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
const { state: previewState, openFile, resolveFile, openWeb, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
useFilePreviewState(previewSessionKey, filePreviewStore);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
@@ -2135,6 +2135,7 @@ export function ThreadShell({
loadPreview={filePreviews.load}
initialPreview={filePreviews.peek(activePreview.value)}
onOpenFilePreview={openFilePreview}
onResolvePath={resolveFile}
/>
) : <WebPreviewPanel key={activePreview.id} url={activePreview.value} />}
</PreviewPane>
+20 -1
View File
@@ -4,6 +4,7 @@ export interface PreviewTab {
id: string;
kind: "file" | "web";
value: string;
canonicalPath?: string;
}
export interface FilePreviewState {
@@ -44,6 +45,21 @@ export class FilePreviewStore {
this.update(key, { tabs, activeId: id });
}
/** Reconcile aliases only after the gateway has resolved and authorized the file. */
resolveFile(key: string, path: string, canonicalPath: string) {
const previous = this.get(key);
const id = `file:${path}`;
const current = previous.tabs.find(tab => tab.id === id);
if (!current || current.canonicalPath === canonicalPath) return;
const existing = previous.tabs.find(tab => tab.id !== id && tab.kind === "file"
&& tab.canonicalPath === canonicalPath);
const tabs = existing
? previous.tabs.filter(tab => tab.id !== id)
: previous.tabs.map(tab => tab.id === id ? { ...tab, canonicalPath } : tab);
this.update(key, { tabs,
activeId: existing && previous.activeId === id ? existing.id : previous.activeId });
}
select(key: string, id: string) {
if (this.get(key).tabs.some((tab) => tab.id === id)) this.update(key, { activeId: id });
}
@@ -80,6 +96,9 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie
const openFile = useCallback((path: string) => {
if (key) store.open(key, "file", path);
}, [key, store]);
const resolveFile = useCallback((path: string, canonicalPath: string) => {
if (key) store.resolveFile(key, path, canonicalPath);
}, [key, store]);
const setWidth = useCallback((width: number) => {
if (key) store.update(key, { width });
}, [key, store]);
@@ -95,5 +114,5 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie
const close = useCallback(() => {
if (key) store.close(key);
}, [key, store]);
return { state, openFile, openWeb, selectTab, closeTab, close, setWidth };
return { state, openFile, resolveFile, openWeb, selectTab, closeTab, close, setWidth };
}
+45 -1
View File
@@ -3,8 +3,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { CodeBlock } from "@/components/CodeBlock";
import { PreviewPane } from "@/components/PreviewPane";
import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewState";
import { setAppLanguage } from "@/i18n";
import { fetchFilePreview } from "@/lib/api";
import { createFilePreviewResource } from "@/lib/file-preview-resource";
vi.mock("@/components/CodeBlock", () => ({
CodeBlock: vi.fn(({
@@ -56,6 +59,7 @@ describe("FilePreviewPanel", () => {
});
it("ignores a late response after changing session", async () => {
const resolvePath = vi.fn();
let resolveFirst!: (payload: import("@/lib/types").FilePreviewPayload) => void;
vi.mocked(fetchFilePreview).mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }));
const payload = {
@@ -63,12 +67,52 @@ describe("FilePreviewPanel", () => {
language: "text", content: "session B", truncated: false, size: 9,
};
vi.mocked(fetchFilePreview).mockResolvedValueOnce(payload);
const view = (key: string) => <FilePreviewPanel key={key} sessionKey={key} path="notes.txt" token="test" />;
const view = (key: string) => <FilePreviewPanel key={key} sessionKey={key} path="notes.txt" token="test" onResolvePath={resolvePath} />;
const { rerender } = render(view("a"));
rerender(view("b"));
await screen.findByText("session B");
await act(async () => resolveFirst({ ...payload, content: "session A" }));
expect(screen.queryByText("session A")).not.toBeInTheDocument();
expect(resolvePath).toHaveBeenCalledOnce();
expect(resolvePath).toHaveBeenCalledWith("notes.txt", "/workspace/b.txt");
});
it("opens, follows a relative link and returns to one report tab with working source controls", async () => {
const report = "# Report\n\n[Details](./details.md)\n";
vi.mocked(fetchFilePreview).mockImplementation(async (_token, _session, path) => {
const details = path.endsWith("details.md");
const name = details ? "details.md" : "REPORT.md";
return { path: `/workspace/reports/${name}`, display_path: `reports/${name}`,
language: "markdown", content: details ? "# Details\n\n[Return](./REPORT.md)\n" : report, truncated: false };
});
const store = new FilePreviewStore();
const resource = createFilePreviewResource(path => fetchFilePreview("test", "a", path));
store.open("a", "file", "reports/REPORT.md");
function View() {
const { state, openFile, resolveFile, selectTab, closeTab, close } = useFilePreviewState("a", store);
const active = state.tabs.find(tab => tab.id === state.activeId)!;
return <PreviewPane tabs={state.tabs} activeId={active.id} width={544} isClosing={false}
onSelect={selectTab} onCloseTab={closeTab} onClose={close} onResizeStart={() => {}}>
<FilePreviewPanel key={active.id} sessionKey="a" path={active.value} token="test"
loadPreview={resource.load} initialPreview={resource.peek(active.value)}
onOpenFilePreview={openFile} onResolvePath={resolveFile} />
</PreviewPane>;
}
render(<View />);
await screen.findByRole("heading", { name: "Report" });
fireEvent.click(screen.getByRole("button", { name: "/workspace/reports/./details.md" }));
await screen.findByRole("heading", { name: "Details" });
fireEvent.click(screen.getByRole("button", { name: "/workspace/reports/./REPORT.md" }));
await screen.findByRole("heading", { name: "Report" });
expect(screen.getAllByRole("tab", { name: "REPORT.md" })).toHaveLength(1);
expect(screen.getAllByRole("tab")).toHaveLength(2);
expect(screen.getByRole("tab", { name: "REPORT.md" })).toHaveAttribute("aria-selected", "true");
expect(fetchFilePreview).toHaveBeenCalledTimes(3);
fireEvent.click(screen.getByRole("button", { name: "Source" }));
expect(screen.getByTestId("mock-code-block").textContent).toBe(report);
fireEvent.click(screen.getByRole("button", { name: "Preview" }));
await screen.findByRole("heading", { name: "Report" });
expect(fetchFilePreview).toHaveBeenCalledTimes(3);
});
it("opens the sidebar image in the shared zoomable viewer and returns to the preview", async () => {
+21
View File
@@ -4,6 +4,27 @@ import { PreviewPane } from "@/components/PreviewPane";
import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewState";
describe("preview tabs", () => {
it("reuses a gateway-resolved file without merging same-named files or sessions", () => {
const store = new FilePreviewStore();
store.open("a", "file", "reports/REPORT.md");
store.resolveFile("a", "reports/REPORT.md", "/workspace/reports/REPORT.md");
store.open("a", "file", "/workspace/reports/./details.md");
store.resolveFile("a", "/workspace/reports/./details.md", "/workspace/reports/details.md");
store.update("a", { width: 620 });
store.open("a", "file", "/workspace/reports/./REPORT.md");
store.resolveFile("a", "/workspace/reports/./REPORT.md", "/workspace/reports/REPORT.md");
expect(store.get("a").tabs.map(tab => tab.value)).toEqual([
"reports/REPORT.md", "/workspace/reports/./details.md",
]);
expect(store.get("a")).toMatchObject({ activeId: "file:reports/REPORT.md", width: 620 });
store.open("a", "file", "archive/REPORT.md");
store.resolveFile("a", "archive/REPORT.md", "/workspace/archive/REPORT.md");
store.open("b", "file", "reports/REPORT.md");
store.resolveFile("b", "reports/REPORT.md", "/workspace/reports/REPORT.md");
expect(store.get("a").tabs).toHaveLength(3);
expect(store.get("b").tabs).toHaveLength(1);
});
it("deduplicates targets, keeps selection and width per session, and closes neighboring tabs", () => {
const store = new FilePreviewStore();
const storage = vi.spyOn(Storage.prototype, "setItem");