Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Attachments: open beside the conversation on wide windows
Yash Kakade94837949be28
diff --git a/src/App.tsx b/src/App.tsxindex e0f0f680ce..7b3ae2b542 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -88,6 +88,7 @@ import { useSessionEnded } from "@/lib/session-ended";import { PairPage } from "./pair/PairPage";import { WebPanelPage } from "@/components/WebPanelPage";import { AppPreviewPanel } from "@/components/published-apps/AppPreviewPanel";+import { FilePreviewPanel } from "@/components/FilePreviewPanel";import { refreshPublishedApps } from "@/lib/own-published-apps";function Shell({ viewer }: { viewer: WelcomeViewer | null }) {@@ -453,6 +454,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {))}<AppPreviewPanel />+ <FilePreviewPanel threadId={group?.threadId ?? bot?.threadId} />{state.forkPanel && sidebarInline && <ForkPanel />}{!state.forkPanel && roomPanelOpen && group && (<RoomPanel key={`room:${group.id}`} group={group} overlay={notificationFeed && state.notificationsOpen && !twoSidePanelsFit} />diff --git a/src/components/FilePreviewPanel.dom.test.ts b/src/components/FilePreviewPanel.dom.test.tsnew file mode 100644index 0000000000..53a3d87254--- /dev/null+++ b/src/components/FilePreviewPanel.dom.test.ts@@ -0,0 +1,126 @@+// @vitest-environment happy-dom+import { act, createElement, Fragment } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({+ state: { computerOpen: false, settingsOpen: false, inspectorOpen: false, activityOpen: false, activeView: "chat" },+ dispatched: [] as unknown[],+ wide: true,+}));+vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), useStore: () => ({ state: fixture.state, dispatch: () => {} }) }));+vi.mock("@/state/store-ref", () => ({ useOptionalStoreRef: () => ({ dispatch: (action: unknown) => fixture.dispatched.push(action), state: () => fixture.state }) }));++const { closeFilePreview } = await import("@/lib/file-preview");+const { openAppPreview, closeAppPreview } = await import("@/lib/app-preview");+const { AttachedFileChip } = await import("./AttachmentPreview");+const { FilePreviewPanel } = await import("./FilePreviewPanel");+// The preview loads this lazily; loaded once here, the tests wait only on the file.+await import("./MarkdownFilePreview");++const PLAN = { path: "/workspace/observing-plan.md", name: "observing-plan.md", private: true };+const message = { threadId: "t1", messageId: "m1" };+let host: HTMLDivElement, root: Root;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.stubGlobal("matchMedia", (query: string) => ({ matches: fixture.wide && query === "(min-width: 1280px)", addEventListener() {}, removeEventListener() {} }));+ vi.stubGlobal("fetch", vi.fn(async () => new Response("# Observing plan\n\nBring a red flashlight.")));+ fixture.state = { computerOpen: false, settingsOpen: false, inspectorOpen: false, activityOpen: false, activeView: "chat" };+ fixture.dispatched.length = 0;+ fixture.wide = true;+ host = document.createElement("div"); document.body.append(host); root = createRoot(host);+});+afterEach(async () => {+ await act(async () => { closeFilePreview(); closeAppPreview(); root.unmount(); });+ host.remove();+ vi.unstubAllGlobals();+});++/** A conversation with one Markdown file in a reply, and the shell's pane beside it; `inPanel` draws the chip in a+ * side panel instead. */+async function render({ threadId = "t1", inPanel = false } = {}) {+ const chip = createElement(AttachedFileChip, { file: PLAN, message });+ await act(async () => root.render(createElement(Fragment, null,+ createElement("main", { "data-look": "chat" }, inPanel ? createElement("aside", null, chip) : chip, createElement("textarea", { "aria-label": "Message" })),+ createElement(FilePreviewPanel, { threadId }),+ )));+}+const nameButton = () => host.querySelector<HTMLButtonElement>("main button[aria-label='Preview: observing-plan.md']")!;+async function openFile() {+ await act(async () => nameButton().click());+ await vi.waitFor(() => expect(document.body.textContent).toContain("Bring a red flashlight."));+}+const pane = () => host.querySelector<HTMLElement>("aside[data-file-preview]");+const dialog = () => document.body.querySelector("dialog");++describe("a file opened from the chat on a wide window", () => {+ it("opens beside the conversation, which stays on screen and usable", async () => {+ await render();+ await openFile();+ expect(pane()?.getAttribute("data-file-preview")).toBe(PLAN.path);+ expect(pane()?.querySelector("h2")?.textContent).toBe("observing-plan.md");+ expect(pane()?.textContent).toContain("Bring a red flashlight.");+ expect(dialog()).toBeNull();+ expect(host.querySelector("main textarea")).not.toBeNull();+ expect(nameButton()).not.toBeNull();+ expect(fixture.dispatched).toContainEqual({ type: "toggleComputer", open: false });+ });++ it("keeps Save as its own button next to the name, and in the pane", async () => {+ await render();+ await openFile();+ expect(host.querySelector("main button[aria-label='Save a copy of observing-plan.md']")).not.toBeNull();+ expect(pane()?.querySelector("button[aria-label='Save a copy of observing-plan.md']")).not.toBeNull();+ });++ it("closes from its button and gives focus back to the file without scrolling the chat", async () => {+ await render();+ await openFile();+ const focus = vi.spyOn(nameButton(), "focus");+ await act(async () => pane()!.querySelector<HTMLButtonElement>("button[aria-label='Close preview']")!.click());+ expect(pane()).toBeNull();+ expect(focus).toHaveBeenCalledWith({ preventScroll: true });+ });++ it("closes on Escape", async () => {+ await render();+ await openFile();+ await act(async () => { pane()!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });+ expect(pane()).toBeNull();+ });++ it("closes when the chat moves to another conversation", async () => {+ await render();+ await openFile();+ await render({ threadId: "t2" });+ expect(pane()).toBeNull();+ });++ it("gives way to another panel on that side", async () => {+ await render();+ await openFile();+ await act(async () => openAppPreview({ url: "https://bright-bakery.netlify.app/", title: "Bright Bakery" }));+ expect(pane()).toBeNull();+ await act(async () => closeAppPreview());+ expect(pane()).toBeNull();+ });+});++describe("a file that keeps the dialog", () => {+ it("opens in the dialog on a narrow window", async () => {+ fixture.wide = false;+ await render();+ await openFile();+ expect(pane()).toBeNull();+ expect(dialog()?.textContent).toContain("Bring a red flashlight.");+ });++ it("opens in the dialog from a side panel", async () => {+ await render({ inPanel: true });+ await openFile();+ expect(pane()).toBeNull();+ expect(dialog()?.textContent).toContain("Bring a red flashlight.");+ expect(fixture.dispatched).toEqual([]);+ });+});diff --git a/src/components/FilePreviewPanel.tsx b/src/components/FilePreviewPanel.tsxnew file mode 100644index 0000000000..16ac215138--- /dev/null+++ b/src/components/FilePreviewPanel.tsx@@ -0,0 +1,77 @@+import { useEffect, useRef, useState } from "react";+import { X } from "lucide-react";++import { useCaptionChrome } from "@/components/DesktopCapabilities";+import { useAppPreview } from "@/lib/app-preview";+import { cn } from "@/lib/cn";+import { closeFilePreview, useFilePreview, type FilePreview } from "@/lib/file-preview";+import { t } from "@/lib/i18n";+import { useRoomPanel } from "@/lib/room-panel";+import { useStore } from "@/state/store";+import { PANEL_MIN_WIDTH, useComputerPanelResize } from "./computer-panel-resize";+import { FilePreviewContent } from "./HtmlFilePreview";++/** A file from a message, beside the conversation where the Computer panel sits, so the transcript and the message box+ * stay in reach while it is open. It gives way when another panel takes that side, and closes when the chat changes. */+export function FilePreviewPanel({ threadId }: { threadId: string | undefined }) {+ const preview = useFilePreview();+ const appPreview = useAppPreview();+ const roomPanel = useRoomPanel();+ const { state } = useStore();+ const otherPanel = state.computerOpen || state.settingsOpen || state.inspectorOpen || state.activityOpen || appPreview !== null || roomPanel !== null;+ const hadOtherPanel = useRef(otherPanel);+ useEffect(() => {+ if (otherPanel && !hadOtherPanel.current) closeFilePreview();+ hadOtherPanel.current = otherPanel;+ }, [otherPanel]);+ useEffect(() => closeFilePreview, [threadId]);+ if (!preview || otherPanel || state.activeView !== "chat") return null;+ return <FilePane key={`${preview.message.threadId}:${preview.message.messageId}:${preview.path}`} preview={preview} />;+}++function FilePane({ preview }: { preview: FilePreview }) {+ const { dragProps } = useCaptionChrome();+ const { panelWidth, maxWidth, separatorRef, separatorWidth, onSeparatorKeyDown, onResizeStart, onResizeMove, onResizeEnd } = useComputerPanelResize();+ const closeButton = useRef<HTMLButtonElement>(null);+ const [dragging, setDragging] = useState(false);+ useEffect(() => closeButton.current?.focus({ preventScroll: true }), []);+ // Taking focus back must not scroll the transcript away from where the person left it.+ const dismiss = () => {+ closeFilePreview();+ if (preview.opener?.isConnected) preview.opener.focus({ preventScroll: true });+ };+ return (+ <aside aria-label={t("attach.besideAria", { name: preview.name })} data-file-preview={preview.path} style={{ width: panelWidth }}+ onKeyDown={(event) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ event.stopPropagation();+ dismiss();+ }}+ className="animate-panel-in relative flex h-full shrink-0 flex-col border-s border-hairline/40 bg-panel motion-reduce:animate-none max-md:absolute max-md:inset-0 max-md:z-40 max-md:w-full!">+ <div+ ref={separatorRef}+ role="separator"+ aria-orientation="vertical"+ aria-label={t("computer.resizeAria")}+ aria-valuemin={PANEL_MIN_WIDTH}+ aria-valuemax={maxWidth}+ aria-valuenow={separatorWidth ?? undefined}+ tabIndex={0}+ onKeyDown={onSeparatorKeyDown}+ onPointerDown={(event) => { setDragging(true); onResizeStart(event); }}+ onPointerMove={onResizeMove}+ onPointerUp={(event) => { setDragging(false); onResizeEnd(event); }}+ onPointerCancel={(event) => { setDragging(false); onResizeEnd(event); }}+ className="absolute inset-y-0 start-0 z-10 w-1.5 cursor-col-resize hover:bg-accent/40 focus-visible:bg-accent/60 max-md:hidden"+ />+ <header {...dragProps} className="ms-1.5 flex items-center gap-1 py-2.5 ps-2.5 pe-3">+ <h2 dir="auto" title={preview.name} className="min-w-0 flex-1 truncate text-[17px] font-semibold text-ink">{preview.name}</h2>+ <button ref={closeButton} type="button" className="ui-icon-button shrink-0" aria-label={t("attach.besideClose")} title={t("attach.besideClose")} onClick={dismiss}><X size={16} /></button>+ </header>+ {/* An HTML file's frame swallows the pointer, so the resize drag would stop the moment it crossed the page. */}+ <div className={cn("ms-1.5 flex min-h-0 flex-1 flex-col overflow-auto px-3 pb-3", dragging && "pointer-events-none")}>+ <FilePreviewContent kind={preview.kind} path={preview.path} name={preview.name} message={preview.message} fill />+ </div>+ </aside>+ );+}diff --git a/src/components/HtmlFilePreview.tsx b/src/components/HtmlFilePreview.tsxindex de54cb40b1..18378bc08d 100644--- a/src/components/HtmlFilePreview.tsx+++ b/src/components/HtmlFilePreview.tsx@@ -2,8 +2,11 @@ import { Component, lazy, Suspense, useEffect, useRef, useState, type ReactNodeimport { Check, Code2, Download, ExternalLink, Eye, LoaderCircle, RotateCcw } from "lucide-react";import { requestMessageFile, useLocalFileSave, type MessageAttachmentContext } from "./AttachmentPreview";import { TableDialog } from "./RichTable";-import { readTableResponse } from "./TableFilePreview";+import { readTableResponse, TableFileContent } from "./TableFilePreview";+import { cn } from "@/lib/cn";+import { useFileBesideChat, type FilePreview } from "@/lib/file-preview";import { t } from "@/lib/i18n";+import { tableDelimiter } from "@/lib/table-data";export const HTML_PREVIEW_MAX_BYTES = 2 * 1024 * 1024;@@ -47,31 +50,42 @@ export function htmlBrowserBridge(): ((source: string, name: string) => Promise<return ogb?.remoteClient?.active ? undefined : ogb?.openHtmlInBrowser;}-/** The preview dialog for an HTML or Markdown file in a message, opened by the eye button or by the file's name. */+/** The preview for an HTML or Markdown file in a message, opened by the eye button or by the file's name: beside the chat+ * when the window has room for it, else in a dialog. */export function useHtmlPreview(path: string, name: string, message?: MessageAttachmentContext) {const [open, setOpen] = useState(false);const opener = useRef<HTMLElement | null>(null);+ const beside = useFileBesideChat();const kind = message === undefined ? null: isHtmlFile(name) || isHtmlFile(path) ? "html": isMarkdownFile(name) || isMarkdownFile(path) ? "markdown" : null;- const key = message ? `${message.threadId}:${message.messageId}:${path}` : "";return {opens: kind !== null,label: t(kind === "markdown" ? "markdown.preview" : "html.preview", { name }),show: (event: { currentTarget: HTMLElement }) => {opener.current = event.currentTarget;+ if (kind && message && beside({ kind, path, name, message, opener: event.currentTarget })) return;setOpen(true);},dialog: kind && open && message? <TableDialog title={name} returnFocus={opener.current} onClose={() => setOpen(false)}>- {kind === "html"- ? <HtmlFileContent key={key} path={path} name={name} message={message} />- : <MarkdownPreviewBoundary><Suspense fallback={<div role="status" className="flex items-center justify-center gap-2 p-12 text-sm text-ink-secondary"><LoaderCircle size={16} className="animate-spin" />{t("markdown.loading")}</div>}><MarkdownFileContent key={key} path={path} name={name} message={message} /></Suspense></MarkdownPreviewBoundary>}+ <FilePreviewContent kind={kind} path={path} name={name} message={message} /></TableDialog>: null,};}+/** A file's preview, in the dialog or in the pane beside the chat, which it fills. */+export function FilePreviewContent({ kind, path, name, message, fill = false }: Pick<FilePreview, "kind" | "path" | "name" | "message"> & { fill?: boolean }) {+ const key = `${message.threadId}:${message.messageId}:${path}`;+ if (kind === "html") return <HtmlFileContent key={key} path={path} name={name} message={message} fill={fill} />;+ if (kind === "table") {+ const delimiter = tableDelimiter(name) ?? tableDelimiter(path);+ return delimiter && <TableFileContent key={key} path={path} name={name} message={message} delimiter={delimiter} />;+ }+ return <MarkdownPreviewBoundary><Suspense fallback={<div role="status" className="flex items-center justify-center gap-2 p-12 text-sm text-ink-secondary"><LoaderCircle size={16} className="animate-spin" />{t("markdown.loading")}</div>}><MarkdownFileContent key={key} path={path} name={name} message={message} fill={fill} /></Suspense></MarkdownPreviewBoundary>;+}+export function HtmlFileButton({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {const preview = useHtmlPreview(path, name, message);return <>@@ -114,7 +128,7 @@ export function OpenInBrowserButton({ source, name, onError }: { source: string;}}><ExternalLink size={14} /></button>;}-function HtmlFileContent({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {+function HtmlFileContent({ path, name, message, fill }: { path: string; name: string; message: MessageAttachmentContext; fill: boolean }) {const [attempt, setAttempt] = useState(0);const [source, setSource] = useState<string | null>(null);const [error, setError] = useState<"size" | "load" | { reason: string } | null>(null);@@ -143,7 +157,7 @@ function HtmlFileContent({ path, name, message }: { path: string; name: string;}, [path, message.threadId, message.messageId, attempt]);if (error) return <div className="p-8 text-center text-sm"><p role="alert" className="mb-3 text-ink-secondary">{typeof error === "object" ? t("html.refused", { reason: error.reason }) : t(error === "size" ? "html.tooLarge" : "html.loadFailed")}</p><button type="button" className="rounded-lg border border-hairline px-3 py-2 hover:bg-raised" onClick={() => setAttempt(attempt + 1)}>{t("chat.retry")}</button></div>;if (source === null) return <div role="status" className="flex items-center justify-center gap-2 p-12 text-sm text-ink-secondary"><LoaderCircle size={16} className="animate-spin" />{t("html.loading")}</div>;- return <div className="flex flex-col gap-2">+ return <div className={cn("flex flex-col gap-2", fill && "min-h-0 flex-1")}><div className="flex items-center justify-end gap-1"><button type="button" className="table-action" aria-pressed={showSource} aria-label={t(showSource ? "html.rendered" : "html.source")} title={t(showSource ? "html.rendered" : "html.source")} onClick={() => setShowSource(!showSource)}>{showSource ? <Eye size={14} /> : <Code2 size={14} />}</button><button type="button" className="table-action" aria-label={t("html.reload")} title={t("html.reload")} onClick={() => setAttempt(attempt + 1)}><RotateCcw size={14} /></button>@@ -153,11 +167,14 @@ function HtmlFileContent({ path, name, message }: { path: string; name: string;{save.state === "failed" && <p role="alert" className="text-end text-[12px] text-danger">{save.reason}</p>}{openFailed && <p role="alert" className="text-end text-[12px] text-danger">{openFailed}</p>}{showSource- ? <pre className="h-[72dvh] overflow-auto rounded-lg border border-hairline/40 bg-inset p-3 text-[12px] leading-5 whitespace-pre-wrap break-words text-ink">{source}</pre>- : <HtmlPreviewFrame source={source} name={name} />}+ ? <pre className={cn(previewHeight(fill), "overflow-auto rounded-lg border border-hairline/40 bg-inset p-3 text-[12px] leading-5 whitespace-pre-wrap break-words text-ink")}>{source}</pre>+ : <HtmlPreviewFrame source={source} name={name} fill={fill} />}</div>;}-export function HtmlPreviewFrame({ source, name }: { source: string; name: string }) {- return <iframe sandbox="" referrerPolicy="no-referrer" srcDoc={htmlPreviewDocument(source)} title={t("html.frameTitle", { name })} className="h-[72dvh] w-full rounded-lg border border-hairline/40 bg-white" />;+/** A dialog's file view has a fixed height; the pane beside the chat gives its view the room under the toolbar. */+export const previewHeight = (fill = false) => fill ? "min-h-0 flex-1" : "h-[72dvh]";++export function HtmlPreviewFrame({ source, name, fill }: { source: string; name: string; fill?: boolean }) {+ return <iframe sandbox="" referrerPolicy="no-referrer" srcDoc={htmlPreviewDocument(source)} title={t("html.frameTitle", { name })} className={cn(previewHeight(fill), "w-full rounded-lg border border-hairline/40 bg-white")} />;}diff --git a/src/components/MarkdownFilePreview.tsx b/src/components/MarkdownFilePreview.tsxindex fe236e9370..9bc551fb6b 100644--- a/src/components/MarkdownFilePreview.tsx+++ b/src/components/MarkdownFilePreview.tsx@@ -2,14 +2,16 @@ import { useEffect, useState } from "react";import { Code2, Download, Eye, LoaderCircle, RotateCcw } from "lucide-react";import { requestMessageFile, useLocalFileSave, type MessageAttachmentContext } from "./AttachmentPreview";import { ChatMarkdown } from "./ChatMarkdown";+import { previewHeight } from "./HtmlFilePreview";import { readTableResponse } from "./TableFilePreview";+import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";export const MARKDOWN_PREVIEW_MAX_BYTES = 2 * 1024 * 1024;/** A Markdown file in a message, drawn the way the chat draws a reply. Security: no message context is passed on, so* paths written in the file stay plain text instead of becoming links that fetch other files. */-export default function MarkdownFileContent({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {+export default function MarkdownFileContent({ path, name, message, fill = false }: { path: string; name: string; message: MessageAttachmentContext; fill?: boolean }) {const [attempt, setAttempt] = useState(0);const [source, setSource] = useState<string | null>(null);const [error, setError] = useState<"size" | "load" | "encoding" | { reason: string } | null>(null);@@ -40,20 +42,20 @@ export default function MarkdownFileContent({ path, name, message }: { path: strconst recovery = <><div className="mt-3 flex flex-wrap justify-center gap-2"><button type="button" className="inline-flex max-w-full min-w-0 items-center gap-1.5 rounded-lg border border-hairline px-3 py-2 hover:bg-raised" disabled={save.state === "saving"} onClick={() => void save.save()}><Download size={14} className="shrink-0" /><span className="min-w-0 break-all">{t("attach.saveAria", { name })}</span></button><button type="button" className="rounded-lg border border-hairline px-3 py-2 hover:bg-raised" onClick={() => setAttempt(attempt + 1)}>{t("chat.retry")}</button></div>{save.state === "failed" && <p role="alert" className="mt-2 text-[12px] text-danger">{save.reason}</p>}</>;if (error) return <div className="p-8 text-center text-sm"><p role="alert" className="text-ink-secondary">{typeof error === "object" ? t("markdown.refused", { reason: error.reason }) : t(error === "size" ? "markdown.tooLarge" : error === "encoding" ? "markdown.notText" : "markdown.loadFailed")}</p>{recovery}</div>;if (source === null) return <div className="p-12 text-center text-sm text-ink-secondary"><span role="status" className="inline-flex items-center gap-2"><LoaderCircle size={16} className="animate-spin" />{t("markdown.loading")}</span>{recovery}</div>;- return <div className="flex flex-col gap-2">+ return <div className={cn("flex flex-col gap-2", fill && "min-h-0 flex-1")}><div className="flex items-center justify-end gap-1"><button type="button" className="table-action" aria-pressed={showSource} aria-label={t(showSource ? "markdown.rendered" : "html.source")} title={t(showSource ? "markdown.rendered" : "html.source")} onClick={() => setShowSource(!showSource)}>{showSource ? <Eye size={14} /> : <Code2 size={14} />}</button><button type="button" className="table-action" aria-label={t("html.reload")} title={t("html.reload")} onClick={() => setAttempt(attempt + 1)}><RotateCcw size={14} /></button><button type="button" className="table-action" aria-label={t("attach.saveAria", { name })} title={t("attach.saveAria", { name })} disabled={save.state === "saving"} onClick={() => void save.save()}><Download size={14} /></button></div>{save.state === "failed" && <p role="alert" className="text-end text-[12px] text-danger">{save.reason}</p>}- <MarkdownFileView source={source} showSource={showSource} />+ <MarkdownFileView source={source} showSource={showSource} fill={fill} /></div>;}/** The file itself: drawn as Markdown, or its raw text. */-export function MarkdownFileView({ source, showSource }: { source: string; showSource: boolean }) {+export function MarkdownFileView({ source, showSource, fill }: { source: string; showSource: boolean; fill?: boolean }) {return showSource- ? <pre className="h-[72dvh] overflow-auto rounded-lg border border-hairline/40 bg-inset p-3 text-[12px] leading-5 whitespace-pre-wrap break-words text-ink">{source}</pre>- : <div data-markdown-file className="h-[72dvh] overflow-auto rounded-lg border border-hairline/40 bg-panel px-5 py-4 text-[14px] leading-6 text-ink"><ChatMarkdown text={source} /></div>;+ ? <pre className={cn(previewHeight(fill), "overflow-auto rounded-lg border border-hairline/40 bg-inset p-3 text-[12px] leading-5 whitespace-pre-wrap break-words text-ink")}>{source}</pre>+ : <div data-markdown-file className={cn(previewHeight(fill), "overflow-auto rounded-lg border border-hairline/40 bg-panel px-5 py-4 text-[14px] leading-6 text-ink")}><ChatMarkdown text={source} /></div>;}diff --git a/src/components/TableFilePreview.tsx b/src/components/TableFilePreview.tsxindex 17f75793b6..35f66421f5 100644--- a/src/components/TableFilePreview.tsx+++ b/src/components/TableFilePreview.tsx@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";import { LoaderCircle, Table2 } from "lucide-react";import { requestMessageFile, type MessageAttachmentContext } from "./AttachmentPreview";import { RichTable, TableDialog } from "./RichTable";+import { useFileBesideChat } from "@/lib/file-preview";import { TABLE_FILE_MAX_BYTES, tableDelimiter, type TextTable } from "@/lib/table-data";import { t } from "@/lib/i18n";@@ -38,15 +39,19 @@ export async function readTableResponse(response: Response, signal: AbortSignal,export function TableFileButton({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {const [open, setOpen] = useState(false);const trigger = useRef<HTMLButtonElement>(null);+ const beside = useFileBesideChat();const delimiter = tableDelimiter(name) ?? tableDelimiter(path);if (!delimiter) return null;+ const show = () => {+ if (!beside({ kind: "table", path, name, message, opener: trigger.current })) setOpen(true);+ };return <>- <button ref={trigger} type="button" className="table-action" title={t("table.preview", { name })} aria-label={t("table.preview", { name })} onClick={() => setOpen(true)}><Table2 size={14} /></button>+ <button ref={trigger} type="button" className="table-action" title={t("table.preview", { name })} aria-label={t("table.preview", { name })} onClick={show}><Table2 size={14} /></button>{open && <TableDialog title={name} returnFocus={trigger.current} onClose={() => setOpen(false)}><TableFileContent key={`${message.threadId}:${message.messageId}:${path}`} path={path} name={name} message={message} delimiter={delimiter} /></TableDialog>}</>;}-function TableFileContent({ path, name, message, delimiter }: {+export function TableFileContent({ path, name, message, delimiter }: {path: string; name: string; message: MessageAttachmentContext; delimiter: "," | "\t";}) {const [attempt, setAttempt] = useState(0);diff --git a/src/lib/file-preview.ts b/src/lib/file-preview.tsnew file mode 100644index 0000000000..34a7e302d2--- /dev/null+++ b/src/lib/file-preview.ts@@ -0,0 +1,57 @@+import { useCallback, useRef, useSyncExternalStore } from "react";++import { useOptionalStoreRef } from "@/state/store-ref";+import { closeAppPreview } from "./app-preview";+import { closeSidePanels } from "./page-open";+import { closeRoomPanel } from "./room-panel";+import { SIDEBAR_AND_PANEL_FIT } from "./use-media-query";++/** A file from a message, shown beside the chat. Renderer-only: nothing about it is stored or sent anywhere. */+export interface FilePreview {+ kind: "html" | "markdown" | "table";+ path: string;+ name: string;+ message: { threadId: string; messageId: string };+ /** What opened it, to take focus back when the person closes the pane. */+ opener: HTMLElement | null;+}++let current: FilePreview | null = null;+const listeners = new Set<() => void>();++function set(next: FilePreview | null): void {+ if (next === current) return;+ current = next;+ for (const listener of listeners) listener();+}++export const openFilePreview = (preview: FilePreview): void => set({ ...preview });+export const closeFilePreview = (): void => set(null);++export function useFilePreview(): FilePreview | null {+ return useSyncExternalStore((listener) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, () => current, () => null);+}++/** A file opens beside the chat only from the conversation itself, never from a panel, and only when the window is+ * wide enough to keep the sidebar, the chat and the pane side by side. */+export function opensBesideChat(opener: HTMLElement | null): boolean {+ if (!opener?.closest("main[data-look='chat']") || opener.closest("aside")) return false;+ return typeof window.matchMedia === "function" && window.matchMedia(SIDEBAR_AND_PANEL_FIT).matches;+}++/** Shows the file in the pane beside the chat, in place of any other panel on that side, and answers true; false+ * leaves it to the caller's dialog. */+export function useFileBesideChat(): (preview: FilePreview) => boolean {+ const store = useOptionalStoreRef();+ const latest = useRef(store);+ latest.current = store;+ return useCallback((preview: FilePreview) => {+ const app = latest.current;+ if (!app || !opensBesideChat(preview.opener)) return false;+ closeSidePanels(app.dispatch);+ closeAppPreview();+ closeRoomPanel();+ openFilePreview(preview);+ return true;+ }, []);+}diff --git a/src/lib/page-open.ts b/src/lib/page-open.tsindex 24725f344c..1fba04fa98 100644--- a/src/lib/page-open.ts+++ b/src/lib/page-open.ts@@ -82,9 +82,16 @@ export function publishedLink(href: string | null | undefined): AppPreview | nulconst SIDE_PANELS = ["toggleComputer", "toggleSettings", "toggleInspector", "toggleActivity"] as const;-/** Shows a published app beside the open conversation, in place of any other panel on that side. */-export function showAppBesideChat(dispatch: (action: { type: (typeof SIDE_PANELS)[number]; open: false }) => void, preview: AppPreview): void {+type SidePanelDispatch = (action: { type: (typeof SIDE_PANELS)[number]; open: false }) => void;++/** Closes every panel on the chat's right side, so a preview can take that side. */+export function closeSidePanels(dispatch: SidePanelDispatch): void {for (const type of SIDE_PANELS) dispatch({ type, open: false });+}++/** Shows a published app beside the open conversation, in place of any other panel on that side. */+export function showAppBesideChat(dispatch: SidePanelDispatch, preview: AppPreview): void {+ closeSidePanels(dispatch);openAppPreview(preview);}diff --git a/src/locales/en.json b/src/locales/en.jsonindex cff141a5e7..de5f533db6 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3188,6 +3188,8 @@"attach.openOriginalAria": "Open original {name}","attach.openOriginal": "Open original","attach.close": "Close image preview",+ "attach.besideAria": "{name} beside the chat",+ "attach.besideClose": "Close preview","attach.previous": "Previous image","attach.next": "Next image","attach.retryAria": "Retry loading {name}",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 4b464c5a27..80f3553ca9 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -3003,6 +3003,8 @@"attach.openOriginalAria": "Abrir o original de {name}","attach.openOriginal": "Abrir o original","attach.close": "Fechar a prévia da imagem",+ "attach.besideAria": "{name} ao lado do chat",+ "attach.besideClose": "Fechar a prévia","attach.previous": "Imagem anterior","attach.next": "Próxima imagem","attach.retryAria": "Tentar carregar {name} novamente",