Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(attachments): right-click a bot's attachment to show the original in Finder
AdityaUmale9a4eb92a168a
diff --git a/server/bot-attachment.test.ts b/server/bot-attachment.test.tsindex d28e59f13a..76a743e12d 100644--- a/server/bot-attachment.test.ts+++ b/server/bot-attachment.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { pathToFileURL } from "node:url";@@ -69,6 +69,8 @@ describe("saveBotAttachment", () => {expect(saved.attachment.path.startsWith(ATTACHMENTS_DIR)).toBe(true);expect(readFileSync(saved.attachment.path)).toEqual(bytes);if (saved.attachment.kind === "file") expect(saved.attachment.name.toLowerCase()).toBe(name.toLowerCase());+ // The desktop app shows the original in its folder, not the copy.+ expect(saved.attachment).toMatchObject({ source: realpathSync(join(WORK, name)) });});it("reads a file from the VM guest workspace through its host mount", async () => {@@ -79,7 +81,8 @@ describe("saveBotAttachment", () => {roots: [WORK],guest: { root: "/home/cua/workspace", host: VM_HOME },});- expect(saved.attachment).toMatchObject({ kind: "file", mime: "application/pdf", name: "決算書.pdf" });+ expect(saved.attachment).toMatchObject({ kind: "file", mime: "application/pdf", name: "決算書.pdf",+ source: realpathSync(join(VM_HOME, "reports", "nekoneko.pdf")) });expect(readFileSync(saved.attachment.path, "utf8")).toBe("%PDF-1.4 fake");});@@ -124,7 +127,7 @@ describe("saveBotAttachment for a file a turn saved outside its folders", () =>// Bots on macOS write the URL unencoded; Windows needs a real file URL.const href = process.platform === "win32" ? pathToFileURL(source).href : `file://${source}`;const saved = await saveBotAttachment({ path: href, roots: [WORK], savedThisTurn: { since, refuse } });- expect(saved.attachment).toMatchObject({ kind: "image", mime: "image/jpeg", name: "00_غلاف.jpg" });+ expect(saved.attachment).toMatchObject({ kind: "image", mime: "image/jpeg", name: "00_غلاف.jpg", source: realpathSync(source) });expect(saved.attachment.path.startsWith(ATTACHMENTS_DIR)).toBe(true);expect(readFileSync(saved.attachment.path, "utf8")).toBe("jpeg-bytes");expect(readFileSync(source, "utf8")).toBe("jpeg-bytes");diff --git a/server/bot-attachment.ts b/server/bot-attachment.tsindex f8890510e4..50cdaa6076 100644--- a/server/bot-attachment.ts+++ b/server/bot-attachment.ts@@ -85,7 +85,7 @@ export async function saveBotAttachment(input: SaveBotAttachmentInput): Promise<if (extensionForMime(mime)) {if (file.bytes > IMAGE_MAX_BYTES) throw statusError(413, `image exceeds ${IMAGE_MAX_BYTES} bytes`);const saved = saveImage(await file.handle.readFile(), mime);- return { attachment: { kind: "image", path: saved.path, mime: saved.mime, name }, bytes: saved.bytes };+ return { attachment: { kind: "image", path: saved.path, mime: saved.mime, name, source: file.path }, bytes: saved.bytes };}if (!extensionForFileMime(mime)) {throw statusError(415, `${file.name} is not a supported attachment type. Supported: ${ATTACH_SUPPORTED_TYPES}.`);@@ -94,7 +94,7 @@ export async function saveBotAttachment(input: SaveBotAttachmentInput): Promise<const saved = await saveFile(file.handle.createReadStream({ start: 0, autoClose: false }), name || basename(file.name), mime, {expectedBytes: file.bytes,});- return { attachment: { kind: "file", path: saved.path, mime: saved.mime, name: saved.name }, bytes: saved.bytes };+ return { attachment: { kind: "file", path: saved.path, mime: saved.mime, name: saved.name, source: file.path }, bytes: saved.bytes };} finally {await file.handle.close().catch(() => undefined);}diff --git a/server/message-file.ts b/server/message-file.tsindex 75150adbb1..2c0f058a3c 100644--- a/server/message-file.ts+++ b/server/message-file.ts@@ -17,6 +17,8 @@ export interface OpenedMessageFile {bytes: number;name: string;mime: string;+ /** The canonical host path that was opened. */+ path: string;}export function messageFileRoots(options: {@@ -403,6 +405,7 @@ export async function openMessageFile(href: string, roots: readonly string[]): Pbytes: opened.size,name: basename(canonicalAfter),mime: mimeFor(canonicalAfter),+ path: canonicalAfter,};} catch (error) {await handle?.close().catch(() => undefined);diff --git a/shared/wire.ts b/shared/wire.tsindex 8677bae0f3..9705076a9e 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -467,8 +467,9 @@ export interface WireMessage extends HelperIntroField, SetupCardFields, WaitLine/** Renderers receive only the allowlisted /api/attachments URL. `file`* entries are opened through the message-scoped file route, never by path. */attachments?: Array<- | { kind: "image"; path: string; mime: string; name?: string }- | { kind: "file"; path: string; mime: string; name: string }+ /** `source`: where a bot's attach-file copy came from on the server's computer, for the desktop app's Show in folder. */+ | { kind: "image"; path: string; mime: string; name?: string; source?: string }+ | { kind: "file"; path: string; mime: string; name: string; source?: string }/** `text` is the words the note speaks (secret-redacted when stored): clients show it behind a* collapsed transcript, never as message body, and the model's replay folds it back after `text`. */| { kind: "audio"; path: string; mime: string; durationMs?: number; text?: string }diff --git a/src/components/AttachmentGallery.reply-group.test.ts b/src/components/AttachmentGallery.reply-group.test.tsindex 85e998823a..54c1693600 100644--- a/src/components/AttachmentGallery.reply-group.test.ts+++ b/src/components/AttachmentGallery.reply-group.test.ts@@ -11,7 +11,7 @@ const deliver = (name: string, path = `/store/${name}`) => ({ kind: "file" as codescribe("files under a reply", () => {it("drops a file the text links inline, so it shows once", () => {const text = "Updated [DESIGN_SYSTEM.md](/work/DESIGN_SYSTEM.md) and [MEMORY.md](/work/MEMORY.md).";- expect(replyAttachmentGroup(text, [])).toEqual({ images: [], files: [], delivered: {} });+ expect(replyAttachmentGroup(text, [])).toEqual({ images: [], files: [], delivered: {}, originals: {} });});it("lets an inline link stand for the same file delivered with attach_file", () => {@@ -21,6 +21,11 @@ describe("files under a reply", () => {expect(group.files.map((file) => file.name)).toEqual(["report.pdf"]);});+ it("carries where each attached copy came from, for Show in Finder", () => {+ const group = replyAttachmentGroup("Done.", [{ ...deliver("report.pdf"), source: "/Users/me/Reports/report.pdf" }, deliver("plain.md")]);+ expect(group.originals).toEqual({ "/store/report.pdf": "/Users/me/Reports/report.pdf" });+ });+it("keeps two deliveries with one name as chips, a link can't pick between them", () => {const group = replyAttachmentGroup("[a.md](/work/a.md)", [deliver("a.md", "/store/1"), deliver("a.md", "/store/2")]);expect(group.delivered).toEqual({});diff --git a/src/components/AttachmentGallery.test.ts b/src/components/AttachmentGallery.test.tsindex 19536e0bea..039fbca595 100644--- a/src/components/AttachmentGallery.test.ts+++ b/src/components/AttachmentGallery.test.ts@@ -23,13 +23,24 @@ describe("bot-attached files", () => {{ path: "/store/bbbb.mp3", name: "song.mp3", private: true },{ path: "/store/cccc.pptx", name: "deck.pptx", private: true },],+ originals: {},});- expect(splitMessageAttachments(undefined)).toEqual({ images: [], files: [] });+ expect(splitMessageAttachments(undefined)).toEqual({ images: [], files: [], originals: {} });expect(splitMessageAttachments([...attachments, { kind: "audio", path: "/store/voice.mp3" }, { kind: "future", path: "/store/unknown" },])).toEqual(splitMessageAttachments(attachments));});+ it("remembers the original of each image and file a bot attached, never of a voice note", () => {+ const split = splitMessageAttachments([+ { ...attachments[0]!, source: "/Users/me/Pictures/chart.png" },+ { ...attachments[2]!, source: "C:\\Users\\me\\deck.pptx" },+ { kind: "audio", path: "/store/voice.mp3", source: "/Users/me/voice.mp3" },+ ]);+ expect(split.originals).toEqual({ "/store/aaaa.png": "/Users/me/Pictures/chart.png", "/store/cccc.pptx": "C:\\Users\\me\\deck.pptx" });+ expect(split.images).toEqual(["/store/aaaa.png"]);+ });+it("shows an attached clip as a play button and a deck as a save chip, without repeating a linked one", () => {const render = (text: string) => renderToStaticMarkup(createElement(MessageAttachmentGallery, { text, attachments, message }));const html = render("");diff --git a/src/components/AttachmentGallery.tsx b/src/components/AttachmentGallery.tsxindex f1de8912c9..baa2fe86de 100644--- a/src/components/AttachmentGallery.tsx+++ b/src/components/AttachmentGallery.tsx@@ -18,6 +18,7 @@ import {type MessageAttachmentContext,type PreviewImage,} from "./AttachmentPreview";+import { useRevealOriginalMenu } from "./RevealOriginalMenu";export interface GalleryFile extends TranscriptFileAttachment {linked?: boolean;@@ -72,23 +73,29 @@ export function isAudioAttachment(path: string): boolean {return /\.(?:mp3|m4a|aac|wav|ogg|oga|opus|flac)$/i.test(fileIdentity(path));}-type MessageAttachmentEntry = { path: string; kind?: string; name?: string };+type MessageAttachmentEntry = { path: string; kind?: string; name?: string; source?: string };+/** A bot's attach-file copy path -> the original it was copied from, for the desktop app's Show in Finder / folder. */+export type AttachmentOriginals = Readonly<Record<string, string>>;+const originalOf = (originals: AttachmentOriginals | undefined, path: string) => originals && Object.hasOwn(originals, path) ? originals[path] : undefined;const NO_GENERATED_ATTACHMENTS: readonly MessageAttachmentEntry[] = [];-export function splitMessageAttachments(attachments: readonly MessageAttachmentEntry[] = NO_GENERATED_ATTACHMENTS): { images: string[]; files: GalleryFile[] } {+export function splitMessageAttachments(attachments: readonly MessageAttachmentEntry[] = NO_GENERATED_ATTACHMENTS): { images: string[]; files: GalleryFile[]; originals: AttachmentOriginals } {const images: string[] = [];const files: GalleryFile[] = [];+ const originals: Record<string, string> = {};for (const attachment of attachments) {+ if (attachment.source && (attachment.kind === "file" || attachment.kind === "image")) originals[attachment.path] = attachment.source;if (attachment.kind === "file") files.push({ path: attachment.path, name: attachment.name || attachmentBasename(attachment.path), private: true });else if (attachment.kind === "image" || attachment.kind === undefined) images.push(attachment.path);}- return { images, files };+ return { images, files, originals };}export function replyAttachmentGroup(text: string, attachments: readonly MessageAttachmentEntry[] = NO_GENERATED_ATTACHMENTS): {images: string[];files: GalleryFile[];delivered: Record<string, string>;+ originals: AttachmentOriginals;} {const attached = splitMessageAttachments(attachments);const links = collectMessageFiles(text);@@ -106,7 +113,7 @@ export function replyAttachmentGroup(text: string, attachments: readonly Messageif (Object.hasOwn(delivered, link.name) || taken.has(fileIdentity(link.path))) continue;if (isVideoAttachment(link.path) || isAudioAttachment(link.path)) files.push(link);}- return { images: attached.images, files, delivered };+ return { images: attached.images, files, delivered, originals: attached.originals };}export function MessageAttachmentGallery({ text, attachments = NO_GENERATED_ATTACHMENTS, message, eager, className }: {@@ -121,7 +128,7 @@ export function MessageAttachmentGallery({ text, attachments = NO_GENERATED_ATTA() => [...attached.files, ...collectMessageFiles(text, [...attached.images, ...attached.files.map((file) => file.path)])],[text, attached],);- return <AttachmentGallery images={attached.images} files={files} message={message} eager={eager} className={className} />;+ return <AttachmentGallery images={attached.images} files={files} originals={attached.originals} message={message} eager={eager} className={className} />;}const MEDIA_STALL_MS = 15_000;@@ -384,16 +391,17 @@ function AudioAttachment({ file, message }: { file: GalleryFile; message: Messag);}-type GalleryItem = { key: string } & (+type GalleryItem = { key: string; source?: string } & (| { kind: "image"; image: PreviewImage }| { kind: "video" | "audio" | "file"; file: GalleryFile });const BENEATH_LIMIT = 6;-export function AttachmentGallery({ images = [], files = [], message, eager = false, beneath = false, className }: {+export function AttachmentGallery({ images = [], files = [], originals, message, eager = false, beneath = false, className }: {images?: Array<string | TranscriptImageAttachment>;files?: GalleryFile[];+ originals?: AttachmentOriginals;message?: MessageAttachmentContext;eager?: boolean;beneath?: boolean;@@ -412,18 +420,20 @@ export function AttachmentGallery({ images = [], files = [], message, eager = faconst image = typeof reference === "string" || reference.private? previewImage(path, typeof reference === "string" ? undefined : reference.name): null;- if (image) result.push({ key, kind: "image", image });- else result.push({ key, kind: "file", file: typeof reference === "string" ? { path, name: attachmentBasename(path) } : reference });+ const source = originalOf(originals, path);+ if (image) result.push({ key, source, kind: "image", image });+ else result.push({ key, source, kind: "file", file: typeof reference === "string" ? { path, name: attachmentBasename(path) } : reference });}for (const file of files) {const key = fileIdentity(file.path);if (seen.has(key)) continue;seen.add(key);const trusted = Boolean(message && (file.private || file.linked));- result.push({ key, kind: trusted && isVideoAttachment(file.path) ? "video" : trusted && isAudioAttachment(file.path) ? "audio" : "file", file });+ result.push({ key, source: originalOf(originals, file.path), kind: trusted && isVideoAttachment(file.path) ? "video" : trusted && isAudioAttachment(file.path) ? "audio" : "file", file });}return result;- }, [images, files, message]);+ }, [images, files, originals, message]);+ const reveal = useRevealOriginalMenu();if (!items.length) return null;const limit = beneath ? BENEATH_LIMIT : 4;const shown = expanded ? items : items.slice(0, limit);@@ -444,7 +454,7 @@ export function AttachmentGallery({ images = [], files = [], message, eager = fa{thumbs.length > 0 && (<div className="flex max-w-full flex-wrap gap-2">{thumbs.map((item) => item.kind === "image" && (- <div key={item.key} className="min-w-0" title={item.image.name}>+ <div key={item.key} className="min-w-0" title={item.image.name} {...reveal.targetProps(item.source)}><AttachmentThumbnail key={item.image.src} image={item.image} eager={eager} onPreview={() => setSelected(item.image)} className="h-24 w-auto max-w-48 rounded-2xl border-0" /></div>))}@@ -453,15 +463,15 @@ export function AttachmentGallery({ images = [], files = [], message, eager = fa{videos.length > 0 && message && (<div className={cn("grid w-[min(34rem,70vw)] max-w-full gap-2", videos.length === 1 ? "grid-cols-1" : "grid-cols-2")}>{videos.map((item) => item.kind === "video" && (- <VideoAttachment key={`${message.threadId}:${message.messageId}:${item.key}`} file={item.file} message={message} />+ <span key={`${message.threadId}:${message.messageId}:${item.key}`} className="contents" {...reveal.targetProps(item.source)}><VideoAttachment file={item.file} message={message} /></span>))}</div>)}{(rest.length > 0 || items.length > limit) && (<div className="flex max-w-full flex-wrap items-start gap-1.5">{rest.map((item) => item.kind === "audio" && message- ? <AudioAttachment key={`${message.threadId}:${message.messageId}:${item.key}`} file={item.file} message={message} />- : item.kind === "file" && <AttachedFileChip key={item.key} file={item.file} linked={item.file.linked} message={message} compact />)}+ ? <span key={`${message.threadId}:${message.messageId}:${item.key}`} className="contents" {...reveal.targetProps(item.source)}><AudioAttachment file={item.file} message={message} /></span>+ : item.kind === "file" && <span key={item.key} className="contents" {...reveal.targetProps(item.source)}><AttachedFileChip file={item.file} linked={item.file.linked} message={message} compact /></span>)}{items.length > limit && (<button type="button" onClick={() => setExpanded(!expanded)} aria-expanded={expanded} className="inline-flex h-7 items-center rounded-full px-2.5 text-[13px] leading-none text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus">{expanded ? t("attach.showLess") : t("attach.moreCount", { count: items.length - limit })}@@ -469,7 +479,7 @@ export function AttachmentGallery({ images = [], files = [], message, eager = fa)}</div>)}- {dialog}+ {dialog}{reveal.menu}</section>);}@@ -479,19 +489,19 @@ export function AttachmentGallery({ images = [], files = [], message, eager = fa{media.length > 0 && (<div className={cn("grid gap-2", media.length === 1 ? "grid-cols-1" : "grid-cols-2")}>{media.map((item) => item.kind === "image" ? (- <div key={item.key} className="min-w-0" title={item.image.name}>+ <div key={item.key} className="min-w-0" title={item.image.name} {...reveal.targetProps(item.source)}><AttachmentThumbnail key={item.image.src} image={item.image} eager={eager} onPreview={() => setSelected(item.image)} className="max-h-72 rounded-2xl border-0 bg-transparent" /></div>) : item.kind === "video" && message ? (- <VideoAttachment key={`${message.threadId}:${message.messageId}:${item.key}`} file={item.file} message={message} />+ <span key={`${message.threadId}:${message.messageId}:${item.key}`} className="contents" {...reveal.targetProps(item.source)}><VideoAttachment file={item.file} message={message} /></span>) : null)}</div>)}{documents.length > 0 && (<div className="flex flex-col items-start gap-1.5">{documents.map((item) => item.kind === "audio" && message- ? <AudioAttachment key={`${message.threadId}:${message.messageId}:${item.key}`} file={item.file} message={message} />- : item.kind === "file" && <AttachedFileChip key={item.key} file={item.file} linked={item.file.linked} message={message} className="max-w-none rounded-xl border-hairline/25 bg-transparent" />)}+ ? <span key={`${message.threadId}:${message.messageId}:${item.key}`} className="contents" {...reveal.targetProps(item.source)}><AudioAttachment file={item.file} message={message} /></span>+ : item.kind === "file" && <span key={item.key} className="contents" {...reveal.targetProps(item.source)}><AttachedFileChip file={item.file} linked={item.file.linked} message={message} className="max-w-none rounded-xl border-hairline/25 bg-transparent" /></span>)}</div>)}{items.length > limit && (@@ -500,7 +510,7 @@ export function AttachmentGallery({ images = [], files = [], message, eager = fa{expanded ? t("attach.showLess") : t("attach.showMore", { count: items.length - limit })}</button>)}- {dialog}+ {dialog}{reveal.menu}</section>);}diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 9345ff29c3..1a2de51710 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -549,7 +549,7 @@ const Bubble = memo(function Bubble({))}</div>)}- {!group && <AttachmentGallery images={generatedPaths} files={linkedFiles} message={{ threadId, messageId: message.id }} className={text ? undefined : "mb-0"} eager={eagerAttachments} />}+ {!group && <AttachmentGallery images={generatedPaths} files={linkedFiles} originals={attached.originals} message={{ threadId, messageId: message.id }} className={text ? undefined : "mb-0"} eager={eagerAttachments} />}{split ? (<ConversationalReply simple={simple} join={join} segments={reply.segments} firstNew={reply.firstNew} citation={{ messageId: message.id, botId, threadId }}renderSegment={(segment) => <ChatMarkdown text={segment} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} />} />@@ -561,7 +561,7 @@ const Bubble = memo(function Bubble({) : text ? (<div data-citation-source={message.id} data-citation-owner-type="bot" data-citation-owner={botId} data-citation-thread={threadId}><ChatMarkdown text={text} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} /></div>) : null}- {group && <AttachmentGallery images={group.images} files={group.files} message={{ threadId, messageId: message.id }} eager={eagerAttachments} beneath />}+ {group && <AttachmentGallery images={group.images} files={group.files} originals={group.originals} message={{ threadId, messageId: message.id }} eager={eagerAttachments} beneath />}</MessageBoundary>)}</div>diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsxindex 13036fec3d..8acda164bb 100644--- a/src/components/GroupView.tsx+++ b/src/components/GroupView.tsx@@ -293,7 +293,7 @@ function RoomTextMessage({) : botText ? (<div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={group.id} data-citation-thread={group.threadId}><ChatMarkdown text={botText} mentionPeers={peers} everyone={!group.dm} mentionPerson={{ profileName: state.config?.profile?.name }} message={{ threadId: group.threadId, messageId: m.id }} delivered={replyGroup?.delivered} /></div>) : null}- {replyGroup && <AttachmentGallery images={replyGroup.images} files={replyGroup.files} message={{ threadId: group.threadId, messageId: m.id }} eager={eager} beneath />}+ {replyGroup && <AttachmentGallery images={replyGroup.images} files={replyGroup.files} originals={replyGroup.originals} message={{ threadId: group.threadId, messageId: m.id }} eager={eager} beneath />}</MessageBoundary>)}</div>diff --git a/src/components/RevealOriginalMenu.test.ts b/src/components/RevealOriginalMenu.test.tsnew file mode 100644index 0000000000..8fddf616f2--- /dev/null+++ b/src/components/RevealOriginalMenu.test.ts@@ -0,0 +1,44 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { canRevealOriginal, revealOriginal, revealOriginalLabel } from "./RevealOriginalMenu";++afterEach(() => vi.unstubAllGlobals());++const shown = vi.fn(async () => "shown" as const);++describe("Show in Finder for the original of a bot's attachment", () => {+ it("is offered only in the desktop app on this computer, for a local absolute path", () => {+ expect(canRevealOriginal("/Users/me/Reports/q3.pdf", shown)).toBe(true);+ expect(canRevealOriginal("C:\\Users\\me\\q3.pdf", shown)).toBe(true);+ expect(canRevealOriginal(undefined, shown)).toBe(false);+ expect(canRevealOriginal("q3.pdf", shown)).toBe(false);+ expect(canRevealOriginal("//server/share/q3.pdf", shown)).toBe(false);+ expect(canRevealOriginal("/Users/me/Reports/q3.pdf", undefined)).toBe(false);+ });++ it("reads the desktop bridge, and a window connected to another computer has none", () => {+ expect(canRevealOriginal("/Users/me/q3.pdf")).toBe(false);+ vi.stubGlobal("window", { ogb: { revealInFolder: shown } });+ expect(canRevealOriginal("/Users/me/q3.pdf")).toBe(true);+ vi.stubGlobal("window", { ogb: { revealInFolder: shown, remoteClient: { active: true } } });+ expect(canRevealOriginal("/Users/me/q3.pdf")).toBe(false);+ });++ it("says Finder on a Mac and folder elsewhere", () => {+ expect(revealOriginalLabel("darwin")).toBe("Show in Finder");+ expect(revealOriginalLabel("win32")).toBe("Show in folder");+ expect(revealOriginalLabel("linux")).toBe("Show in folder");+ });++ it("shows the original, and says so when it moved or is gone instead of falling back to the copy", async () => {+ const reveal = vi.fn(async (_path: string) => "shown" as "shown" | "missing" | "invalid");+ expect(await revealOriginal("/Users/me/q3.pdf", reveal)).toBe("");+ expect(reveal).toHaveBeenCalledWith("/Users/me/q3.pdf");+ reveal.mockResolvedValueOnce("missing");+ expect(await revealOriginal("/Users/me/q3.pdf", reveal)).toBe("The original file was moved or deleted");+ reveal.mockResolvedValueOnce("invalid");+ expect(await revealOriginal("/Users/me/q3.pdf", reveal)).toMatch(/Couldn't show that file/);+ reveal.mockRejectedValueOnce(new Error("ipc"));+ expect(await revealOriginal("/Users/me/q3.pdf", reveal)).toMatch(/Couldn't show that file/);+ expect(reveal).toHaveBeenCalledTimes(4);+ });+});diff --git a/src/components/RevealOriginalMenu.tsx b/src/components/RevealOriginalMenu.tsxnew file mode 100644index 0000000000..312808a26e--- /dev/null+++ b/src/components/RevealOriginalMenu.tsx@@ -0,0 +1,77 @@+// Right-click on a file a bot attached shows the original it was copied from in Finder or the file manager, never the+// app's own copy: an original that moved or is gone says so. Only the desktop app on the computer that holds the file+// offers it; a phone, the web or a window connected to another computer gets no menu.+import { useEffect, useRef, useState, type MouseEvent } from "react";+import { createPortal } from "react-dom";+import { FolderOpen } from "lucide-react";+import { t } from "@/lib/i18n";+import { cn } from "@/lib/cn";+import { MENU_ITEM, MENU_SHEET } from "./menu-recipe";++const REVEALABLE_PATH = /^(?:\/(?!\/)|[a-zA-Z]:[\\/])/;+const ITEM_CLASS = `${MENU_ITEM} text-ink hover:bg-menu-hover [&>svg]:text-ink-secondary`;++type Reveal = NonNullable<NonNullable<Window["ogb"]>["revealInFolder"]>;++function revealBridge(): Reveal | undefined {+ const ogb = typeof window === "undefined" ? undefined : window.ogb;+ return ogb?.remoteClient?.active ? undefined : ogb?.revealInFolder;+}++export function canRevealOriginal(source: string | undefined, reveal: Reveal | undefined = revealBridge()): source is string {+ return Boolean(reveal) && typeof source === "string" && REVEALABLE_PATH.test(source);+}++export function revealOriginalLabel(platform: string | undefined): string {+ return t(platform === "darwin" ? "attach.showInFinder" : "attach.showInFolder");+}++/** Empty when shown; otherwise what to tell the person. */+export async function revealOriginal(source: string, reveal: Reveal): Promise<string> {+ try {+ const result = await reveal(source);+ return result === "shown" ? "" : t(result === "missing" ? "attach.originalMissing" : "attach.revealFailed");+ } catch {+ return t("attach.revealFailed");+ }+}++export function useRevealOriginalMenu() {+ const [at, setAt] = useState<{ left: number; top: number; source: string; problem?: string } | null>(null);+ const menuRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!at) return;+ menuRef.current?.querySelector<HTMLButtonElement>("button")?.focus();+ const close = (event: Event) => { if (!(event.target instanceof Node && menuRef.current?.contains(event.target))) setAt(null); };+ window.addEventListener("mousedown", close);+ window.addEventListener("scroll", close, true);+ return () => { window.removeEventListener("mousedown", close); window.removeEventListener("scroll", close, true); };+ }, [at]);+ const reveal = revealBridge();+ const label = revealOriginalLabel(typeof window === "undefined" ? undefined : window.ogb?.platform);+ const show = async (source: string) => {+ const problem = reveal ? await revealOriginal(source, reveal) : t("attach.revealFailed");+ setAt((current) => current?.source !== source ? current : problem ? { ...current, problem } : null);+ };+ return {+ /** Spread onto the element that holds one attachment. */+ targetProps: (source: string | undefined) => !canRevealOriginal(source, reveal) ? {} : {+ onContextMenu: (event: MouseEvent<HTMLElement>) => {+ event.preventDefault();+ event.stopPropagation();+ setAt({ left: Math.max(8, Math.min(event.clientX, window.innerWidth - 268)), top: Math.max(8, Math.min(event.clientY, window.innerHeight - 110)), source });+ },+ },+ menu: at && createPortal(+ <div ref={menuRef} role="group" aria-label={label} style={{ left: at.left, top: at.top }}+ className={cn("fixed z-50 w-[260px]", MENU_SHEET)}+ onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setAt(null); } }}>+ <button type="button" onClick={() => void show(at.source)} title={at.source} className={ITEM_CLASS}>+ <FolderOpen size={16} />{label}+ </button>+ {at.problem && <p role="alert" className="px-2 pb-1 text-[13px] leading-[18px] text-danger">{at.problem}</p>}+ </div>,+ document.body,+ ),+ };+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 6454005cd9..4caaa04657 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2795,6 +2795,8 @@"attach.downloading": "Downloading…","attach.downloaded": "Downloaded","attach.showInFolder": "Show in folder",+ "attach.showInFinder": "Show in Finder",+ "attach.originalMissing": "The original file was moved or deleted","attach.folderEmpty": "This folder has no files to open here","attach.folderFilesAria": "Files in {name}","attach.folderTruncated": "Only the first files are listed",