Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(files): let self-hosted owners open a single outside-workspace linked file
jonathanwxh-cell7395224e0bb8
diff --git a/server/index.ts b/server/index.tsindex 6062126e74..1724810d86 100644--- a/server/index.ts+++ b/server/index.ts@@ -11965,6 +11965,7 @@ ROUTES.push(createThreadRoutes({cliOwnerToken: () => cliOwnerToken,pageSize, messagePage, messagePageBefore, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,botComputerControlSnapshot: sharedVm.botSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, stopRefusal: (auth, threadId) => runOwners.stopRefusal(threadId, runActor(auth)), memberDefaultBot: CLOUD_TEAM ? (email) => { const own = ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name, opened: (made) => void mausbotOwnChat.claim(made) }); if (own) void mausbotOwnChat.claim(own); return own; } : undefined,+ ...(!CLOUD_HOME && !HOSTED_WORKSPACE ? { ownerOutsideFileRefuse: [DATA_DIR, ...(process.env.OMB_USER_DATA ? [process.env.OMB_USER_DATA] : [])] } : {}),uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),keptAttachments: CLOUD_TEAM ? undefined : keptAttachments,diff --git a/server/message-file.test.ts b/server/message-file.test.tsindex 6dd57fcc22..a4763df945 100644--- a/server/message-file.test.ts+++ b/server/message-file.test.ts@@ -8,6 +8,7 @@ import { afterAll, beforeEach, describe, expect, it } from "vitest";import {MESSAGE_FILE_DOWNLOAD_MAX_BYTES,MESSAGE_FILE_MAX_BYTES,+ canOpenOutsideWorkspaceMessageFile,messageFileDisposition,messageFileDownloadName,messageAttachmentName,@@ -19,6 +20,7 @@ import {mimeFor,openMessageFile,openMessageFolderEntry,+ openOutsideWorkspaceMessageFile,} from "./message-file.ts";const referencesAttachment = (text: string, requested: string) => messageAttachmentName(text, requested) !== null;@@ -499,4 +501,44 @@ describe("message-linked files", () => {expect(messageFileDownloadName("setup.exe", "4e8d.pdf")).toBe("setup.pdf");expect(messageFileDownloadName("preview.jpg", "4e8d.png")).toBe("preview.png");});++ it("opens one explicit outside-workspace regular file for an owner while refusing folders, app data, secrets, and relative links", async () => {+ const outside = mkdtempSync(join(tmpdir(), "omb-outside-single-"));+ const appData = mkdtempSync(join(tmpdir(), "omb-appdata-refuse-"));+ try {+ const note = join(outside, "shared-notes.md");+ writeFileSync(note, "# shared outside note\n");+ const folder = join(outside, "subdir");+ mkdirSync(folder, { recursive: true });+ const appFile = join(appData, "store.json");+ writeFileSync(appFile, "{}");+ const secretDir = join(outside, ".openmausbot-secrets");+ mkdirSync(secretDir, { recursive: true });+ const secretFile = join(secretDir, "token.txt");+ writeFileSync(secretFile, "secret");++ expect(await canOpenOutsideWorkspaceMessageFile(note, [appData])).toBe(true);+ expect(await canOpenOutsideWorkspaceMessageFile(pathToFileURL(note).href, [appData])).toBe(true);+ expect(await canOpenOutsideWorkspaceMessageFile(folder, [appData])).toBe(false);+ expect(await canOpenOutsideWorkspaceMessageFile(appFile, [appData])).toBe(false);+ expect(await canOpenOutsideWorkspaceMessageFile(secretFile, [appData])).toBe(false);+ expect(await canOpenOutsideWorkspaceMessageFile("relative/shared-notes.md", [appData])).toBe(false);++ const opened = await openOutsideWorkspaceMessageFile(note, [appData]);+ try {+ expect(opened.bytes).toBe(22);+ expect(opened.name).toBe("shared-notes.md");+ } finally {+ await opened.handle.close();+ }++ await expect(openOutsideWorkspaceMessageFile(appFile, [appData])).rejects.toMatchObject({ status: 403, code: "outside_workspace" });+ await expect(openOutsideWorkspaceMessageFile(secretFile, [appData])).rejects.toMatchObject({ status: 403, code: "secret_file" });+ await expect(openOutsideWorkspaceMessageFile(folder, [appData])).rejects.toMatchObject({ status: 400, code: "directory" });+ await expect(openOutsideWorkspaceMessageFile("relative/shared-notes.md", [appData])).rejects.toMatchObject({ status: 403, code: "outside_workspace" });+ } finally {+ rmSync(outside, { recursive: true, force: true });+ rmSync(appData, { recursive: true, force: true });+ }+ });});diff --git a/server/message-file.ts b/server/message-file.tsindex cf81999e50..8385ce2ac6 100644--- a/server/message-file.ts+++ b/server/message-file.ts@@ -380,21 +380,73 @@ export function mimeFor(path: string): string {}}-/** Canonicalised before and after opening, and the handle compared with the post-open path, to reject symlink escapes and directory swaps. */-export async function openMessageFile(- href: string,- roots: readonly string[],- maxBytes = MESSAGE_FILE_MAX_BYTES,+async function openCanonicalMessageFile(+ candidate: string,+ canonicalBefore: string,+ maxBytes: number,+ isAllowedAfter: (canonicalAfter: string) => boolean,): Promise<OpenedMessageFile> {- const requested = referencedPath(href);- const canonicalRoots = (await Promise.all(roots.map(async (root) => {+ if (inSecretFolder(canonicalBefore)) throw statusError(403, SECRET_FILE_REFUSAL, "secret_file");++ let handle: FileHandle | undefined;+ try {+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;+ const nonBlock = typeof constants.O_NONBLOCK === "number" ? constants.O_NONBLOCK : 0;+ handle = await open(canonicalBefore, constants.O_RDONLY | noFollow | nonBlock);+ const opened = await handle.stat();+ if (opened.isDirectory()) throw statusError(400, "the link points to a folder, not a file", "directory");+ if (!opened.isFile()) throw statusError(400, "the link does not point to a regular file");+ if (opened.size > maxBytes) throw fileTooLarge(opened.size, maxBytes, canonicalBefore);++ const canonicalAfter = await realpath(candidate);+ if (!isAllowedAfter(canonicalAfter)) throw outsideWorkspace();+ if (inSecretFolder(canonicalAfter)) throw statusError(403, SECRET_FILE_REFUSAL, "secret_file");+ const after = await stat(canonicalAfter);+ if (opened.dev !== after.dev || opened.ino !== after.ino) {+ throw statusError(409, "the linked file changed while it was being opened");+ }++ return {+ handle,+ bytes: opened.size,+ name: basename(canonicalAfter),+ mime: mimeFor(canonicalAfter),+ path: canonicalAfter,+ };+ } catch (error) {+ await handle?.close().catch(() => undefined);+ throw error;+ }+}++async function resolveCanonicalRoots(roots: readonly string[], directoriesOnly: boolean): Promise<string[]> {+ return (await Promise.all(roots.map(async (root) => {+ if (!root) return null;try {const canonical = await realpath(root);- return (await stat(canonical)).isDirectory() ? canonical : null;+ return !directoriesOnly || (await stat(canonical)).isDirectory() ? canonical : null;} catch {return null;}}))).filter((root): root is string => Boolean(root));+}++function resolveAbsoluteLocalHref(href: string): string {+ const requested = referencedPath(href, false, false);+ if (!isAbsolute(requested) || requested.startsWith("\\\\") || requested.startsWith("//")) {+ throw outsideWorkspace();+ }+ return resolve(requested);+}++/** Canonicalised before and after opening, and the handle compared with the post-open path, to reject symlink escapes and directory swaps. */+export async function openMessageFile(+ href: string,+ roots: readonly string[],+ maxBytes = MESSAGE_FILE_MAX_BYTES,+): Promise<OpenedMessageFile> {+ const requested = referencedPath(href);+ const canonicalRoots = await resolveCanonicalRoots(roots, true);if (canonicalRoots.length === 0) throw statusError(404, "the linked file is unavailable");const candidates = isAbsolute(requested)@@ -414,35 +466,9 @@ export async function openMessageFile(sawOutsideRoot = true;continue;}- if (inSecretFolder(canonicalBefore)) throw statusError(403, SECRET_FILE_REFUSAL, "secret_file");-- let handle: FileHandle | undefined;try {- const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;- const nonBlock = typeof constants.O_NONBLOCK === "number" ? constants.O_NONBLOCK : 0;- handle = await open(canonicalBefore, constants.O_RDONLY | noFollow | nonBlock);- const opened = await handle.stat();- if (opened.isDirectory()) throw statusError(400, "the link points to a folder, not a file", "directory");- if (!opened.isFile()) throw statusError(400, "the link does not point to a regular file");- if (opened.size > maxBytes) throw fileTooLarge(opened.size, maxBytes, canonicalBefore);-- const canonicalAfter = await realpath(candidate);- if (!containedBy(root, canonicalAfter)) throw outsideWorkspace();- if (inSecretFolder(canonicalAfter)) throw statusError(403, SECRET_FILE_REFUSAL, "secret_file");- const after = await stat(canonicalAfter);- if (opened.dev !== after.dev || opened.ino !== after.ino) {- throw statusError(409, "the linked file changed while it was being opened");- }-- return {- handle,- bytes: opened.size,- name: basename(canonicalAfter),- mime: mimeFor(canonicalAfter),- path: canonicalAfter,- };+ return await openCanonicalMessageFile(candidate, canonicalBefore, maxBytes, (canonicalAfter) => containedBy(root, canonicalAfter));} catch (error) {- await handle?.close().catch(() => undefined);if (error && typeof error === "object" && "status" in error) throw error;continue;}@@ -452,6 +478,54 @@ export async function openMessageFile(throw statusError(404, "the linked file is unavailable");}+/** True when an owner's explicit single-file open could succeed without granting any folder or secret/app-data path. */+export async function canOpenOutsideWorkspaceMessageFile(href: string, refusedRoots: readonly string[]): Promise<boolean> {+ let candidate: string;+ try {+ candidate = resolveAbsoluteLocalHref(href);+ } catch {+ return false;+ }+ let canonical: string;+ try {+ canonical = await realpath(candidate);+ if (!(await stat(canonical)).isFile()) return false;+ } catch {+ return false;+ }+ if (inSecretFolder(canonical)) return false;+ const canonicalRefused = await resolveCanonicalRoots(refusedRoots, false);+ return !canonicalRefused.some((dir) => containedBy(dir, canonical));+}++/** Opens a single linked regular file outside the workspace for a self-hosted owner, refusing folders, secrets, and app data. */+export async function openOutsideWorkspaceMessageFile(+ href: string,+ refusedRoots: readonly string[],+ maxBytes = MESSAGE_FILE_MAX_BYTES,+): Promise<OpenedMessageFile> {+ const candidate = resolveAbsoluteLocalHref(href);+ const canonicalRefused = await resolveCanonicalRoots(refusedRoots, false);+ let canonicalBefore: string;+ try {+ canonicalBefore = await realpath(candidate);+ } catch {+ throw statusError(404, "the linked file is unavailable");+ }+ if (canonicalRefused.some((dir) => containedBy(dir, canonicalBefore))) throw outsideWorkspace();+ try {+ return await openCanonicalMessageFile(+ candidate,+ canonicalBefore,+ maxBytes,+ (canonicalAfter) => !canonicalRefused.some((dir) => containedBy(dir, canonicalAfter)),+ );+ } catch (error) {+ if (error && typeof error === "object" && "status" in error) throw error;+ throw statusError(404, "the linked file is unavailable");+ }+}+/** HFS+ and FAT keep whole or even seconds, so a file written early in a turn can carry a slightly earlier time. */const SAVED_SINCE_SLACK_MS = 2_000;diff --git a/server/routes/threads-file-handle.test.ts b/server/routes/threads-file-handle.test.tsindex 6fe17a2ee1..c8adcd1961 100644--- a/server/routes/threads-file-handle.test.ts+++ b/server/routes/threads-file-handle.test.ts@@ -1,5 +1,6 @@import { mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";import type { IncomingMessage, ServerResponse } from "node:http";+import { tmpdir } from "node:os";import { join } from "node:path";import { Readable, Writable } from "node:stream";import { pathToFileURL } from "node:url";@@ -139,4 +140,114 @@ describe("POST /api/threads/:threadId/messages/:messageId/file", () => {await result;expect(captured.handles[0]!.fd).toBe(-1);});++ it("lets a self-hosted owner open one linked outside-workspace file only on explicit confirmation, never non-owners, hosted workspaces, app data, folders, or unlinked paths", async () => {+ const store = new Store(() => sonnet);+ const bot = store.createBot({ name: "Scout" }, { seedMessages: false });+ const root = join(DATA_DIR, "task-workspaces", bot.id, bot.threadId);+ const outsideDir = join(tmpdir(), `omb-route-outside-${Date.now()}`);+ mkdirSync(root, { recursive: true });+ mkdirSync(outsideDir, { recursive: true });+ const outsideFile = join(outsideDir, "shared-plan.md");+ const appFile = join(DATA_DIR, "private-store.json");+ const unlinkedFile = join(outsideDir, "unlinked.md");+ writeFileSync(outsideFile, "outside ok\n");+ writeFileSync(appFile, "secret\n");+ writeFileSync(unlinkedFile, "nope\n");+ try {+ const message = store.appendMessage(bot.threadId, {+ role: "bot",+ kind: "text",+ text: `[plan](<${pathToFileURL(outsideFile).href}>) [dir](<${pathToFileURL(outsideDir).href}>) [app](<${pathToFileURL(appFile).href}>)`,+ });+ const callRoute = async (opts: {+ body?: Record<string, unknown>;+ method?: "POST" | "GET";+ query?: string;+ caller?: RequestAuth;+ hostedWorkspace?: boolean;+ ownerOutsideFileRefuse?: readonly string[];+ }) => {+ const chunks: Buffer[] = [];+ let statusCode = 0;+ const headers: Record<string, string> = {};+ const res = Object.assign(new Writable({+ write(chunk, _enc, cb) { chunks.push(Buffer.from(chunk)); cb(); },+ }), {+ writeHead(code: number, hdrs?: Record<string, string>) {+ statusCode = code;+ if (hdrs) Object.assign(headers, hdrs);+ return res;+ },+ setHeader(k: string, v: string) { headers[k.toLowerCase()] = v; return res; },+ }) as unknown as ServerResponse;+ const handle = createThreadRoutes({+ store,+ viewerFor: () => ({}),+ visibleTo: () => ({ bot: () => true, group: () => true, thread: () => true }),+ workspaceAccess: () => null,+ desktopMutationToken: () => undefined,+ companionMutationToken: () => undefined,+ cliOwnerToken: () => undefined,+ messageFileRootsForThread: () => [root],+ hostedWorkspace: opts.hostedWorkspace ?? false,+ ...(opts.ownerOutsideFileRefuse ? { ownerOutsideFileRefuse: opts.ownerOutsideFileRefuse } : {}),+ } as unknown as ThreadRouteDeps);+ const path = `/api/threads/${bot.threadId}/messages/${message.id}/file`;+ const url = new URL(`${path}${opts.query ?? ""}`, "http://127.0.0.1");+ const req = Readable.from(opts.method === "GET" ? [] : [Buffer.from(JSON.stringify(opts.body ?? {}))]) as IncomingMessage;+ req.headers = { "content-type": "application/json" };+ req.method = opts.method ?? "POST";+ try {+ await handle({ req, res, url, path, method: opts.method ?? "POST", auth: opts.caller ?? auth, json, readBody });+ } catch (err) {+ const status = (err as { status?: number } | null)?.status ?? 500;+ const code = (err as { code?: string } | null)?.code;+ return {+ statusCode: status,+ headers,+ body: JSON.stringify({ error: err instanceof Error ? err.message : String(err), ...(code ? { code } : {}) }),+ };+ }+ return { statusCode, headers, body: Buffer.concat(chunks).toString("utf8") };+ };++ // Self-hosted owner gets canOpenOutside hint on initial click, then opens on allowOutsideWorkspace.+ const first = await callRoute({ body: { path: outsideFile, listFolder: true }, ownerOutsideFileRefuse: [DATA_DIR] });+ expect(first.statusCode).toBe(403);+ expect(JSON.parse(first.body)).toMatchObject({ code: "outside_workspace", canOpenOutside: true });++ const opened = await callRoute({ body: { path: outsideFile, allowOutsideWorkspace: true }, ownerOutsideFileRefuse: [DATA_DIR] });+ expect(opened.statusCode).toBe(200);+ expect(opened.body).toBe("outside ok\n");++ // Folder links, listFolder + allowOutsideWorkspace, app data, and unlinked files remain refused without canOpenOutside.+ const folderHint = await callRoute({ body: { path: outsideDir, listFolder: true }, ownerOutsideFileRefuse: [DATA_DIR] });+ expect(folderHint.statusCode).toBe(403);+ expect(JSON.parse(folderHint.body).canOpenOutside).toBeUndefined();++ const folderBypass = await callRoute({ body: { path: outsideDir, listFolder: true, allowOutsideWorkspace: true }, ownerOutsideFileRefuse: [DATA_DIR] });+ expect(folderBypass.statusCode).toBe(403);++ const appDataRefusal = await callRoute({ body: { path: appFile, allowOutsideWorkspace: true }, ownerOutsideFileRefuse: [DATA_DIR] });+ expect(appDataRefusal.statusCode).toBe(403);++ const unlinkedRefusal = await callRoute({ body: { path: unlinkedFile, allowOutsideWorkspace: true }, ownerOutsideFileRefuse: [DATA_DIR] });+ expect(unlinkedRefusal.statusCode).toBe(403);++ // Non-admin callers, service loopback, hosted workspaces, and cloud deployments (no ownerOutsideFileRefuse) cannot open outside files.+ const nonOwner = { kind: "session", session: { id: "member-1", membershipAuthority: "local" }, scopes: [] } as unknown as RequestAuth;+ const serviceLoopback = { kind: "loopback", trust: "service", scopes: [] } as unknown as RequestAuth;+ for (const caller of [nonOwner, serviceLoopback]) {+ const res = await callRoute({ body: { path: outsideFile }, caller, ownerOutsideFileRefuse: [DATA_DIR] });+ expect(res.statusCode).toBe(403);+ expect(JSON.parse(res.body).canOpenOutside).toBeUndefined();+ expect((await callRoute({ body: { path: outsideFile, allowOutsideWorkspace: true }, caller, ownerOutsideFileRefuse: [DATA_DIR] })).statusCode).toBe(403);+ }+ expect((await callRoute({ body: { path: outsideFile, allowOutsideWorkspace: true }, hostedWorkspace: true, ownerOutsideFileRefuse: [DATA_DIR] })).statusCode).toBe(403);+ expect((await callRoute({ body: { path: outsideFile, allowOutsideWorkspace: true } })).statusCode).toBe(403);+ } finally {+ rmSync(outsideDir, { recursive: true, force: true });+ }+ });});diff --git a/server/routes/threads.ts b/server/routes/threads.tsindex 354c85f131..e863863fb2 100644--- a/server/routes/threads.ts+++ b/server/routes/threads.ts@@ -21,10 +21,10 @@ import type { GroupUsageReader } from "../group-thread-usage.ts";import { readMessage, searchMessagesAsync } from "../message-db.ts";import { cappedMediaRange, MessageMediaLinks, STREAMABLE_MEDIA_MIMES } from "../message-media-links.ts";import {- listMessageFolder, MESSAGE_FILE_DOWNLOAD_MAX_BYTES, MESSAGE_FILE_MAX_BYTES, messageAttachmentName, messageFileDisposition, messageFileDownloadName, messageFolderEntryName,- messageImageTargetAt, messageReferencesFile, openMessageFile, openMessageFolderEntry, referencedFileName,+ canOpenOutsideWorkspaceMessageFile, listMessageFolder, MESSAGE_FILE_DOWNLOAD_MAX_BYTES, MESSAGE_FILE_MAX_BYTES, messageAttachmentName, messageFileDisposition, messageFileDownloadName, messageFolderEntryName,+ messageImageTargetAt, messageReferencesFile, openMessageFile, openMessageFolderEntry, openOutsideWorkspaceMessageFile, referencedFileName,} from "../message-file.ts";-import { resolveRequestAuth, type RequestAuth, type ResolveOptions } from "../request-auth.ts";+import { ownerOrAdmin, resolveRequestAuth, type RequestAuth, type ResolveOptions } from "../request-auth.ts";import type { queuedSteerSnapshot } from "../steer-queue.ts";import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";import { answerAsleep, backgroundWhileAsleep } from "../cloud-power.ts";@@ -78,6 +78,8 @@ export interface ThreadRouteDeps {attachmentInUse(name: string): boolean;/** The stored files a Settings clear must leave (pictures, banner, routine and calendar-call files), null until those load; absent on a Team Cloud, which has no clear. */keptAttachments?(): ReadonlySet<string> | null;+ /** Directories a self-hosted owner still cannot open via single outside-workspace file links (app data dir, user data). */+ ownerOutsideFileRefuse?: readonly string[];}export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {@@ -279,6 +281,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {if (folderEntry === null) return json(res, 400, { error: "entry must be one file name" });// An inline image is read whole by the browser; a saved file is streamed below, so it may be larger.const maxBytes = streamsMessageImage ? MESSAGE_FILE_MAX_BYTES : MESSAGE_FILE_DOWNLOAD_MAX_BYTES;+ const ownerCanOpenOutside = Boolean(deps.ownerOutsideFileRefuse) && !HOSTED_WORKSPACE && ownerOrAdmin(auth) && method === "POST" && message.role === "bot" && !botAttachment && !folderEntry && !asksMediaLink;let file: Awaited<ReturnType<typeof openMessageFile>> | undefined;try {try {@@ -299,6 +302,14 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {if (copy) {file = await openMessageFile(copy.path, [ATTACHMENTS_DIR], maxBytes);downloadName = copy.name;+ } else if (code === "outside_workspace" && ownerCanOpenOutside) {+ if (body?.allowOutsideWorkspace === true && body?.listFolder !== true) {+ file = await openOutsideWorkspaceMessageFile(href, deps.ownerOutsideFileRefuse!, maxBytes);+ } else if (await canOpenOutsideWorkspaceMessageFile(href, deps.ownerOutsideFileRefuse!)) {+ return json(res, 403, { error: error instanceof Error ? error.message : "the linked file is outside this conversation's workspace", code: "outside_workspace", canOpenOutside: true });+ } else {+ throw error;+ }} else {// Only a client that asks for listings gets one; older clients keep the 400.if (body?.listFolder !== true || folderEntry || code !== "directory") throw error;diff --git a/src/components/AttachmentPreview.test.ts b/src/components/AttachmentPreview.test.tsindex 031c131193..75c1b4157a 100644--- a/src/components/AttachmentPreview.test.ts+++ b/src/components/AttachmentPreview.test.ts@@ -365,3 +365,40 @@ describe("image preview copy button", () => {}});});++describe("opening a single outside-workspace file when permitted by owner", () => {+ it("preserves canOpenOutside on outside_workspace errors and omits listFolder on retry", async () => {+ const fetch = vi.fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({+ error: "the linked file is outside this conversation's workspace",+ code: "outside_workspace",+ canOpenOutside: true,+ }), { status: 403, headers: { "content-type": "application/json" } }))+ .mockResolvedValueOnce(new Response(new Blob(["hello"], { type: "text/plain" }), { status: 200 }));+ vi.stubGlobal("fetch", fetch);+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:test"), revokeObjectURL: vi.fn() });+ const seen: { current: ReturnType<typeof useLocalFileSave> | null } = { current: null };+ const Probe = () => {+ seen.current = useLocalFileSave("/outside/notes.md", "notes.md", { threadId: "t1", messageId: "m1" });+ return null;+ };+ const root = createRoot(document.createElement("div"));+ try {+ await act(async () => { root.render(createElement(Probe)); });+ await act(async () => { await seen.current!.save(); });+ expect(seen.current!.state).toBe("failed");+ expect(seen.current!.outsideWorkspace).toBe(true);+ expect(seen.current!.canOpenOutside).toBe(true);++ await act(async () => { await seen.current!.save({ allowOutsideWorkspace: true }); });+ expect(seen.current!.state).toBe("saved");+ expect(JSON.parse(String(fetch.mock.calls[1]![1]!.body))).toEqual({+ path: "/outside/notes.md",+ allowOutsideWorkspace: true,+ });+ } finally {+ await act(async () => { root.unmount(); });+ vi.unstubAllGlobals();+ }+ });+});diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsxindex a47336a2c1..e6c06fe4d0 100644--- a/src/components/AttachmentPreview.tsx+++ b/src/components/AttachmentPreview.tsx@@ -17,7 +17,6 @@ import {ExternalLink,Eye,FileText,- FolderOpen,ImageOff,LoaderCircle,Maximize2,@@ -33,12 +32,13 @@ import {} from "@/lib/composer-attachments";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { revealBridge, revealHostPath, revealProblemText, REVEALABLE_PATH } from "@/lib/reveal-host-path";import { serverErrorText } from "@/lib/server-error";import { CopyImageButton } from "./CopyImageButton";import { FilePreviewButton } from "./FilePreviewButton";import { chipNameAction, SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";-import { ImageLoading } from "./ImageLoading"; import { openLinkedFolder } from "./RevealOriginalMenu"; import { serverFetch } from "@/lib/relay-server";+import { ImageLoading } from "./ImageLoading"; import { OutsideWorkspaceFile } from "./OutsideWorkspacePreview"; import { openLinkedFolder } from "./RevealOriginalMenu"; import { serverFetch } from "@/lib/relay-server";++export { OutsideWorkspaceFile };export interface PreviewImage {src: string;@@ -225,20 +225,25 @@ export async function requestMessageFile(filePath: string,message: MessageAttachmentContext,signal: AbortSignal,- options?: { entry?: string; list?: boolean; mediaLink?: boolean },+ options?: { entry?: string; list?: boolean; mediaLink?: boolean; allowOutsideWorkspace?: boolean },): Promise<Response> {const response = await serverFetch(`/api/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.messageId)}/file`, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({path: filePath,- ...(options?.entry !== undefined ? { entry: options.entry } : options?.list ? { listFolder: true } : options?.mediaLink ? { media: true } : {}),+ ...(options?.allowOutsideWorkspace ? { allowOutsideWorkspace: true } : {}),+ ...(options?.entry !== undefined ? { entry: options.entry } : options?.allowOutsideWorkspace ? {} : options?.list ? { listFolder: true } : options?.mediaLink ? { media: true } : {}),}),signal,});if (!response.ok) {- const body = await response.json().catch(() => null) as { error?: string; code?: string } | null;- throw Object.assign(new Error(serverErrorText(body, body?.error ?? t("attach.downloadFailed"))), { code: body?.code, status: response.status });+ const body = await response.json().catch(() => null) as { error?: string; code?: string; canOpenOutside?: unknown } | null;+ throw Object.assign(new Error(serverErrorText(body, body?.error ?? t("attach.downloadFailed"))), {+ code: body?.code,+ status: response.status,+ ...(body?.canOpenOutside === true ? { canOpenOutside: true } : {}),+ });}return response;}@@ -255,6 +260,7 @@ export function useLocalFileSave(filePath: string, name?: string, message?: Messconst [reason, setReason] = useState("");const [savedTo, setSavedTo] = useState("");const [failureCode, setFailureCode] = useState<unknown>(undefined);+ const [canOpenOutside, setCanOpenOutside] = useState(false);const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const request = useRef<AbortController | null>(null);const saving = useRef(false);@@ -276,11 +282,12 @@ export function useLocalFileSave(filePath: string, name?: string, message?: MesssetReason("");setSavedTo("");setFailureCode(undefined);+ setCanOpenOutside(false);setFolder(null);setState("idle");}, [filePath, entry, message?.messageId, message?.threadId]);- const save = useCallback(async () => {+ const save = useCallback(async (options?: { allowOutsideWorkspace?: boolean }) => {if (saving.current) return;if (!message) {setReason(t("attach.unavailableOld"));@@ -294,12 +301,18 @@ export function useLocalFileSave(filePath: string, name?: string, message?: Mess}setReason("");setFailureCode(undefined);+ setCanOpenOutside(false);setState("saving");request.current?.abort();const controller = new AbortController();request.current = controller;try {- const response = await requestMessageFile(filePath, message, controller.signal, entry === undefined ? { list: true } : { entry });+ const requestOptions = entry !== undefined+ ? { entry }+ : options?.allowOutsideWorkspace+ ? { allowOutsideWorkspace: true }+ : { list: true };+ const response = await requestMessageFile(filePath, message, controller.signal, requestOptions);if (response.headers.get("x-openmausbot-folder") === "1") {const listing = await response.json() as MessageFolderListing;if (!mounted.current || controller.signal.aborted) return;@@ -342,6 +355,7 @@ export function useLocalFileSave(filePath: string, name?: string, message?: Messif (!mounted.current || controller.signal.aborted) return;setReason(error instanceof Error ? error.message : t("attach.saveFailed"));setFailureCode((error as { code?: unknown } | null)?.code);+ setCanOpenOutside((error as { canOpenOutside?: unknown } | null)?.canOpenOutside === true);setState("failed");} finally {if (request.current === controller) {@@ -352,7 +366,7 @@ export function useLocalFileSave(filePath: string, name?: string, message?: Mess}, [filePath, entry, message?.messageId, message?.threadId, name]);const outsideWorkspace = failureCode === "outside_workspace"; // Retrying can't move a file into the folder or make it smaller.- return { state, reason, savedTo, outsideWorkspace, retryable: state === "failed" && !outsideWorkspace && failureCode !== "file_too_large", folder, save };+ return { state, reason, savedTo, outsideWorkspace, canOpenOutside, retryable: state === "failed" && !outsideWorkspace && failureCode !== "file_too_large", folder, save };}export function saveFailureText(save: { reason: string; outsideWorkspace: boolean }): string {@@ -417,38 +431,6 @@ export function MessageFolderFiles({ folderPath, listing, message }: {);}-export function OutsideWorkspaceFile({ filePath, standalone = false }: { filePath: string; standalone?: boolean }) {- const [problem, setProblem] = useState("");- const reveal = revealBridge();- if (!reveal || !REVEALABLE_PATH.test(filePath)) {- return (- <code title={t("attach.outsideWorkspacePath")} className="select-all whitespace-pre-wrap break-all text-ink">- {filePath}- </code>- );- }- const show = async () => {- setProblem("");- const result = await revealHostPath(filePath);- const text = revealProblemText(result);- if (text) setProblem(text);- };- return (- <>- <button- type="button"- onClick={() => void show()}- title={filePath}- className={standalone ? "ui-button touch:min-h-10" : "inline-flex items-center gap-1 text-accent underline decoration-accent/40 hover:decoration-accent"}- >- <FolderOpen size={standalone ? 14 : 12} className="shrink-0" aria-hidden="true" />- {t("attach.showInFolder")}- </button>- {problem && <span role="alert" className="text-danger">{problem}</span>}- </>- );-}-export function AttachmentPreviewDialog({image,images,@@ -943,7 +925,11 @@ export function AttachedFileChip({ file, message, linked = false, compact = fals: saveFailureText(save)}{failed && save.outsideWorkspace && (<div className="mt-1 flex flex-wrap items-center gap-x-1.5">- <OutsideWorkspaceFile filePath={file.shownPath ?? file.path} />+ <OutsideWorkspaceFile+ filePath={file.shownPath ?? file.path}+ onOpenOutside={save.canOpenOutside ? () => void save.save({ allowOutsideWorkspace: true }) : undefined}+ openOutsideLabel={t("attach.saveOutsideFile")}+ /></div>)}</div>@@ -1003,7 +989,13 @@ function CompactFileChip({ file, message, linked, save, preview, className }: {<span role={failed ? "alert" : "status"} className={cn("px-2.5 text-[12px]", failed ? "text-danger" : "text-ink-secondary")}>{save.state === "saving" ? t("attach.downloading") : saveFailureText(save)}{failed && save.outsideWorkspace && (- <span className="ms-1.5 inline-flex flex-wrap items-center gap-x-1.5"><OutsideWorkspaceFile filePath={file.shownPath ?? file.path} /></span>+ <span className="ms-1.5 inline-flex flex-wrap items-center gap-x-1.5">+ <OutsideWorkspaceFile+ filePath={file.shownPath ?? file.path}+ onOpenOutside={save.canOpenOutside ? () => void save.save({ allowOutsideWorkspace: true }) : undefined}+ openOutsideLabel={t("attach.saveOutsideFile")}+ />+ </span>)}</span>)}diff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.tsindex cdb2f146c3..9dbec7c775 100644--- a/src/components/ChatMarkdown.test.ts+++ b/src/components/ChatMarkdown.test.ts@@ -907,6 +907,7 @@ describe("ChatMarkdown attachments", () => {reason: "",savedTo: "",outsideWorkspace: false,+ canOpenOutside: false,retryable: false,folder: {name: "04_post",@@ -941,6 +942,7 @@ describe("ChatMarkdown attachments", () => {reason: outsideWorkspace ? "the linked file is outside this conversation's workspace" : "",savedTo: "",outsideWorkspace,+ canOpenOutside: false,retryable: !outsideWorkspace,folder: null,save: vi.fn(async () => undefined),@@ -1008,7 +1010,7 @@ describe("ChatMarkdown attachments", () => {const outsideSave = () => {vi.spyOn(OutsideWorkspaceProbe, "useMessageFileOutsideWorkspace").mockReturnValue(null);return vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({- state: "failed", reason: "", savedTo: "", outsideWorkspace: true, retryable: false, folder: null,+ state: "failed", reason: "", savedTo: "", outsideWorkspace: true, canOpenOutside: false, retryable: false, folder: null,save: vi.fn(async () => undefined),});};@@ -1041,7 +1043,7 @@ describe("ChatMarkdown attachments", () => {const reveal = vi.fn(async () => "shown" as const);(window as { ogb?: unknown }).ogb = { revealInFolder: reveal, remoteClient: { active: false } };vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({- state: "idle", reason: "", savedTo: "", outsideWorkspace: false, retryable: false, folder: null,+ state: "idle", reason: "", savedTo: "", outsideWorkspace: false, canOpenOutside: false, retryable: false, folder: null,save: vi.fn(async () => undefined),});const host = document.createElement("div");@@ -1070,6 +1072,7 @@ describe("ChatMarkdown attachments", () => {reason: "the linked file is outside this conversation's workspace",savedTo: "",outsideWorkspace: false,+ canOpenOutside: false,retryable: true,folder: null,save: vi.fn(async () => undefined),diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsxindex 051f9d06b1..e74ea593fc 100644--- a/src/components/ChatMarkdown.tsx+++ b/src/components/ChatMarkdown.tsx@@ -440,7 +440,11 @@ function LocalFileLink({ filePath, shownPath, shownName, name, source, children,)}{save.state === "failed" && save.outsideWorkspace && !revealOnClick && (<span className="inline-flex flex-wrap items-center gap-x-1.5 text-[12px]">- <OutsideWorkspaceFile filePath={shownPath} />+ <OutsideWorkspaceFile+ filePath={shownPath}+ onOpenOutside={save.canOpenOutside ? () => void save.save({ allowOutsideWorkspace: true }) : undefined}+ openOutsideLabel={t("attach.saveOutsideFile")}+ /></span>)}{save.folder && <MessageFolderFiles folderPath={filePath} listing={save.folder} message={message} />}diff --git a/src/components/HtmlFilePreview.dom.test.ts b/src/components/HtmlFilePreview.dom.test.tsindex acf2a15bf7..8bcca29194 100644--- a/src/components/HtmlFilePreview.dom.test.ts+++ b/src/components/HtmlFilePreview.dom.test.ts@@ -39,4 +39,21 @@ describe("HTML file preview errors", () => {expect(alertText()).toBe("");expect(document.body.querySelector("iframe")?.getAttribute("srcdoc")).toContain("<h1>Report</h1>");});++ it("offers Open this file when outside_workspace includes canOpenOutside and opens on click", async () => {+ const fetch = vi.fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({ error: "the linked file is outside this conversation's workspace", code: "outside_workspace", canOpenOutside: true }), { status: 403, headers: { "content-type": "application/json" } }))+ .mockResolvedValueOnce(new Response("<h1>Allowed outside HTML</h1>"));+ vi.stubGlobal("fetch", fetch);+ await act(async () => root.render(createElement(HtmlFileButton, { path: "/outside/report.html", name: "report.html", message })));+ await act(async () => host.querySelector<HTMLButtonElement>("button")!.click());+ const openOutside = await vi.waitFor(() => {+ const button = [...document.body.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === "Open this file");+ expect(button).toBeDefined();+ return button!;+ });+ await act(async () => openOutside.click());+ await vi.waitFor(() => expect(document.body.querySelector("iframe")?.getAttribute("srcdoc")).toContain("<h1>Allowed outside HTML</h1>"));+ expect(JSON.parse(String(fetch.mock.calls[1]![1]!.body))).toEqual({ path: "/outside/report.html", allowOutsideWorkspace: true });+ });});diff --git a/src/components/HtmlFilePreview.tsx b/src/components/HtmlFilePreview.tsxindex 71f965f0ce..44bc252800 100644--- a/src/components/HtmlFilePreview.tsx+++ b/src/components/HtmlFilePreview.tsx@@ -1,7 +1,7 @@import { Component, lazy, Suspense, useEffect, useRef, useState, type ReactNode } from "react";import { Check, Code2, Download, ExternalLink, Eye, LoaderCircle, RotateCcw } from "lucide-react";import { requestMessageFile, useLocalFileSave, type MessageAttachmentContext } from "./AttachmentPreview";-import { OutsideWorkspacePreview, refusedAsOutsideWorkspace } from "./OutsideWorkspacePreview";+import { OutsideWorkspacePreview, canOpenOutsideWorkspace, refusedAsOutsideWorkspace } from "./OutsideWorkspacePreview";import { TableDialog } from "./RichTable";import { readTableResponse, TableFileContent } from "./TableFilePreview";import { cn } from "@/lib/cn";@@ -136,34 +136,42 @@ export function OpenInBrowserButton({ source, name, onError }: { source: string;}function HtmlFileContent({ path, shownPath, name, message, fill }: { path: string; shownPath: string; name: string; message: MessageAttachmentContext; fill: boolean }) {+ const fileKey = `${message.threadId}:${message.messageId}:${path}`;const [attempt, setAttempt] = useState(0);const [source, setSource] = useState<string | null>(null);const [error, setError] = useState<"size" | "load" | "outside" | { reason: string } | null>(null);+ const [canOpenOutside, setCanOpenOutside] = useState(false);+ const [allowOutsideFor, setAllowOutsideFor] = useState<string | null>(null);+ const allowOutside = allowOutsideFor === fileKey;const [showSource, setShowSource] = useState(false);const [openFailed, setOpenFailed] = useState("");const save = useLocalFileSave(path, name, message);useEffect(() => {const controller = new AbortController();setError(null);+ setCanOpenOutside(false);setSource(null);void (async () => {let answered = false;try {- const response = await requestMessageFile(path, message, controller.signal);+ const response = await requestMessageFile(path, message, controller.signal, allowOutside ? { allowOutsideWorkspace: true } : undefined);answered = true;const text = await readTableResponse(response, controller.signal, PREVIEW_MAX_BYTES);if (!controller.signal.aborted) setSource(text);} catch (reason) {if (controller.signal.aborted) return;// A refusal from the server says why; only a request that got no answer (TypeError) is the connection.- if (refusedAsOutsideWorkspace(reason)) setError("outside");+ if (refusedAsOutsideWorkspace(reason)) {+ setCanOpenOutside(canOpenOutsideWorkspace(reason));+ setError("outside");+ }else if (!answered && reason instanceof Error && !(reason instanceof TypeError)) setError({ reason: reason.message });else setError(reason instanceof Error && reason.message === "size" ? "size" : "load");}})();return () => controller.abort();- }, [path, message.threadId, message.messageId, attempt]);- if (error === "outside") return <OutsideWorkspacePreview filePath={shownPath} />;+ }, [path, message.threadId, message.messageId, attempt, allowOutside]);+ if (error === "outside") return <OutsideWorkspacePreview filePath={shownPath} onOpenOutside={canOpenOutside ? () => setAllowOutsideFor(fileKey) : undefined} />;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" ? "attach.fileTooLarge" : "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={cn("flex flex-col gap-2", fill && "min-h-0 flex-1")}>@@ -171,7 +179,7 @@ function HtmlFileContent({ path, shownPath, name, message, fill }: { path: strin<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><OpenInBrowserButton source={source} name={name} onError={setOpenFailed} />- <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>+ <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(allowOutside ? { allowOutsideWorkspace: true } : undefined)}><Download size={14} /></button></div>{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>}diff --git a/src/components/MarkdownFilePreview.tsx b/src/components/MarkdownFilePreview.tsxindex 4f9566a3f2..93c72a348a 100644--- a/src/components/MarkdownFilePreview.tsx+++ b/src/components/MarkdownFilePreview.tsx@@ -1,7 +1,7 @@import { useEffect, useState } from "react";import { Code2, Download, Eye, LoaderCircle, RotateCcw } from "lucide-react";import { requestMessageFile, useLocalFileSave, type MessageAttachmentContext } from "./AttachmentPreview";-import { OutsideWorkspacePreview, refusedAsOutsideWorkspace } from "./OutsideWorkspacePreview";+import { OutsideWorkspacePreview, canOpenOutsideWorkspace, refusedAsOutsideWorkspace } from "./OutsideWorkspacePreview";import { ChatMarkdown } from "./ChatMarkdown";import { previewHeight } from "./HtmlFilePreview";import { readTableResponse } from "./TableFilePreview";@@ -16,19 +16,24 @@ const AUTO_RENDER_MAX_CHARS = 2 * 1024 * 1024;* paths written in the file stay plain text instead of becoming links that fetch other files. plain: a plain text* file, always shown as its raw text. */export default function MarkdownFileContent({ path, shownPath = path, name, message, fill = false, plain = false }: { path: string; shownPath?: string; name: string; message: MessageAttachmentContext; fill?: boolean; plain?: boolean }) {+ const fileKey = `${message.threadId}:${message.messageId}:${path}`;const [attempt, setAttempt] = useState(0);const [source, setSource] = useState<string | null>(null);const [error, setError] = useState<"size" | "load" | "encoding" | "outside" | { reason: string } | null>(null);+ const [canOpenOutside, setCanOpenOutside] = useState(false);+ const [allowOutsideFor, setAllowOutsideFor] = useState<string | null>(null);+ const allowOutside = allowOutsideFor === fileKey;const [showSource, setShowSource] = useState(false);const save = useLocalFileSave(path, name, message);useEffect(() => {const controller = new AbortController();setError(null);+ setCanOpenOutside(false);setSource(null);void (async () => {let answered = false;try {- const response = await requestMessageFile(path, message, controller.signal);+ const response = await requestMessageFile(path, message, controller.signal, allowOutside ? { allowOutsideWorkspace: true } : undefined);answered = true;// Notes saved by Windows apps are often Windows-1252, not UTF-8.const text = await readTableResponse(response, controller.signal, PREVIEW_MAX_BYTES, "windows-1252");@@ -39,23 +44,26 @@ export default function MarkdownFileContent({ path, shownPath = path, name, mess} catch (reason) {if (controller.signal.aborted) return;// A refusal from the server says why; only a request that got no answer (TypeError) is the connection.- if (refusedAsOutsideWorkspace(reason)) setError("outside");+ if (refusedAsOutsideWorkspace(reason)) {+ setCanOpenOutside(canOpenOutsideWorkspace(reason));+ setError("outside");+ }else if (!answered && reason instanceof Error && !(reason instanceof TypeError)) setError({ reason: reason.message });else setError(reason instanceof Error && (reason.message === "size" || reason.message === "encoding") ? reason.message : "load");}})();return () => controller.abort();- }, [path, message.threadId, message.messageId, attempt]);+ }, [path, message.threadId, message.messageId, attempt, allowOutside]);// Save and Retry stay on screen while loading too, so a stalled request never leaves only a spinner; they wrap so a long name can't push Retry off a narrow dialog.- const 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 === "outside") return <OutsideWorkspacePreview filePath={shownPath} />;+ const 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(allowOutside ? { allowOutsideWorkspace: true } : undefined)}><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 === "outside") return <OutsideWorkspacePreview filePath={shownPath} onOpenOutside={canOpenOutside ? () => setAllowOutsideFor(fileKey) : undefined} />;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" ? "attach.fileTooLarge" : 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={cn("flex flex-col gap-2", fill && "min-h-0 flex-1")}><div className="flex items-center justify-end gap-1">{!plain && <button type="button" className="table-action" aria-pressed={showSource} aria-label={t(showSource ? "markdown.rendered" : "html.source")} title={t(showSource ? "markdown.rendered" : "html.source")} disabled={source.length > AUTO_RENDER_MAX_CHARS} 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>+ <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(allowOutside ? { allowOutsideWorkspace: true } : undefined)}><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} fill={fill} />diff --git a/src/components/OutsideWorkspacePreview.tsx b/src/components/OutsideWorkspacePreview.tsxindex 786b19c72f..43655de02f 100644--- a/src/components/OutsideWorkspacePreview.tsx+++ b/src/components/OutsideWorkspacePreview.tsx@@ -1,19 +1,88 @@-import { OutsideWorkspaceFile } from "./AttachmentPreview";-import { REVEALABLE_PATH, revealBridge } from "@/lib/reveal-host-path";+import { useState } from "react";+import { FolderOpen } from "lucide-react";++import { REVEALABLE_PATH, revealBridge, revealHostPath, revealProblemText } from "@/lib/reveal-host-path";import { t } from "@/lib/i18n";+export function OutsideWorkspaceFile({+ filePath,+ standalone = false,+ onOpenOutside,+ openOutsideLabel,+}: {+ filePath: string;+ standalone?: boolean;+ onOpenOutside?: () => void;+ openOutsideLabel?: string;+}) {+ const [problem, setProblem] = useState("");+ const reveal = revealBridge();+ const openButton = onOpenOutside ? (+ <button+ type="button"+ onClick={onOpenOutside}+ className={standalone ? "ui-button touch:min-h-10" : "inline-flex items-center gap-1 text-accent underline decoration-accent/40 hover:decoration-accent"}+ >+ {openOutsideLabel ?? t("attach.openOutsideFile")}+ </button>+ ) : null;+ if (!reveal || !REVEALABLE_PATH.test(filePath)) {+ const pathCode = (+ <code title={t("attach.outsideWorkspacePath")} className="select-all whitespace-pre-wrap break-all text-ink">+ {filePath}+ </code>+ );+ if (!openButton) return pathCode;+ return (+ <>+ {openButton}+ {pathCode}+ </>+ );+ }+ const show = async () => {+ setProblem("");+ const result = await revealHostPath(filePath);+ const text = revealProblemText(result);+ if (text) setProblem(text);+ };+ return (+ <>+ {openButton}+ <button+ type="button"+ onClick={() => void show()}+ title={filePath}+ className={standalone ? "ui-button touch:min-h-10" : "inline-flex items-center gap-1 text-accent underline decoration-accent/40 hover:decoration-accent"}+ >+ <FolderOpen size={standalone ? 14 : 12} className="shrink-0" aria-hidden="true" />+ {t("attach.showInFolder")}+ </button>+ {problem && <span role="alert" className="text-danger">{problem}</span>}+ </>+ );+}+export const refusedAsOutsideWorkspace = (error: unknown): boolean => (error as { code?: unknown } | null)?.code === "outside_workspace";-export function OutsideWorkspacePreview({ filePath }: { filePath: string }) {+export const canOpenOutsideWorkspace = (error: unknown): boolean =>+ refusedAsOutsideWorkspace(error) && (error as { canOpenOutside?: unknown } | null)?.canOpenOutside === true;++export function OutsideWorkspacePreview({ filePath, onOpenOutside }: { filePath: string; onOpenOutside?: () => void }) {const absolute = REVEALABLE_PATH.test(filePath) || /^(?:\\\\|\/\/)/.test(filePath);const revealable = Boolean(revealBridge()) && REVEALABLE_PATH.test(filePath);return (<div className="p-8 text-center text-sm"><p role="alert" className="mb-3 text-ink-secondary">{t("attach.previewOutsideWorkspace")}</p>+ {onOpenOutside && !absolute && (+ <div className="mb-2 flex justify-center">+ <button type="button" onClick={onOpenOutside} className="ui-button touch:min-h-10">{t("attach.openOutsideFile")}</button>+ </div>+ )}{absolute && <>{!revealable && <p className="mb-1 text-[12px] text-ink-secondary">{t("attach.outsideWorkspacePath")}</p>}- <div className="flex flex-col items-center gap-1 text-[12px]">- <OutsideWorkspaceFile filePath={filePath} standalone />+ <div className="flex flex-col items-center gap-2 text-[12px]">+ <OutsideWorkspaceFile filePath={filePath} standalone onOpenOutside={onOpenOutside} />{revealable && <code className="select-all whitespace-pre-wrap break-all text-ink-secondary">{filePath}</code>}</div></>}diff --git a/src/components/TableFilePreview.tsx b/src/components/TableFilePreview.tsxindex ea34cb6027..808eb70103 100644--- a/src/components/TableFilePreview.tsx+++ b/src/components/TableFilePreview.tsx@@ -1,7 +1,7 @@import { useEffect, useMemo, useRef, useState } from "react";import { LoaderCircle, Table2 } from "lucide-react";import { requestMessageFile, type MessageAttachmentContext } from "./AttachmentPreview";-import { OutsideWorkspacePreview, refusedAsOutsideWorkspace } from "./OutsideWorkspacePreview";+import { OutsideWorkspacePreview, canOpenOutsideWorkspace, refusedAsOutsideWorkspace } from "./OutsideWorkspacePreview";import { RichTable, TableDialog } from "./RichTable";import { useFileBesideChat } from "@/lib/file-preview";import { TABLE_FILE_MAX_BYTES, tableDelimiter, type TextTable } from "@/lib/table-data";@@ -55,13 +55,18 @@ export function TableFileButton({ path, shownPath, name, message }: { path: striexport function TableFileContent({ path, shownPath = path, name, message, delimiter }: {path: string; shownPath?: string; name: string; message: MessageAttachmentContext; delimiter: "," | "\t";}) {+ const fileKey = `${message.threadId}:${message.messageId}:${path}`;const [attempt, setAttempt] = useState(0);const [table, setTable] = useState<TextTable | null>(null);const [error, setError] = useState<string | null>(null);+ const [canOpenOutside, setCanOpenOutside] = useState(false);+ const [allowOutsideFor, setAllowOutsideFor] = useState<string | null>(null);+ const allowOutside = allowOutsideFor === fileKey;useEffect(() => {const controller = new AbortController();let worker: Worker | undefined;setError(null);+ setCanOpenOutside(false);setTable(null);const fail = (reason: string) => {if (!controller.signal.aborted) setError(reason);@@ -69,7 +74,7 @@ export function TableFileContent({ path, shownPath = path, name, message, delimi};void (async () => {try {- const response = await requestMessageFile(path, message, controller.signal);+ const response = await requestMessageFile(path, message, controller.signal, allowOutside ? { allowOutsideWorkspace: true } : undefined);const text = await readTableResponse(response, controller.signal);controller.signal.throwIfAborted();worker = new Worker(new URL("../lib/table-file.worker.ts", import.meta.url), { type: "module" });@@ -80,12 +85,15 @@ export function TableFileContent({ path, shownPath = path, name, message, delimi};worker.onerror = () => fail("format");worker.postMessage({ text, delimiter });- } catch (reason) { fail(refusedAsOutsideWorkspace(reason) ? "outside" : reason instanceof Error && reason.message === "size" ? "size" : "load"); }+ } catch (reason) {+ if (!controller.signal.aborted && refusedAsOutsideWorkspace(reason)) setCanOpenOutside(canOpenOutsideWorkspace(reason));+ fail(refusedAsOutsideWorkspace(reason) ? "outside" : reason instanceof Error && reason.message === "size" ? "size" : "load");+ }})();return () => { controller.abort(); worker?.terminate(); };- }, [path, message.threadId, message.messageId, delimiter, attempt]);+ }, [path, message.threadId, message.messageId, delimiter, attempt, allowOutside]);const data = useMemo(() => table && ({ columns: table.headers.map((text) => ({ text })), rows: table.rows.map((row) => row.map((text) => ({ text }))) }), [table]);- if (error === "outside") return <OutsideWorkspacePreview filePath={shownPath} />;+ if (error === "outside") return <OutsideWorkspacePreview filePath={shownPath} onOpenOutside={canOpenOutside ? () => setAllowOutsideFor(fileKey) : undefined} />;if (error) return <div className="p-8 text-center text-sm"><p role="alert" className="mb-3 text-ink-secondary">{t(error === "size" ? "table.tooLarge" : error === "columns" || error === "format" ? "table.invalid" : "table.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 (!data) 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("table.loading")}</div>;return <RichTable {...data} name={name} expanded />;diff --git a/src/locales/en.json b/src/locales/en.jsonindex aac855d04c..8c6b352728 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3331,6 +3331,8 @@"attach.folderFilesAria": "Files in {name}","attach.folderTruncated": "Only the first files are listed","attach.outsideWorkspace": "This file is outside this chat's working folder, so it can't be saved from here",+ "attach.openOutsideFile": "Open this file",+ "attach.saveOutsideFile": "Save this file","attach.outsideWorkspacePath": "Find this file at this path on the computer running {app}","attach.revealMissing": "That file is no longer there","attach.revealFailed": "Couldn't show that file in its folder. It may have been moved or deleted.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 4165209349..a74c461745 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -3112,6 +3112,8 @@"attach.folderFilesAria": "Arquivos em {name}","attach.folderTruncated": "Só os primeiros arquivos estão listados","attach.outsideWorkspace": "Este arquivo está fora da pasta de trabalho desta conversa, então não pode ser salvo daqui",+ "attach.openOutsideFile": "Abrir este arquivo",+ "attach.saveOutsideFile": "Salvar este arquivo","attach.outsideWorkspacePath": "Encontre este arquivo neste caminho no computador onde o app {app} roda","attach.revealMissing": "Esse arquivo não está mais lá","attach.revealFailed": "Não foi possível mostrar esse arquivo na pasta. Ele pode ter sido movido ou excluído.",