Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): preserve previews during credential renewal
Xubin Renc2edd5632e31
diff --git a/docs/webui.md b/docs/webui.mdindex bf30b8e54..abc1df3ad 100644--- a/docs/webui.md+++ b/docs/webui.md@@ -136,9 +136,26 @@ them with **View diff**. Large diffs may hide unchanged lines or truncate theinline preview. Select the filename in the activity row to open the read-onlyfile preview panel.-Use the **…** menu beside a file reference (or right-click it) to preview the file-and copy its absolute or project-relative path. The same menu is available in-the preview header. Keyboard users can focus a reference and press **Shift+F10**.+Files open as tabs in one preview pane. Select another file to add or switch a+tab without reopening the pane; close a tab with its **×**, or close the pane+with **Escape**. Tabs and width follow each session while the WebUI remains open.+They are kept only in memory and cleared when that session is deleted or the+connection ends. The pane overlays the conversation on narrow screens.++PNG, JPEG, GIF and WebP files can be previewed as images within the size limit.+Hover or focus an image file reference for a compact quick look, or select it+to open the pane. Select the preview image for the full-size viewer, which+supports zoom controls, pinch-to-zoom and panning. HTML and SVG files remain+read-only source previews rather than executable pages.++A plain image file link does not automatically insert a large image into the+reply. Explicit Markdown images appear inline; image attachments use a compact+gallery, showing at most four thumbnails before a count of the remaining images.+An image already displayed inline is not duplicated in the attachment gallery.++Select a file reference to preview it. Right-click the reference or its preview+tab to copy its absolute or project-relative path. Keyboard users can focus a+reference and press **Shift+F10**.Paths are resolved on the gateway machine, which may not be the computer runningyour browser. Files outside the project do not have a project-relative path.If a reference cannot be resolved, you can still copy the original reference;diff --git a/webui/src/components/FilePreviewPanel.tsx b/webui/src/components/FilePreviewPanel.tsxindex 16d2d3022..d963b583f 100644--- a/webui/src/components/FilePreviewPanel.tsx+++ b/webui/src/components/FilePreviewPanel.tsx@@ -35,13 +35,17 @@ export function FilePreviewPanel({// Cache aging must not restart an already open preview on unrelated rerenders.const initialPreviewRef = useRef(initialPreview);initialPreviewRef.current = initialPreview;+ // Credential renewal is not a new file selection. Read the current token only+ // when a session/path/loader change actually starts another request.+ const tokenRef = useRef(token);+ tokenRef.current = token;useEffect(() => {let cancelled = false;setImageOpen(false);const cached = initialPreviewRef.current;setState(cached ? { status: "ready", payload: cached } : { status: "loading" });- (loadPreview?.(path) ?? fetchFilePreview(token, sessionKey, path))+ (loadPreview?.(path) ?? fetchFilePreview(tokenRef.current, sessionKey, path)).then((payload) => {if (!cancelled) setState({ status: "ready", payload });})@@ -51,7 +55,7 @@ export function FilePreviewPanel({return () => {cancelled = true;};- }, [path, sessionKey, token, loadPreview]);+ }, [path, sessionKey, loadPreview]);const displayPath = state.status === "ready" ? state.payload.display_path : path;const { name } = splitFilePath(displayPath);diff --git a/webui/src/components/MarkdownTextRenderer.tsx b/webui/src/components/MarkdownTextRenderer.tsxindex 1d65c74f2..765c663ea 100644--- a/webui/src/components/MarkdownTextRenderer.tsx+++ b/webui/src/components/MarkdownTextRenderer.tsx@@ -453,6 +453,7 @@ function InlineLinkPreviewRow({ link }: { link: InlineLinkPreview }) {return (<WebLink+ layout="row"href={link.href}target="_blank"rel="noreferrer noopener"diff --git a/webui/src/components/WebLink.tsx b/webui/src/components/WebLink.tsxindex 74e869e13..f9a7daf5d 100644--- a/webui/src/components/WebLink.tsx+++ b/webui/src/components/WebLink.tsx@@ -5,10 +5,11 @@ import { useTranslation } from "react-i18next";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { copyTextToClipboard } from "@/lib/clipboard";import { parseWebLink } from "@/lib/web-preview";+import { cn } from "@/lib/utils";export const WebPreviewContext = createContext<((url: string) => void) | undefined>(undefined);-export function WebLink({ href = "", children, ...props }: ComponentPropsWithoutRef<"a">) {+export function WebLink({ href = "", children, layout = "inline", className, ...props }: ComponentPropsWithoutRef<"a"> & { layout?: "inline" | "row" }) {const { t } = useTranslation();const openPreview = useContext(WebPreviewContext);const [open, setOpen] = useState(false);@@ -19,7 +20,7 @@ export function WebLink({ href = "", children, ...props }: ComponentPropsWithoutreturn () => window.clearTimeout(timer);}, [feedback]);const url = parseWebLink(href);- const anchor = <a {...props} href={href} target="_blank" rel="noreferrer noopener">{children}</a>;+ const anchor = <a {...props} className={cn(className, layout === "row" && "min-w-0 flex-1")} href={href} target="_blank" rel="noreferrer noopener">{children}</a>;if (!url) {// Keep the renderer's relative media/document and mail links unchanged.const relative = !/^[a-z][a-z\d+.-]*:/i.test(href)@@ -28,7 +29,7 @@ export function WebLink({ href = "", children, ...props }: ComponentPropsWithout}return (<DropdownMenu open={open} onOpenChange={setOpen}>- <span className="inline max-w-full" onContextMenu={(event) => {+ <span className={cn("max-w-full", layout === "row" ? "inline-flex w-full min-w-0 items-center" : "inline")} onContextMenu={(event) => {event.preventDefault(); event.stopPropagation(); setOpen(true);}} onKeyDown={(event) => {if ((event.shiftKey && event.key === "F10") || event.key === "ContextMenu") {@@ -38,7 +39,7 @@ export function WebLink({ href = "", children, ...props }: ComponentPropsWithout{anchor}<DropdownMenuTrigger asChild><button type="button" aria-label={t("webPreview.actions")} title={t("webPreview.actions")}- className="ml-0.5 inline-flex h-6 w-6 items-center justify-center rounded-md align-middle text-muted-foreground/70 hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ className="ml-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md align-middle text-muted-foreground/70 hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><MoreHorizontal className="h-3.5 w-3.5" aria-hidden /></button></DropdownMenuTrigger>diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsxindex 7ae5e57b6..36c3e5548 100644--- a/webui/src/components/thread/ThreadShell.tsx+++ b/webui/src/components/thread/ThreadShell.tsx@@ -1556,7 +1556,7 @@ export function ThreadShell({if (!previewSessionKey) return Promise.reject(new Error("No active session"));return temporary ? loadTemporaryFilePreview(path) : fetchFilePreview(getToken(), previewSessionKey, path);}, [previewSessionKey, temporary, loadTemporaryFilePreview, getToken]);- const filePreviews = useMemo(() => createFilePreviewResource(loadFilePreview), [loadFilePreview, token]);+ const filePreviews = useMemo(() => createFilePreviewResource(loadFilePreview), [loadFilePreview]);const fileActions = useMemo(() => ({resolveMetadata: resolveFileMetadata,loadPreview: filePreviews.load,diff --git a/webui/src/tests/file-preview-panel.test.tsx b/webui/src/tests/file-preview-panel.test.tsxindex 78f5660fd..00974edc5 100644--- a/webui/src/tests/file-preview-panel.test.tsx+++ b/webui/src/tests/file-preview-panel.test.tsx@@ -165,4 +165,23 @@ describe("FilePreviewPanel", () => {expect(fetchFilePreview).toHaveBeenCalledTimes(1);});++ it("preserves the open image and zoom on token renewal, using the current token for the next file", async () => {+ vi.mocked(fetchFilePreview).mockResolvedValue({+ kind: "image", path: "/workspace/chart.png", display_path: "chart.png",+ size: 42, mime_type: "image/png", data_url: "data:image/png;base64,example",+ });+ const view = (token: string, path = "chart.png") =>+ <FilePreviewPanel sessionKey="websocket:a" path={path} token={token} />;+ const { rerender } = render(view("old"));+ fireEvent.click(await screen.findByRole("button", { name: "View image: chart.png" }));+ const dialog = screen.getByRole("dialog");+ fireEvent.click(within(dialog).getByRole("button", { name: "Zoom in" }));+ rerender(view("renewed"));+ expect(fetchFilePreview).toHaveBeenCalledTimes(1);+ expect(screen.getByRole("dialog")).toBe(dialog);+ expect(within(dialog).getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");+ rerender(view("renewed", "second.png"));+ await waitFor(() => expect(fetchFilePreview).toHaveBeenLastCalledWith("renewed", "websocket:a", "second.png"));+ });});diff --git a/webui/src/tests/temporary-chat-navigation.test.tsx b/webui/src/tests/temporary-chat-navigation.test.tsxindex b472dff9c..cae831834 100644--- a/webui/src/tests/temporary-chat-navigation.test.tsx+++ b/webui/src/tests/temporary-chat-navigation.test.tsx@@ -5,6 +5,7 @@ import App from "@/App";import { ThreadMessageCache } from "@/lib/thread-message-cache";import { FilePreviewStore } from "@/hooks/useFilePreviewState";import type { InboundEvent, Outbound } from "@/lib/types";+import { fetchBootstrap } from "@/lib/bootstrap";import { canonicalThreadPayload } from "./thread-test-payload";let groupedTopics = false;@@ -16,7 +17,7 @@ const previewFile = (path: string) => ({vi.mock("@/lib/bootstrap", async (importOriginal) => ({...await importOriginal<typeof import("@/lib/bootstrap")>(),- fetchBootstrap: async () => ({ token: "test", api_token: "test", ws_path: "/" }),+ fetchBootstrap: vi.fn(async () => ({ token: "test", api_token: "test", ws_path: "/" })),deriveWsUrl: () => "ws://test",}));@@ -95,6 +96,7 @@ async function selectTopic(name: string) {describe("temporary chat navigation", () => {beforeEach(() => {+ vi.mocked(fetchBootstrap).mockReset().mockResolvedValue({ token: "test", api_token: "test", ws_path: "/" });groupedTopics = false;withFiles = false;localStorage.clear();@@ -145,6 +147,30 @@ describe("temporary chat navigation", () => {vi.unstubAllGlobals();});+ it("keeps the preview resource stable across bootstrap token refresh", async () => {+ withFiles = true;+ vi.useFakeTimers({ shouldAdvanceTime: true });+ vi.mocked(fetchBootstrap)+ .mockResolvedValueOnce({ token: "old", api_token: "old", ws_path: "/", expires_in: 30 })+ .mockResolvedValue({ token: "renewed", api_token: "renewed", ws_path: "/", expires_in: 300 });+ render(<App />);+ await screen.findByRole("button", { name: "Temporary chat" });+ act(() => TestSocket.current.open());+ await selectTopic("Regular topic");+ fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));+ const content = await screen.findByText("Preview of notes.txt");+ const fullPreviewRequests = () => vi.mocked(fetch).mock.calls.filter(([url]) =>+ String(url).includes("/file-preview?path=") && !String(url).includes("probe=") && !String(url).includes("metadata="));+ expect(fullPreviewRequests()).toHaveLength(1);+ await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });+ expect(fetchBootstrap).toHaveBeenCalledTimes(2);+ expect(screen.getByText("Preview of notes.txt")).toBe(content);+ expect(fullPreviewRequests()).toHaveLength(1);+ fireEvent.click(screen.getByRole("button", { name: "second.txt" }));+ await screen.findByText("Preview of second.txt");+ expect(new Headers(fullPreviewRequests().at(-1)?.[1]?.headers).get("Authorization")).toBe("Bearer renewed");+ });+it.each([false, true])("restores file previews after pane navigation (temporary=%s)", async (temporary) => {withFiles = true;groupedTopics = true;diff --git a/webui/src/tests/web-preview.test.tsx b/webui/src/tests/web-preview.test.tsxindex 47033f92d..9f986c246 100644--- a/webui/src/tests/web-preview.test.tsx+++ b/webui/src/tests/web-preview.test.tsx@@ -76,6 +76,16 @@ describe("web preview boundaries", () => {});describe("web link actions", () => {+ it("reserves room for actions beside a full-width link row without changing inline links", () => {+ const { rerender } = render(<WebLink layout="row" href="https://example.com/">Long website title</WebLink>);+ const link = screen.getByRole("link", { name: "Long website title" });+ expect(link.parentElement).toHaveClass("inline-flex", "w-full");+ expect(link).toHaveClass("min-w-0", "flex-1");+ expect(screen.getByRole("button", { name: "Link actions" })).toHaveClass("shrink-0");+ rerender(<WebLink href="https://example.com/">Long website title</WebLink>);+ expect(link.parentElement).toHaveClass("inline");+ expect(link).not.toHaveClass("flex-1");+ });it("opens a shared right-click menu without loading any website beforehand", async () => {const open = vi.fn();const { container } = render(<WebPreviewContext.Provider value={open}><WebLink href="https://example.com/?a=b#c">Example</WebLink></WebPreviewContext.Provider>);