AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(desktop): open attachment copies in system applications (#768)
tianma-if56c684891343
diff --git a/apps/desktop/src/main/attachment-open.mjs b/apps/desktop/src/main/attachment-open.mjsnew file mode 100644index 00000000..3e0c6406--- /dev/null+++ b/apps/desktop/src/main/attachment-open.mjs@@ -0,0 +1,112 @@+import { createWriteStream } from "node:fs";+import { mkdir, mkdtemp, readdir, rm, stat } from "node:fs/promises";+import { extname, join } from "node:path";+import { pipeline } from "node:stream/promises";+import { isSafeResourceId } from "./resource-url.mjs";+import { restrictDirectory, restrictFile } from "./file-permissions.mjs";++// Only document/media formats: never hand scripts, shortcuts, executables or+// unknown file types to an OS handler. Those remain available via Download.+const OPENABLE_EXTENSIONS = new Set((+ "pdf txt md markdown csv tsv json xml log rtf doc docx odt xls xlsx ods ppt pptx odp "+ + "png jpg jpeg gif webp avif bmp tif tiff heic heif svg ico "+ + "mp3 m4a aac wav ogg flac opus aiff mp4 m4v mov webm mkv avi wmv "+ + "zip 7z rar tar gz bz2 xz epub"+).split(" "));+const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;++export const attachmentOpenInput = (input) => {+ if (typeof input?.url !== "string" || input.url.length > 1024+ || typeof input.filename !== "string" || input.filename.length > 1024) return null;+ try {+ const url = new URL(input.url);+ if (url.username || url.password || url.port || url.search || url.hash) return null;+ const staged = url.protocol === "edgeever-staged:";+ if (staged ? !url.hostname || !["", "/"].includes(url.pathname)+ : url.protocol !== "edgeever-resource:" || url.hostname !== "resource") return null;+ const id = decodeURIComponent(staged ? url.hostname : url.pathname.slice(1));+ if (!isSafeResourceId(id)) return null;+ // Treat the supplied label as a filename, never as a path. Remove Windows+ // special characters, trailing dots/spaces and Unicode direction controls.+ const base = input.filename.split(/[\\/]/).pop() || "";+ // oxlint-disable-next-line no-control-regex -- sanitize cross-platform filenames+ let filename = base.replace(/[\u0000-\u001f\u007f<>:"|?*\u202a-\u202e\u2066-\u2069]/g, "_")+ .trim().replace(/[. ]+$/, "");+ const extension = extname(filename);+ if (!OPENABLE_EXTENSIONS.has(extension.slice(1).toLowerCase())) return { blocked: true };+ // Bound UTF-8 length while retaining the full extension, including on Windows.+ let stem = filename.slice(0, -extension.length).replace(/[. ]+$/, "");+ while (Buffer.byteLength(stem) > 120) stem = Array.from(stem).slice(0, -1).join("");+ if (!stem || /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(stem.normalize("NFKC"))) stem = `attachment_${stem}`;+ filename = stem + extension;+ return { url: staged ? `edgeever-staged://${id}` : `edgeever-resource://resource/${id}`, filename };+ } catch { return null; }+};++const cleanupOpenedAttachments = async (directory) => {+ const entries = await readdir(directory, { withFileTypes: true });+ for (const entry of entries) {+ if (!entry.isDirectory() || !entry.name.startsWith("open-")) continue;+ const path = join(directory, entry.name);+ // Use the newer of creation and file modification times so externally edited+ // copies survive for at least a week after their last change.+ const children = await readdir(path).catch(() => []);+ const times = await Promise.all([path, ...children.map((name) => join(path, name))]+ .map((item) => stat(item).then((info) => info.mtimeMs).catch(() => Date.now())));+ if (Math.max(...times) < Date.now() - RETENTION_MS) await rm(path, { recursive: true, force: true });+ }+};++export const registerAttachmentOpenIpc = (ipcMain, options) => {+ const pending = new Map();+ ipcMain.handle("desktop:open-attachment", async (event, input) => {+ try { options.authorize(event); } catch { return { ok: false, code: "forbidden" }; }+ const parsed = attachmentOpenInput(input);+ if (!parsed) return { ok: false, code: "forbidden" };+ if (parsed.blocked) return { ok: false, code: "blocked" };+ const scope = options.getScope();+ const directory = options.getDirectory();+ const key = JSON.stringify([directory, parsed.url, parsed.filename]);+ if (pending.has(key)) return pending.get(key);+ const assertCurrent = () => {+ try { options.authorize(event); } catch { throw Object.assign(new Error("Attachment open forbidden"), { code: "forbidden" }); }+ if (scope !== options.getScope()) throw Object.assign(new Error("Attachment account changed"), { code: "forbidden" });+ };+ const operation = (async () => {+ let folder;+ let response;+ let failureCode = "unavailable";+ try {+ await mkdir(directory, { recursive: true, mode: 0o700 });+ await restrictDirectory(directory);+ await cleanupOpenedAttachments(directory).catch(() => {});+ assertCurrent();+ const signal = AbortSignal.timeout(120_000);+ response = await options.readResource(parsed.url, signal, assertCurrent);+ try { assertCurrent(); } catch (error) { await response.body?.cancel(); throw error; }+ if (!response.ok || !response.body) {+ await response.body?.cancel();+ return { ok: false, code: "unavailable" };+ }+ // Unique copies avoid overwriting a file being edited in another app.+ folder = await mkdtemp(join(directory, "open-"));+ await restrictDirectory(folder);+ const path = join(folder, parsed.filename);+ await pipeline(response.body, createWriteStream(path, { flags: "wx", mode: 0o600 }), { signal });+ await restrictFile(path);+ assertCurrent();+ failureCode = "open-failed";+ const error = await options.openPath(path);+ if (error) throw new Error(error);+ // External applications can read lazily; do not remove on return/quit.+ return { ok: true };+ } catch (error) {+ await response?.body?.cancel().catch(() => {});+ if (folder) await rm(folder, { recursive: true, force: true }).catch(() => {});+ return { ok: false, code: error?.code === "forbidden" ? "forbidden" : failureCode };+ }+ })();+ pending.set(key, operation);+ try { return await operation; } finally { pending.delete(key); }+ });+};diff --git a/apps/desktop/src/main/attachment-open.test.mjs b/apps/desktop/src/main/attachment-open.test.mjsnew file mode 100644index 00000000..a8bbb9df--- /dev/null+++ b/apps/desktop/src/main/attachment-open.test.mjs@@ -0,0 +1,162 @@+import { afterEach, expect, test } from "bun:test";+import { mkdtemp, readFile, readdir, rm, stat, utimes, mkdir, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { basename, join } from "node:path";+import { runInNewContext } from "node:vm";+import { attachmentOpenInput, registerAttachmentOpenIpc } from "./attachment-open.mjs";++const directories = [];+afterEach(async () => { await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))); });+const input = { url: "edgeever-resource://resource/res_1", filename: "训练.xlsx" };+const fixture = async (overrides = {}) => {+ const directory = await mkdtemp(join(tmpdir(), "edgeever-open-test-"));+ directories.push(directory);+ let handler;+ const opened = [];+ const reads = [];+ const options = {+ authorize: () => {}, getScope: () => "account-1", getDirectory: () => directory,+ readResource: async (url) => { reads.push(url); return new Response("attachment bytes"); },+ openPath: async (path) => { opened.push(path); return ""; },+ ...overrides,+ };+ registerAttachmentOpenIpc({ handle: (channel, value) => { expect(channel).toBe("desktop:open-attachment"); handler = value; } }, options);+ return { directory, opened, reads, options, open: (value = input) => handler({}, value) };+};++test("accepts document/media/archive types and preserves safe extensions", () => {+ for (const filename of ["训练.xlsx", "old.xls", "plan.docx", "old.doc", "slides.pptx", "report.pdf", "archive.zip", "clip.mp4", "sound.mp3", "notes.txt"]) {+ expect(attachmentOpenInput({ ...input, filename })).toEqual({ ...input, filename });+ }+ for (const filename of ["program.exe", "file.pdf.exe", "run.sh", "run.command", "run.bat", "app.desktop", "link.lnk", "setup.msi", "code.js", "file", "unknown.bin", "file.hta", "open.url"]) {+ expect(attachmentOpenInput({ ...input, filename })).toEqual({ blocked: true });+ }+ expect(attachmentOpenInput({ ...input, filename: "../../CON.xlsx" }).filename).toBe("attachment_CON.xlsx");+ expect(attachmentOpenInput({ ...input, filename: "COM¹.pdf" }).filename).toBe("attachment_COM¹.pdf");+ expect(attachmentOpenInput({ ...input, filename: "NUL .txt" }).filename).toBe("attachment_NUL.txt");+ expect(attachmentOpenInput({ ...input, filename: 'C:\\folder\\a:b?.pdf. ' }).filename).toBe("a_b_.pdf");+ expect(attachmentOpenInput({ ...input, filename: "文".repeat(200) + ".xlsx" }).filename.endsWith(".xlsx")).toBe(true);+});++test("rejects arbitrary paths, network URLs and malformed internal resource addresses", () => {+ for (const url of ["file:///etc/passwd", "https://example.org/file.xlsx", "edgeever-resource://evil/res_1", "edgeever-resource://user@resource/res_1", "edgeever-resource://resource/res_1?download=a.xlsx", "edgeever-resource://resource/res_1#x", "edgeever-resource://resource/%2fetc", "edgeever-resource://resource/%2e%2e", "edgeever-staged://pending/evil", "edgeever-staged://pending:123", "edgeever-resource://resource/%zz"]) {+ expect(attachmentOpenInput({ ...input, url })).toBeNull();+ }+});++test("streams complete bytes to a private, named copy before asking the OS to open it", async () => {+ const context = await fixture();+ expect(await context.open()).toEqual({ ok: true });+ const path = context.opened[0];+ expect(basename(path)).toBe("训练.xlsx");+ expect(await readFile(path, "utf8")).toBe("attachment bytes");+ expect(context.reads).toEqual([input.url]);+ if (process.platform !== "win32") expect((await stat(path)).mode & 0o777).toBe(0o600);+ await writeFile(path, "edited externally");+ expect(await context.open()).toEqual({ ok: true });+ expect(context.opened[1]).not.toBe(path);+ expect(await readFile(path, "utf8")).toBe("edited externally");+});++test("staged attachments use the same path without requiring an HTTP URL", async () => {+ const context = await fixture();+ expect(await context.open({ url: "edgeever-staged://stage_1", filename: "offline.docx" })).toEqual({ ok: true });+ expect(context.reads).toEqual(["edgeever-staged://stage_1"]);+ expect(basename(context.opened[0])).toBe("offline.docx");+});++test("failed retrieval/offline cache misses and missing OS associations return visible error codes", async () => {+ for (const status of [401, 404, 504]) {+ const context = await fixture({ readResource: async () => new Response("missing", { status }) });+ expect(await context.open()).toEqual({ ok: false, code: "unavailable" });+ expect(context.opened).toEqual([]);+ expect(await readdir(context.directory)).toEqual([]);+ }+ const context = await fixture({ openPath: async () => "No application is associated with this file" });+ expect(await context.open()).toEqual({ ok: false, code: "open-failed" });+ expect(await readdir(context.directory)).toEqual([]);+});++test("partial downloads are never opened and their temporary files are removed", async () => {+ let chunks = 0;+ const context = await fixture({ readResource: async () => new Response(new ReadableStream({+ pull(controller) { if (++chunks === 1) controller.enqueue(new Uint8Array([1, 2])); else controller.error(new Error("Disconnected")); },+ })) });+ expect(await context.open()).toEqual({ ok: false, code: "unavailable" });+ expect(context.opened).toEqual([]);+ expect(await readdir(context.directory)).toEqual([]);+});++test("rejects unauthorized requests and blocked types before reading bytes", async () => {+ const context = await fixture();+ expect(await context.open({ ...input, filename: "run.exe" })).toEqual({ ok: false, code: "blocked" });+ context.options.authorize = () => { throw new Error("Untrusted frame"); };+ expect(await context.open()).toEqual({ ok: false, code: "forbidden" });+ expect(context.reads).toEqual([]);+});++test("rechecks account and sender after async retrieval, cancels the body and never opens another workspace's file", async () => {+ for (const changeScope of [true, false]) {+ let scope = "account-1";+ let authorized = true;+ let cancelled = false;+ const context = await fixture({+ getScope: () => scope,+ authorize: () => { if (!authorized) throw new Error("Window closed"); },+ readResource: async () => {+ if (changeScope) scope = "account-2"; else authorized = false;+ return new Response(new ReadableStream({ cancel() { cancelled = true; } }));+ },+ });+ expect(await context.open()).toEqual({ ok: false, code: "forbidden" });+ expect(context.opened).toEqual([]);+ expect(cancelled).toBe(true);+ }+});++test("concurrent clicks open one copy, and a subsequent click can retry", async () => {+ let finish;+ let reads = 0;+ const ready = new Promise((resolve) => { finish = resolve; });+ const context = await fixture({ readResource: async () => { reads++; await ready; return new Response("bytes"); } });+ const first = context.open();+ const second = context.open();+ finish();+ expect(await first).toEqual({ ok: true });+ expect(await second).toEqual({ ok: true });+ expect(reads).toBe(1);+ expect(context.opened).toHaveLength(1);+ await context.open();+ expect(context.opened).toHaveLength(2);+});++test("cleans old copies, retaining recent copies and recently edited files", async () => {+ const context = await fixture();+ const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000);+ for (const name of ["open-old", "open-edited", "open-recent", "unrelated"]) {+ const folder = join(context.directory, name);+ await mkdir(folder); await writeFile(join(folder, "notes.txt"), "notes");+ if (name !== "open-recent") await utimes(folder, old, old);+ if (name !== "open-edited") await utimes(join(folder, "notes.txt"), old, old);+ }+ await context.open();+ const entries = await readdir(context.directory);+ expect(entries).not.toContain("open-old");+ for (const name of ["open-edited", "open-recent", "unrelated"]) expect(entries).toContain(name);+});++test("preload only invokes attachment opening during isolated user activation", async () => {+ const source = await readFile(new URL("../preload/index.cjs", import.meta.url), "utf8");+ let bridge;+ const calls = [];+ const userActivation = { isActive: false };+ runInNewContext(source, { navigator: { userActivation }, require: () => ({+ contextBridge: { exposeInMainWorld: (_name, value) => { bridge = value; } },+ ipcRenderer: { sendSync: () => undefined, invoke: (...args) => { calls.push(args); return Promise.resolve({ ok: true }); } },+ }) });+ expect(await bridge.openAttachment(input)).toEqual({ ok: false, code: "forbidden" });+ expect(calls).toEqual([]);+ userActivation.isActive = true;+ expect(await bridge.openAttachment(input)).toEqual({ ok: true });+ expect(calls).toEqual([["desktop:open-attachment", input]]);+});diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjsindex e21f9434..c5e2eb94 100644--- a/apps/desktop/src/main/index.mjs+++ b/apps/desktop/src/main/index.mjs@@ -42,6 +42,7 @@ import { formatGlobalShortcutForHumans, globalShortcutAccelerator, globalShortcuimport { trayIconPath } from "./tray-icon.mjs";import { writeFileClipboard, writeImageClipboard, writeRichClipboard, writeTextClipboard } from "./clipboard-write.mjs";import { registerClipboardReadIpc } from "./clipboard-read.mjs";+import { registerAttachmentOpenIpc } from "./attachment-open.mjs";import { captureRegionScreenToNote, captureScreenToNote, createScreenshotCaptureGuard, screenshotImportIpcPayload, writeScreenshotTempPath } from "./screenshot-capture.mjs";import { cancelScreenshotRegionSelection, openScreenshotRegionSelector } from "./screenshot-region.mjs";import { LocalDataResetError, scheduleMacLocalDataReset } from "./local-data-reset.mjs";@@ -1021,7 +1022,8 @@ const createTray = () => {tray.on("double-click", () => showWindow(mainWindow));};-const handleResourceProtocolRequest = async (request) => {+const handleResourceProtocolRequest = async (request, assertCurrent = () => {}) => {+ assertCurrent();const resourceId = resourceIdFromRequest(request.url);if (!resourceId) return new Response("Invalid resource", { status: 400 });const downloadDisposition = downloadContentDispositionFromRequest(request.url);@@ -1065,12 +1067,14 @@ const handleResourceProtocolRequest = async (request) => {if (!configuredApiBaseUrl) return new Response("Resource is not cached", { status: 504 });const sourceUrl = `${configuredApiBaseUrl}/api/v1/resources/${encodeURIComponent(resourceId)}/blob`;try {+ assertCurrent();const sessionToken = credentialForUrl(desktopSessionToken, desktopSessionTokenOrigin, sourceUrl);const cookies = await session.defaultSession.cookies.get({ url: sourceUrl });+ assertCurrent();const headers = resourceRequestHeaders({ cookies, sessionToken });const rangeHeader = request.headers.get("range");if (rangeHeader) headers.set("range", rangeHeader);- const response = await net.fetch(sourceUrl, { headers, redirect: "error" });+ const response = await net.fetch(sourceUrl, { headers, redirect: "error", signal: request.signal });if (!response.ok) return new Response("Resource request failed", { status: response.status });if (response.status === 206) {const responseHeaders = resourceResponseHeaders(response.headers.get("content-type"), downloadDisposition);@@ -1132,35 +1136,38 @@ const handleResourceProtocolRequest = async (request) => {}};-const registerResourceProtocol = () => {- protocol.handle("edgeever-resource", handleResourceProtocolRequest);-- protocol.handle("edgeever-staged", async (request) => {- const stagedId = resourceIdFromRequest(request.url);- if (!stagedId) return new Response("Invalid staged resource", { status: 400 });+const handleStagedResourceProtocolRequest = async (request, assertCurrent = () => {}) => {+ assertCurrent();+ const stagedId = resourceIdFromRequest(request.url);+ if (!stagedId) return new Response("Invalid staged resource", { status: 400 });- const directory = stagedResourceDirectory();- try {- const metadata = await readStagedResourceMetadata(directory, stagedId);- const path = join(directory, `${stagedId}.bin`);- const size = await stat(path).then((details) => details.size).catch(() => null);- if (size === null && isSafeResourceId(metadata.resourceId)) {- const target = new URL(`edgeever-resource://resource/${encodeURIComponent(metadata.resourceId)}`);- target.search = new URL(request.url).search;- return handleResourceProtocolRequest(new Request(target, { headers: request.headers }));- }- if (size === null) throw new Error("Staged bytes are missing");- const stream = createReadStream(path);- const headers = resourceResponseHeaders(metadata.type, downloadContentDispositionFromRequest(request.url));- headers.set("Content-Length", String(size));- return new Response(Readable.toWeb(stream), {- headers,- });- } catch (error) {- void writeDiagnostic("resource.staged-read-failed", { stagedId, message: error.message });- return new Response("Staged resource unavailable", { status: 404 });+ const directory = stagedResourceDirectory();+ try {+ const metadata = await readStagedResourceMetadata(directory, stagedId);+ const path = join(directory, `${stagedId}.bin`);+ const size = await stat(path).then((details) => details.size).catch(() => null);+ if (size === null && isSafeResourceId(metadata.resourceId)) {+ const target = new URL(`edgeever-resource://resource/${encodeURIComponent(metadata.resourceId)}`);+ target.search = new URL(request.url).search;+ assertCurrent();+ return handleResourceProtocolRequest(new Request(target, { headers: request.headers, signal: request.signal }), assertCurrent);}- });+ if (size === null) throw new Error("Staged bytes are missing");+ const stream = createReadStream(path);+ const headers = resourceResponseHeaders(metadata.type, downloadContentDispositionFromRequest(request.url));+ headers.set("Content-Length", String(size));+ return new Response(Readable.toWeb(stream), {+ headers,+ });+ } catch (error) {+ void writeDiagnostic("resource.staged-read-failed", { stagedId, message: error.message });+ return new Response("Staged resource unavailable", { status: 404 });+ }+};++const registerResourceProtocol = () => {+ protocol.handle("edgeever-resource", (request) => handleResourceProtocolRequest(request));+ protocol.handle("edgeever-staged", (request) => handleStagedResourceProtocolRequest(request));};const registerDesktopAppProtocol = () => {@@ -2341,6 +2348,20 @@ const startApplication = async () => {});ipcMain.handle("desktop:download-update", () => downloadTrustedDesktopUpdate("manual-download"));ipcMain.handle("desktop:install-update", () => installDownloadedUpdate());+ registerAttachmentOpenIpc(ipcMain, {+ authorize: (event) => {+ if (!isAppRendererSender(event) || instanceChangePending+ || !isAllowedAppNavigation(event.senderFrame.url, desktopRendererEntryUrl())) {+ throw new Error("Attachment open forbidden");+ }+ },+ getScope: () => JSON.stringify([configuredApiBaseUrl, activeAccountId, desktopSessionToken]),+ getDirectory: () => join(sidecarDataDirectory(activeAccountId), "opened-attachments"),+ readResource: (url, signal, assertCurrent) => url.startsWith("edgeever-staged:")+ ? handleStagedResourceProtocolRequest(new Request(url, { signal }), assertCurrent)+ : handleResourceProtocolRequest(new Request(url, { signal }), assertCurrent),+ openPath: (path) => shell.openPath(path),+ });ipcMain.handle("desktop:stage-resource-begin", async (_event, input) => {const { memoId, name, type, size } = normalizeStagedResourceMetadataInput(input);const id = `stage_${Date.now()}_${Math.random().toString(36).slice(2)}`;diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjsindex aa02fe43..b672b31c 100644--- a/apps/desktop/src/preload/index.cjs+++ b/apps/desktop/src/preload/index.cjs@@ -107,6 +107,10 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({return () => ipcRenderer.removeListener("desktop:update-status-changed", listener);},sidecarRequest: (method, params = {}) => ipcRenderer.invoke("desktop:sidecar-request", method, params),+ openAttachment: (input) => {+ if (!navigator.userActivation?.isActive) return Promise.resolve({ ok: false, code: "forbidden" });+ return ipcRenderer.invoke("desktop:open-attachment", input);+ },beginStagedResource: (input) => ipcRenderer.invoke("desktop:stage-resource-begin", input),appendStagedResource: (id, bytes) => ipcRenderer.invoke("desktop:stage-resource-append", id, bytes),completeStagedResource: (id) => ipcRenderer.invoke("desktop:stage-resource-complete", id),diff --git a/apps/web/src/components/attachments/AttachmentExternalLink.tsx b/apps/web/src/components/attachments/AttachmentExternalLink.tsxnew file mode 100644index 00000000..232e88af--- /dev/null+++ b/apps/web/src/components/attachments/AttachmentExternalLink.tsx@@ -0,0 +1,69 @@+import { forwardRef, useRef, useState, type ComponentPropsWithoutRef } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogTitle } from "@/components/ui/dialog";+import { isDesktopResourceRuntime, toDesktopResourceUrl } from "@/lib/desktop-resources";++type Props = Omit<ComponentPropsWithoutRef<"a">, "href"> & {+ href: string;+ filename: string;+ iconOnly?: boolean;+};++/** Browsers keep normal link behavior; desktop attachments open a local copy. */+export const AttachmentExternalLink = forwardRef<HTMLAnchorElement, Props>(+ ({ href, filename, iconOnly, children, onClick, ...props }, ref) => {+ const { t } = useTranslation();+ const busy = useRef(false);+ const [opening, setOpening] = useState(false);+ const [error, setError] = useState<string | null>(null);+ return (+ <>+ <a+ {...props}+ ref={ref}+ href={href}+ target="_blank"+ rel="noreferrer"+ aria-busy={opening || undefined}+ aria-disabled={opening || undefined}+ onClick={(event) => {+ onClick?.(event);+ if (event.defaultPrevented || !isDesktopResourceRuntime()) return;+ const url = toDesktopResourceUrl(href);+ if (!url.startsWith("edgeever-resource://") && !url.startsWith("edgeever-staged://")) return;+ event.preventDefault();+ if (busy.current) return;+ busy.current = true;+ setOpening(true);+ // Invoke synchronously while the click still has user activation.+ const request = window.edgeeverDesktop?.openAttachment?.({ url, filename });+ void Promise.resolve(request).then((result) => {+ if (!result?.ok) setError(result?.code ?? "open-failed");+ }).catch(() => setError("open-failed")).finally(() => {+ busy.current = false;+ setOpening(false);+ });+ }}+ >+ {opening ? <Loader2 aria-hidden="true" className="h-4 w-4 shrink-0 animate-spin" /> : null}+ {opening && iconOnly ? null : children}+ {opening ? <span className="sr-only">{t("attachmentOpen.opening")}</span> : null}+ </a>+ <Dialog open={error !== null} onOpenChange={(open) => { if (!open) setError(null); }}>+ <DialogContent showCloseButton={false}>+ <DialogTitle>{t("attachmentOpen.failed")}</DialogTitle>+ <DialogDescription>+ {t(error === "blocked" ? "attachmentOpen.blocked"+ : error === "unavailable" ? "attachmentOpen.unavailable"+ : error === "forbidden" ? "attachmentOpen.forbidden" : "attachmentOpen.openFailed")}+ </DialogDescription>+ <DialogFooter><DialogClose asChild><Button>{t("common.close")}</Button></DialogClose></DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+ },+);+AttachmentExternalLink.displayName = "AttachmentExternalLink";diff --git a/apps/web/src/components/editor/FileAttachment.tsx b/apps/web/src/components/editor/FileAttachment.tsxindex a931ea7b..84864248 100644--- a/apps/web/src/components/editor/FileAttachment.tsx+++ b/apps/web/src/components/editor/FileAttachment.tsx@@ -9,6 +9,7 @@ import { useContext, useState } from "react";import { NodeViewWrapper, ReactNodeViewRenderer, type NodeViewProps } from "@tiptap/react";import { ChevronDown, ChevronUp, Download, ExternalLink } from "lucide-react";import { useTranslation } from "react-i18next";+import { AttachmentExternalLink } from "@/components/attachments/AttachmentExternalLink";import { AttachmentFileIcon } from "@/components/attachments/AttachmentFileIcon";import { AudioAttachmentPlayer } from "@/components/attachments/AudioAttachmentPlayer";import { DocxAttachmentPreview } from "@/components/attachments/DocxAttachmentPreview";@@ -85,24 +86,23 @@ const FileAttachmentNodeView = ({ node, updateAttributes }: NodeViewProps) => {{identity}</button>) : (- <a+ <AttachmentExternalLinkhref={resolvedUrl}- target="_blank"- rel="noreferrer"+ filename={filename || label}className="flex min-w-0 flex-1 items-center gap-2 text-left no-underline">{identity}- </a>+ </AttachmentExternalLink>)}<ButtonTooltip title={t("editor.resourceActions.download")}><a className="pdf-viewer-action" href={downloadUrl} download={filename || label} aria-label={t("editor.resourceActions.download")}><Download aria-hidden="true" /></a></ButtonTooltip>- <ButtonTooltip title={t("pdfViewer.openExternal")}>- <a className="pdf-viewer-action" href={resolvedUrl} target="_blank" rel="noreferrer" aria-label={t("pdfViewer.openExternal")}>+ <ButtonTooltip title={t(isDesktopResourceRuntime() ? "attachmentOpen.copyHint" : "pdfViewer.openExternal")}>+ <AttachmentExternalLink className="pdf-viewer-action" href={resolvedUrl} filename={filename || label} iconOnly aria-label={t("pdfViewer.openExternal")}><ExternalLink aria-hidden="true" />- </a>+ </AttachmentExternalLink></ButtonTooltip>{expandable ? (<ButtonTooltip title={expanded ? t("pdfViewer.collapse") : t("pdfViewer.expand")}>diff --git a/apps/web/src/components/pdf/PdfViewer.tsx b/apps/web/src/components/pdf/PdfViewer.tsxindex 6f32c692..ce570476 100644--- a/apps/web/src/components/pdf/PdfViewer.tsx+++ b/apps/web/src/components/pdf/PdfViewer.tsx@@ -17,6 +17,7 @@ import type { PDFDocumentProxy, PDFPageProxy } from "pdfjs-dist";import { useCallback, useEffect, useRef, useState } from "react";import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";+import { AttachmentExternalLink } from "@/components/attachments/AttachmentExternalLink";import { AttachmentFileIcon } from "@/components/attachments/AttachmentFileIcon";import { COMPACT_ATTACHMENT_WIDTH_CLASS } from "@/components/attachments/attachment-layout";import { ButtonTooltip } from "@/components/ui/button-tooltip";@@ -312,8 +313,8 @@ export const PdfViewer = ({<ButtonTooltip title={t("pdfViewer.download")}><a className="pdf-viewer-action" href={toDesktopResourceDownloadUrl(resolvedUrl, filename || label)} download={filename || label} aria-label={t("pdfViewer.download")}><Download aria-hidden="true" /></a></ButtonTooltip>- <ButtonTooltip title={t("pdfViewer.openExternal")}>- <a className="pdf-viewer-action" href={resolvedUrl} target="_blank" rel="noreferrer" aria-label={t("pdfViewer.openExternal")}><ExternalLink aria-hidden="true" /></a>+ <ButtonTooltip title={t(isDesktopResourceRuntime() ? "attachmentOpen.copyHint" : "pdfViewer.openExternal")}>+ <AttachmentExternalLink className="pdf-viewer-action" href={resolvedUrl} filename={filename || label} iconOnly aria-label={t("pdfViewer.openExternal")}><ExternalLink aria-hidden="true" /></AttachmentExternalLink></ButtonTooltip>{isFullscreen || (expanded && !failed) ? (<ButtonTooltip title={isFullscreen ? t("pdfViewer.exitFullscreen") : t("pdfViewer.fullscreen")}>diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex e6d0b2cd..1c814369 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -122,6 +122,7 @@ interface EdgeEverDesktopBridge {installUpdate(): Promise<unknown>;onUpdateStatus(callback: (status: DesktopUpdateStatus) => void): () => void;sidecarRequest<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;+ openAttachment(input: { url: string; filename: string }): Promise<{ ok: boolean; code?: "forbidden" | "blocked" | "unavailable" | "open-failed" }>;beginStagedResource(input: { memoId: string; name: string; type: string; size: number }): Promise<{ id: string; partSize: number }>;appendStagedResource(id: string, bytes: ArrayBuffer): Promise<{ receivedBytes: number }>;completeStagedResource(id: string): Promise<{ id: string }>;diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 126e5b8f..3dd64d20 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -2605,6 +2605,15 @@ export const enUS = {restoreConfirmLabel: "Restore",formActor: "Form submission",},+ attachmentOpen: {+ copyHint: "Open an attachment copy (external edits are not synced)",+ opening: "Opening attachment…",+ failed: "Could not open attachment",+ blocked: "This file type cannot be opened directly. Download it to open it yourself.",+ unavailable: "The attachment could not be retrieved. If you are offline, connect to your instance and try again.",+ forbidden: "Your workspace changed or this action is unavailable. Reopen the note and try again.",+ openFailed: "The system could not open this file. Check that an application is associated with this file type, or download it to open it yourself.",+ },pdfViewer: {loading: "Loading PDF…",unavailable: "This PDF cannot be previewed. You can still download it or open it externally.",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 7a010267..6706b48b 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2594,6 +2594,15 @@ export const ja = {restoreConfirmLabel: "復元",formActor: "フォーム送信",},+ attachmentOpen: {+ copyHint: "添付ファイルのコピーを開く(外部での編集は同期されません)",+ opening: "添付ファイルを開いています…",+ failed: "添付ファイルを開けませんでした",+ blocked: "この種類のファイルは直接開けません。ダウンロードして開いてください。",+ unavailable: "添付ファイルを取得できませんでした。オフラインの場合はインスタンスに接続して再試行してください。",+ forbidden: "ワークスペースが変更されたか、この操作は利用できません。ノートを開き直して再試行してください。",+ openFailed: "システムがファイルを開けませんでした。対応するアプリの関連付けを確認するか、ダウンロードして開いてください。",+ },pdfViewer: {loading: "PDF を読み込み中…",unavailable: "この PDF はプレビューできません。ダウンロードするか、外部で開くことはできます。",diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex 63f204fe..60be6018 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -2594,6 +2594,15 @@ export const pl = {restoreConfirmLabel: "Przywróć",formActor: "Przesłanie formularza",},+ attachmentOpen: {+ copyHint: "Otwórz kopię załącznika (zmiany zewnętrzne nie są synchronizowane)",+ opening: "Otwieranie załącznika…",+ failed: "Nie można otworzyć załącznika",+ blocked: "Tego typu pliku nie można otworzyć bezpośrednio. Pobierz go i otwórz samodzielnie.",+ unavailable: "Nie udało się pobrać załącznika. Jeśli jesteś offline, połącz się z instancją i spróbuj ponownie.",+ forbidden: "Obszar roboczy uległ zmianie lub ta czynność jest niedostępna. Otwórz notatkę ponownie i spróbuj jeszcze raz.",+ openFailed: "System nie mógł otworzyć pliku. Sprawdź powiązanie typu pliku z aplikacją lub pobierz plik i otwórz go samodzielnie.",+ },pdfViewer: {loading: "Wczytywanie PDF…",unavailable: "Nie można wyświetlić podglądu tego pliku PDF. Nadal możesz go pobrać lub otworzyć w innej aplikacji.",diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.tsindex 3978bd39..5dab20e0 100644--- a/packages/shared/src/i18n/ru.ts+++ b/packages/shared/src/i18n/ru.ts@@ -2605,6 +2605,15 @@ export const ru = {restoreConfirmLabel: "Восстановить",formActor: "Отправка формы",},+ attachmentOpen: {+ copyHint: "Открыть копию вложения (внешние изменения не синхронизируются)",+ opening: "Открытие вложения…",+ failed: "Не удалось открыть вложение",+ blocked: "Этот тип файла нельзя открыть напрямую. Скачайте его и откройте самостоятельно.",+ unavailable: "Не удалось получить вложение. Если вы не в сети, подключитесь к своему экземпляру и повторите попытку.",+ forbidden: "Рабочее пространство изменилось или действие недоступно. Откройте заметку заново и повторите попытку.",+ openFailed: "Система не смогла открыть файл. Проверьте наличие приложения, связанного с этим типом файла, или скачайте файл и откройте его самостоятельно.",+ },pdfViewer: {loading: "Загрузка PDF…",unavailable: "Этот PDF нельзя просмотреть. Вы всё ещё можете скачать его или открыть во внешней программе.",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 5685b3c8..aa4c9cda 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -2605,6 +2605,15 @@ export const zhCN = {restoreConfirmLabel: "恢复",formActor: "表单提交",},+ attachmentOpen: {+ copyHint: "打开附件副本(外部修改不会同步)",+ opening: "正在打开附件…",+ failed: "无法打开附件",+ blocked: "此文件类型不能直接打开,请下载后自行处理。",+ unavailable: "无法读取附件。如果当前处于离线状态,请连接实例后重试。",+ forbidden: "工作区已切换或当前无法执行此操作,请重新打开笔记后重试。",+ openFailed: "系统无法打开此文件,请检查是否已安装并关联相应应用,或下载后自行打开。",+ },pdfViewer: {loading: "正在加载 PDF…",unavailable: "无法预览此 PDF,你仍可下载或在外部打开。",diff --git a/tests/browser/attachment-open.browser.tsx b/tests/browser/attachment-open.browser.tsxnew file mode 100644index 00000000..32427f75--- /dev/null+++ b/tests/browser/attachment-open.browser.tsx@@ -0,0 +1,56 @@+// Open via Vite's /@fs/<checkout>/tests/browser/attachment-open.html.+// The real TipTap attachment card and PDF viewer share a controlled IPC mock.+import React, { useState } from "react";+import { createRoot } from "react-dom/client";+import { Editor, EditorContent } from "@tiptap/react";+import StarterKit from "@tiptap/starter-kit";+import { I18nextProvider } from "react-i18next";+import i18next from "i18next";+import { zhCN } from "../../packages/shared/src/i18n/zh-CN";+import { FileAttachment } from "../../apps/web/src/components/editor/FileAttachment";+import { PdfViewer } from "../../apps/web/src/components/pdf/PdfViewer";+import "../../apps/web/src/styles/globals.css";++const i18n = i18next.createInstance();+await i18n.init({ lng: "zh-CN", resources: { "zh-CN": { translation: zhCN } }, initAsync: false });+let resolveOpen: ((value: { ok: boolean; code?: string }) => void) | undefined;+const calls: Array<{ url: string; filename: string }> = [];+Object.defineProperty(window, "edgeeverDesktop", { configurable: true, value: {+ isAvailable: true,+ apiBaseUrl: "http://attachment-fixture.invalid",+ openAttachment: (input: { url: string; filename: string }) => {+ calls.push(input);+ document.getElementById("calls")!.textContent = JSON.stringify(calls);+ return new Promise((resolve) => { resolveOpen = resolve; });+ },+} });+const editor = new Editor({ extensions: [StarterKit, FileAttachment], content: {+ type: "doc", content: [{ type: "paragraph", content: [{ type: FileAttachment.name, attrs: {+ url: "edgeever-resource://resource/sheet_1", label: "训练.xlsx", filename: "训练.xlsx",+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", byteSize: 6440,+ } }] }],+} });+const Fixture = () => {+ const [desktop, setDesktop] = useState(true);+ return <I18nextProvider i18n={i18n}>+ <div className="my-4 flex flex-wrap gap-3">+ <button onClick={() => resolveOpen?.({ ok: true })}>完成打开</button>+ <button onClick={() => resolveOpen?.({ ok: false, code: "unavailable" })}>模拟离线无缓存</button>+ <button onClick={() => resolveOpen?.({ ok: false, code: "blocked" })}>模拟受限文件</button>+ <button onClick={() => resolveOpen?.({ ok: false, code: "open-failed" })}>模拟无关联应用</button>+ <button onClick={() => {+ const next = !desktop;+ window.edgeeverDesktop!.isAvailable = next;+ editor.commands.setContent({ type: "doc", content: [{ type: "paragraph", content: [{ type: FileAttachment.name, attrs: {+ url: next ? "edgeever-resource://resource/sheet_1" : "/api/v1/resources/sheet_1/blob",+ label: "训练.xlsx", filename: "训练.xlsx", byteSize: 6440,+ } }] }] });+ setDesktop(next);+ }}>运行环境:{desktop ? "桌面" : "Web"}</button>+ </div>+ <EditorContent editor={editor} />+ <PdfViewer url={desktop ? "edgeever-staged://pdf_1" : "/api/v1/resources/pdf_1/blob"} label="报告.pdf" filename="报告.pdf" byteSize={1000} />+ <pre id="calls" className="mt-5 whitespace-pre-wrap text-xs">[]</pre>+ </I18nextProvider>;+};+createRoot(document.getElementById("fixture")!).render(<Fixture />);diff --git a/tests/browser/attachment-open.html b/tests/browser/attachment-open.htmlnew file mode 100644index 00000000..309fb696--- /dev/null+++ b/tests/browser/attachment-open.html@@ -0,0 +1,10 @@+<!doctype html>+<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Attachment external opening check</title></head>+<body><main class="mx-auto max-w-3xl p-6"><h1 class="mb-4 text-lg font-semibold">附件外部打开交互检查</h1><p>仅使用模拟桌面桥,不访问实例或启动外部应用。</p><div id="fixture"></div></main>+<script type="module">+import RefreshRuntime from "/@react-refresh";+RefreshRuntime.injectIntoGlobalHook(window);+window.$RefreshReg$ = () => {};+window.$RefreshSig$ = () => (type) => type;+window.__vite_plugin_react_preamble_installed__ = true;+</script><script type="module" src="./attachment-open.browser.tsx"></script></body></html>