Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(security): validate attachment drag sources and update vulnerable tooling (#274)
Ruben Lütke1a5fbcbc4481
diff --git a/.gitattributes b/.gitattributesindex febe21ac41..b640b40a0c 100644--- a/.gitattributes+++ b/.gitattributes@@ -9,6 +9,10 @@## Pin all signed artifacts to LF unconditionally on every platform.+# Every POSIX shell script needs LF, including development and verification+# helpers run from Windows checkouts through Git Bash, WSL or Docker.+*.sh text eol=lf+install/install.sh text eol=lfinstall/install.ps1 text eol=lfinstall/installer.py text eol=lfdiff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.jsonindex c4c1ed727c..86147ddbd8 100644--- a/jarvis/ui/web/frontend/package-lock.json+++ b/jarvis/ui/web/frontend/package-lock.json@@ -6341,9 +6341,9 @@}},"node_modules/nanoid": {- "version": "3.3.16",- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",- "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",+ "version": "3.3.19",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==","dev": true,"funding": [{diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsxindex f67d858417..01ab06069f 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx@@ -8,6 +8,8 @@ import { useFileDropGuard } from "@/hooks/useFileDropGuard";import { useAgentChatStore } from "@/store/agentChat";import { useEventStore } from "@/store/events";import type { AgentChatCatalog } from "@/lib/agentChatApi";+import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";+import { NATIVE_DROP_EVENT } from "@/lib/nativeDrop";/*** Files in the chat composer — the drop, the paste, and what travels with the@@ -200,6 +202,39 @@ describe("chat composer attachments", () => {expect(screen.queryByTestId("chat-attachment-shot.png")).toBeNull();});+ it.each([WORKSPACE_PATH_TYPE, "text/uri-list", "text/plain"])(+ "does not request a local attachment from foreign %s data",+ async (type) => {+ composer();+ await act(async () => {+ fireEvent.drop(screen.getByTestId("agent-composer"), {+ dataTransfer: {+ ...transfer([]),+ types: [type],+ getData: (format: string) => format === type ? "file:///private/secret.txt" : "",+ },+ });+ });+ expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/attachments"))).toBe(false);+ },+ );++ it("uses offered bytes even when a native hint names another local file", async () => {+ vi.stubGlobal("__JARVIS_EMBEDDED_DESKTOP", true);+ composer();+ const png = new File(["offered bytes"], "shot.png", { type: "image/png" });+ await act(async () => {+ fireEvent.drop(screen.getByTestId("agent-composer"), { dataTransfer: transfer([png]) });+ window.dispatchEvent(new CustomEvent(NATIVE_DROP_EVENT, {+ detail: { paths: ["/private/shot.png"], names: ["shot.png"] },+ }));+ });+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png")).toBeDefined());+ const [, init] = fetchMock.mock.calls.find(([url]) => String(url).includes("/attachments")) as [string, RequestInit];+ expect((init.body as FormData).get("paths")).toBeNull();+ expect((init.body as FormData).getAll("files")).toHaveLength(1);+ });+it("lets a picture alone be the whole message", async () => {const send = vi.fn(async () => {});seed({ send });diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.tsindex 822455c7be..63da5aa794 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts@@ -11,8 +11,7 @@* broken, not as two surfaces with different features (maintainer, 2026-08-24).** The pieces are deliberately the terminal path's own — the same drag tracking- * (`usePaneFileDrag`), the same payload extraction (`paneDrop`), the same- * desktop-shell path resolution (`waitForNativeDrop`) — so the two surfaces+ * (`usePaneFileDrag`) and the same payload extraction (`paneDrop`) so the two surfaces* cannot drift into disagreeing about what a drop is. Only the endpoint* differs: a chat has no pane to type a path into, so the files are HELD here* and travel with the sentence when it is sent.@@ -27,7 +26,6 @@ import {type PaneDropPayload,} from "@/components/agentic/paneDrop";import { usePaneFileDrag } from "@/components/agentic/paneFileDrag";-import { waitForNativeDrop } from "@/lib/nativeDrop";import { attachChatFiles, type AgentChatSurface, type ChatAttachment } from "@/lib/agentChatApi";export interface ChatAttachments {@@ -104,22 +102,10 @@ export function useChatAttachments(const { dragging, handlers: dragHandlers } = usePaneFileDrag(useCallback((dt: DataTransfer) => {- // Both reads happen BEFORE any await, and they have to: a DataTransfer- // empties the moment this handler returns, and the desktop shell only- // answers a listener that was already in place when the drop happened.- const payload = extractPaneDrop(dt);- void waitForNativeDrop().then((detail) => {- if (!detail?.paths.length) return void attach(payload);- // Inside the desktop shell the host knows where the file really- // lies. Prefer that over uploading its bytes — same file, no copy —- // and drop the byte copies the shell just accounted for so nothing- // is attached twice.- const named = new Set(detail.names.map((n) => n.toLowerCase()));- return void attach({- paths: Array.from(new Set([...payload.paths, ...detail.paths])),- files: payload.files.filter((f) => !named.has(f.name.toLowerCase())),- });- });+ // Read before returning: browsers clear DataTransfer after this event.+ // Native path hints are not a file-read grant on every WebView backend;+ // use the granted File bytes or our own explorer's receipt everywhere.+ void attach(extractPaneDrop(dt));},[attach],),diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.droptarget.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.droptarget.test.tsxindex 0d66bf7445..6c95feca16 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.droptarget.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceBar.droptarget.test.tsx@@ -69,7 +69,7 @@ describe("WorkspaceBar file drops", () => {expect(onDropFiles.mock.calls[0][0]).toBe("w2");});- it("hands over the paths the drag carried", () => {+ it("does not turn a URI supplied by another page into a local file read", () => {const onDropFiles = vi.fn();render(<WorkspaceBar {...base} onDropFiles={onDropFiles} />);@@ -77,7 +77,7 @@ describe("WorkspaceBar file drops", () => {dataTransfer: transfer(["Files"]),});- expect(onDropFiles.mock.calls[0][1].paths).toEqual(["C:/shot.png"]);+ expect(onDropFiles.mock.calls[0][1].paths).toEqual([]);});it("ignores a drag carrying only selected text", () => {diff --git a/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.test.ts b/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.test.tsindex 2f80d9124c..9fc0a00a6b 100644--- a/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.test.ts@@ -90,7 +90,8 @@ describe("lifting one explorer row into a drag", () => {setWorkspaceEntryDrag(dt, { root: "/home/me/project", path: "src" });expect(dt.getData("text/uri-list")).toBe("file:///home/me/project/src");expect(dt.getData("text/plain")).toBe("/home/me/project/src");- expect(dt.getData(WORKSPACE_PATH_TYPE)).toBe("/home/me/project/src");+ expect(dt.getData(WORKSPACE_PATH_TYPE)).toMatch(/^[0-9a-f]{64}$/);+ expect(extractPaneDrop(dt).paths).toEqual(["/home/me/project/src"]);});it("carries a FOLDER as readily as a file", () => {@@ -104,4 +105,26 @@ describe("lifting one explorer row into a drag", () => {false,);});++ it("encodes a literal POSIX backslash without turning it into a separator", () => {+ expect(workspaceFileUri("/project/\\.env")).toBe("file:///project/%5C.env");+ });++ it("does not trim a listed filename into another file before authorization", () => {+ const dt = dataTransfer();+ expect(setWorkspaceEntryDrag(dt, { root: "/project", path: ".env " })).toBe(false);+ expect(extractPaneDrop(dt).paths).toEqual([]);+ });++ it("preserves spaces inside the complete path", () => {+ const dt = dataTransfer();+ expect(setWorkspaceEntryDrag(dt, { root: "/project ", path: " report.txt" })).toBe(true);+ expect(extractPaneDrop(dt).paths).toEqual(["/project / report.txt"]);+ });++ it("does not strip a literal POSIX backslash into another filename", () => {+ const dt = dataTransfer();+ expect(setWorkspaceEntryDrag(dt, { root: "/project", path: "\\.env" })).toBe(true);+ expect(extractPaneDrop(dt).paths).toEqual(["/project/\\.env"]);+ });});diff --git a/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.ts b/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.tsindex 325f022939..580dbc0afd 100644--- a/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/explorerDrag.ts@@ -18,7 +18,7 @@* pointed at the same server are the same page. So the separator is read off* the workspace root the server sent, never off `navigator`.*/-import { WORKSPACE_PATH_TYPE } from "./paneDrop";+import { setWorkspaceDragPaths } from "./paneDrop";/** A drive letter (`C:\…`) or a UNC share (`\\server\…`) — Windows either way. */function isWindowsRoot(root: string): boolean {@@ -33,10 +33,12 @@ function isWindowsRoot(root: string): boolean {* draggable" — better than a path rooted at nothing.*/export function absoluteWorkspacePath(root: string, path: string): string {- const base = root.trim().replace(/[\\/]+$/, "");- const relative = path.trim().replace(/^[\\/]+/, "");+ // These are server-listed names, not padded text input. Trimming a name+ // could select a different file before the receipt validator sees it.+ const base = root.replace(/[\\/]+$/, "");+ const relative = path;if (!base) return "";- if (!relative) return root.trim();+ if (!relative) return root;return isWindowsRoot(base)? `${base}\\${relative.replace(/\//g, "\\")}`: `${base}/${relative}`;@@ -45,7 +47,7 @@ export function absoluteWorkspacePath(root: string, path: string): string {/*** The same path as a `file://` URI, for drop targets outside this page.*- * Only the OUTSIDE case needs this — a pane reads {@link WORKSPACE_PATH_TYPE}+ * Only the OUTSIDE case needs this — a pane reads its internal drag receipt* and never has to parse a URL. It is offered anyway because a drag that* carries `text/uri-list` is a drag another application can accept, and* withholding it would make the explorer a dead end everywhere but here.@@ -54,7 +56,7 @@ export function absoluteWorkspacePath(root: string, path: string): string {* which is the one shape a bare `file:///` prefix would silently corrupt.*/export function workspaceFileUri(absolute: string): string {- const posix = absolute.replace(/\\/g, "/");+ const posix = isWindowsRoot(absolute) ? absolute.replace(/\\/g, "/") : absolute;const encoded = posix.split("/").map((segment) => encodeURIComponent(segment))@@ -79,7 +81,7 @@ export interface WorkspaceEntryDrag {** Three formats for three audiences, all describing the same file:*- * * {@link WORKSPACE_PATH_TYPE} — the panes, verbatim and lossless.+ * * An internal receipt — the panes, verbatim and lossless.* * `text/uri-list` — other applications, and the pane's own arming check,* which is what makes the drop overlay appear as the row crosses a pane.* * `text/plain` — anything that only takes text: a chat composer, an editor,@@ -91,7 +93,7 @@ export function setWorkspaceEntryDrag(): boolean {const absolute = absoluteWorkspacePath(entry.root, entry.path);if (!absolute) return false;- dt.setData(WORKSPACE_PATH_TYPE, absolute);+ if (!setWorkspaceDragPaths(dt, [absolute])) return false;dt.setData("text/uri-list", workspaceFileUri(absolute));dt.setData("text/plain", absolute);// "copy" and not "move": the file stays where it is. A "move" cursor over adiff --git a/jarvis/ui/web/frontend/src/components/agentic/paneDrop.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.test.tsindex fb0181ad10..3f2baad1bc 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneDrop.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import {WORKSPACE_PATH_TYPE,dragCarriesFiles,@@ -6,6 +6,7 @@ import {extractPasteFiles,isEmptyPayload,nameClipboardFile,+ setWorkspaceDragPaths,} from "./paneDrop";/** Minimal DataTransfer stand-in — jsdom has no real one. */@@ -15,11 +16,14 @@ function dt(opts: {workspacePath?: string;files?: File[];}): DataTransfer {+ const data = new Map<string, string>();return {+ setData: (type: string, value: string) => data.set(type, value),getData: (type: string) => {+ if (data.has(type)) return data.get(type)!;if (type === "text/uri-list") return opts.uriList ?? "";if (type === WORKSPACE_PATH_TYPE) return opts.workspacePath ?? "";- return opts.text ?? "";+ return type === "text/plain" ? opts.text ?? "" : "";},files: opts.files ?? [],items: (opts.files ?? []).map((file) => ({@@ -34,22 +38,22 @@ function file(name: string, type = "image/png", size = 4): File {return new File([new Uint8Array(size)], name, { type });}-describe("reading a drop onto a terminal pane", () => {- it("takes the real path Explorer and Finder hand over", () => {- const payload = extractPaneDrop(dt({ uriList: "file:///C:/work/shot.png\r\n" }));- expect(payload.paths).toEqual(["C:/work/shot.png"]);- });-- it("takes a POSIX path the same way", () => {- expect(extractPaneDrop(dt({ text: "/home/ruben/shot.png" })).paths).toEqual([- "/home/ruben/shot.png",- ]);- });+afterEach(() => {+ window.dispatchEvent(new Event("dragend"));+ vi.restoreAllMocks();+});- it("takes a UNC path", () => {- expect(extractPaneDrop(dt({ text: "\\\\nas\\share\\shot.png" })).paths).toEqual([- "\\\\nas\\share\\shot.png",- ]);+describe("reading a drop onto a terminal pane", () => {+ it.each([+ "file:///C:/private/secret.txt",+ "FILE:///C:/private/%73ecret.txt",+ "/home/person/private/secret.txt",+ "\\\\nas\\share\\secret.txt",+ "C:\\private\\secret.txt\r\nC:\\private\\other.txt",+ ])("rejects untrusted textual paths in every drag format: %s", (path) => {+ for (const data of [{ uriList: path }, { text: path }, { workspacePath: path }]) {+ expect(isEmptyPayload(extractPaneDrop(dt(data)))).toBe(true);+ }});it("keeps the bytes when there is no path — a pasted screenshot has none", () => {@@ -58,13 +62,12 @@ describe("reading a drop onto a terminal pane", () => {expect(payload.files.map((f) => f.name)).toEqual(["image.png"]);});- it("does not send the same file twice when both a path and bytes arrive", () => {- // A normal Explorer drag produces exactly this: a path AND a File object.+ it("keeps granted file bytes and ignores a claimed path with the same name", () => {const payload = extractPaneDrop(dt({ uriList: "file:///C:/work/shot.png", files: [file("shot.png")] }),);- expect(payload.paths).toEqual(["C:/work/shot.png"]);- expect(payload.files).toEqual([]);+ expect(payload.paths).toEqual([]);+ expect(payload.files.map((f) => f.name)).toEqual(["shot.png"]);});it("ignores dragged prose, which also arrives as text/plain", () => {@@ -81,9 +84,9 @@ describe("reading a drop onto a terminal pane", () => {it("reads several dropped files at once", () => {const payload = extractPaneDrop(- dt({ uriList: "file:///C:/a.png\r\nfile:///C:/b.png" }),+ dt({ files: [file("a.png"), file("b.png")] }),);- expect(payload.paths).toEqual(["C:/a.png", "C:/b.png"]);+ expect(payload.files.map((f) => f.name)).toEqual(["a.png", "b.png"]);});it("survives a drop with nothing in it", () => {@@ -92,26 +95,94 @@ describe("reading a drop onto a terminal pane", () => {});it("takes a row dragged out of the app's own explorer verbatim", () => {- // A UNC path is the case the URI round-trip cannot survive, which is why- // the in-app drag carries the path under its own type.- const payload = extractPaneDrop(- dt({ workspacePath: "\\\\nas\\share\\project\\docs\\plan.md" }),- );+ const transfer = dt({});+ setWorkspaceDragPaths(transfer, ["\\\\nas\\share\\project\\docs\\plan.md"]);+ const payload = extractPaneDrop(transfer);expect(payload.paths).toEqual(["\\\\nas\\share\\project\\docs\\plan.md"]);});it("does not attach an explorer row twice when the drag also carries text", () => {// The explorer fills text/plain and text/uri-list too, for drop targets// outside this page. A pane must still see exactly one file.- const payload = extractPaneDrop(- dt({- workspacePath: "C:\\work\\project\\README.md",+ const transfer = dt({uriList: "file:///C:/work/project/README.md",text: "C:\\work\\project\\README.md",- }),- );+ });+ setWorkspaceDragPaths(transfer, ["C:\\work\\project\\README.md"]);+ const payload = extractPaneDrop(transfer);expect(payload.paths).toEqual(["C:\\work\\project\\README.md"]);});++ it("a receipt authorizes only the stored paths, once", () => {+ const transfer = dt({ text: "/private/secret", uriList: "file:///private/secret" });+ const paths = ["/project/selected.txt"];+ setWorkspaceDragPaths(transfer, paths);+ paths[0] = "/private/secret";+ expect(extractPaneDrop(transfer).paths).toEqual(["/project/selected.txt"]);+ expect(isEmptyPayload(extractPaneDrop(transfer))).toBe(true);+ });++ it("rejects a forged receipt without consuming a valid internal drag", () => {+ const transfer = dt({});+ setWorkspaceDragPaths(transfer, ["/project/selected.txt"]);+ const forged = dt({ workspacePath: "forged-receipt", files: [file("offered.png")] });+ expect(extractPaneDrop(forged).paths).toEqual([]);+ expect(extractPaneDrop(forged).files.map((f) => f.name)).toEqual(["offered.png"]);+ expect(extractPaneDrop(transfer).paths).toEqual(["/project/selected.txt"]);+ });++ it("a new explorer drag invalidates the previous receipt", () => {+ const old = dt({});+ const current = dt({});+ setWorkspaceDragPaths(old, ["/project/old.txt"]);+ setWorkspaceDragPaths(current, ["/project/current.txt"]);+ expect(isEmptyPayload(extractPaneDrop(old))).toBe(true);+ expect(extractPaneDrop(current).paths).toEqual(["/project/current.txt"]);+ });++ it("a detached window can consume the receipt exactly once", async () => {+ const transfer = dt({});+ setWorkspaceDragPaths(transfer, ["/project/selected.txt"]);+ vi.resetModules();+ const otherWindow = await import("./paneDrop");+ expect(otherWindow.extractPaneDrop(transfer).paths).toEqual(["/project/selected.txt"]);+ expect(isEmptyPayload(extractPaneDrop(transfer))).toBe(true);+ });++ it("expired and ended drags cannot authorize another read", () => {+ const transfer = dt({});+ setWorkspaceDragPaths(transfer, ["/project/selected.txt"]);+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + 120_001);+ expect(isEmptyPayload(extractPaneDrop(transfer))).toBe(true);+ setWorkspaceDragPaths(transfer, ["/project/selected.txt"]);+ window.dispatchEvent(new Event("dragend"));+ expect(isEmptyPayload(extractPaneDrop(transfer))).toBe(true);+ });++ it("keeps same-page drags working when browser storage is blocked", () => {+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("blocked"); });+ const transfer = dt({});+ setWorkspaceDragPaths(transfer, ["/project/selected.txt"]);+ expect(extractPaneDrop(transfer).paths).toEqual(["/project/selected.txt"]);+ expect(isEmptyPayload(extractPaneDrop(transfer))).toBe(true);+ });++ it.each(["\n", "\r", "\v", "\f", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029"])(+ "rejects every Python splitlines separator in a filename: %j", (separator) => {+ const path = `/project/one${separator}/private/secret`;+ const transfer = dt({});+ expect(setWorkspaceDragPaths(transfer, [path])).toBe(false);+ expect(isEmptyPayload(extractPaneDrop(transfer))).toBe(true);+ },+ );++ it.each(["/project/.env ", "/project/.env\t", "/project/.env\u00a0", "/project/.env\x1f"])(+ "does not let the receiver trim a filename into another file: %j", (path) => {+ const transfer = dt({});+ expect(setWorkspaceDragPaths(transfer, [path])).toBe(false);+ expect(isEmptyPayload(extractPaneDrop(transfer))).toBe(true);+ },+ );});describe("deciding whether a drag in flight is worth offering a pane for", () => {diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneDrop.ts b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.tsindex c233a5e54c..db91935e77 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneDrop.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneDrop.ts@@ -1,19 +1,10 @@/*** Reading a drop or a paste that lands on a terminal pane.*- * A browser hands a web page two very different things depending on where the- * drag came from, and the difference decides whether anything has to be copied:- *- * * **A real path.** Explorer and Finder put the file's location in- * `text/uri-list` (and usually `text/plain`). Nothing needs copying — the- * agent can open the file where it lies.- * * **Only bytes.** A screenshot pasted from the clipboard, an image dragged- * off a web page, anything from a sandboxed source. There is no path to be- * had — that is a deliberate browser restriction, not something to work- * around — so those bytes have to be written somewhere the agent can reach.- *- * Both are collected here and sent together; the backend copies only what it- * has to.+ * Text and custom MIME data can come from a hostile page. They cannot grant+ * permission to read a local path. Internal explorer drags carry an opaque,+ * single-use receipt held by this origin; external drops carry File+ * bytes. Native path hints are not a file-read grant on every WebView backend.** The hard constraint that shapes this file: **a DataTransfer is emptied the* moment the event handler returns.** Reading it after an `await` yields an@@ -23,7 +14,7 @@*/export interface PaneDropPayload {- /** Real filesystem paths the drag carried, if any. */+ /** Filesystem paths authorized by this page's own explorer. */paths: string[];/** Raw files, for everything the browser gave no path for. */files: File[];@@ -38,12 +29,94 @@ export interface PaneDropPayload {* (`\\server\share`) do not survive being parsed back out of a URL, and the* failure is silent — the agent is handed a path to nowhere.*- * So an in-app drag carries the path VERBATIM under its own type. It is- * newline-separated for the same reason the wire format is: one gesture may- * eventually mean several entries.+ * The type carries a receipt, never a path supplied by the drop source.*/export const WORKSPACE_PATH_TYPE = "application/x-jarvis-workspace-path";+interface WorkspaceDrag {+ receipt: string;+ paths: string[];+ expiresAt: number;+}++const DRAG_STORAGE_KEY = "jarvis:workspace-drag-receipt";+const DRAG_LIFETIME_MS = 120_000;+// Python splits on all these line separators and strips the unit separator too.+const PATH_LINE_BREAK = /[\r\n\v\f\x1c-\x1f\x85\u2028\u2029]/;++function isExactWirePath(path: unknown): path is string {+ // The receiver strips each line. Reject ambiguous filenames instead of+ // selecting a different file after whitespace normalization.+ return typeof path === "string" && path.length > 0 &&+ !PATH_LINE_BREAK.test(path) && path === path.trim();+}+let workspaceDrag: (WorkspaceDrag & { stored: boolean }) | null = null;+let expiryTimer: ReturnType<typeof setTimeout> | undefined;+let cleanupInstalled = false;++function clearWorkspaceDrag(): void {+ try {+ const stored = JSON.parse(localStorage.getItem(DRAG_STORAGE_KEY) ?? "null");+ if (stored?.receipt === workspaceDrag?.receipt) localStorage.removeItem(DRAG_STORAGE_KEY);+ } catch {+ // Blocked/corrupt storage cannot authorize a drop; the local fallback expires too.+ }+ workspaceDrag = null;+ clearTimeout(expiryTimer);+}++/** Register paths from an explorer row in this page, not from drag metadata. */+export function setWorkspaceDragPaths(dt: DataTransfer, paths: readonly string[]): boolean {+ clearWorkspaceDrag();+ // Attachment APIs frame paths as lines. A filename containing a newline must+ // never become a second file-read request; byte uploads still accept it.+ if (!paths.length || !paths.every(isExactWirePath)) return false;+ // getRandomValues also works on HTTP LAN origins where randomUUID is absent.+ const receipt = Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) =>+ byte.toString(16).padStart(2, "0"),+ ).join("");+ const record: WorkspaceDrag = { receipt, paths: [...paths], expiresAt: Date.now() + DRAG_LIFETIME_MS };+ let stored = false;+ try {+ // Same-origin storage lets a detached IDE window hand a file to the main+ // window. Foreign pages cannot mint or change this record.+ localStorage.setItem(DRAG_STORAGE_KEY, JSON.stringify(record));+ stored = true;+ } catch {+ // Storage-disabled browsers retain same-window drags without trusting MIME paths.+ }+ workspaceDrag = { ...record, stored };+ expiryTimer = setTimeout(clearWorkspaceDrag, DRAG_LIFETIME_MS);+ if (!cleanupInstalled) {+ window.addEventListener("dragend", clearWorkspaceDrag);+ cleanupInstalled = true;+ }+ dt.setData(WORKSPACE_PATH_TYPE, receipt);+ return true;+}++function consumeWorkspaceDrag(receipt: string): string[] | null {+ if (!/^[0-9a-f]{64}$/.test(receipt)) return null;+ let record: WorkspaceDrag | null = null;+ try {+ const stored = JSON.parse(localStorage.getItem(DRAG_STORAGE_KEY) ?? "null");+ if (stored?.receipt === receipt) {+ localStorage.removeItem(DRAG_STORAGE_KEY);+ record = stored;+ }+ } catch {+ // A stored receipt that cannot be read/consumed fails closed.+ }+ if (!record && workspaceDrag?.receipt === receipt && !workspaceDrag.stored) record = workspaceDrag;+ if (workspaceDrag?.receipt === receipt) clearWorkspaceDrag();+ if (+ !record || !Number.isFinite(record.expiresAt) || record.expiresAt <= Date.now() ||+ !Array.isArray(record.paths) || record.paths.length === 0 ||+ !record.paths.every(isExactWirePath)+ ) return null;+ return record.paths;+}+/** True when this payload has nothing worth sending. */export function isEmptyPayload(payload: PaneDropPayload): boolean {return payload.paths.length === 0 && payload.files.length === 0;@@ -81,81 +154,26 @@ export function dragCarriesFiles(dt: DataTransfer | null): boolean {);}-/**- * A `file://` URI as a native path; anything else unchanged.- *- * Windows URIs carry a leading slash before the drive letter- * (`file:///C:/x` → `C:/x`), which is why this cannot be a plain `slice(7)`.- */-function unwrapFileUri(value: string): string {- if (!/^file:/i.test(value)) return value;- let path: string;- try {- path = decodeURIComponent(new URL(value).pathname);- } catch {- return value;- }- if (path.length > 2 && path[0] === "/" && path[2] === ":") path = path.slice(1);- return path;-}--/**- * Does this string look like a filesystem path rather than dragged prose?- *- * Dragging selected TEXT also fills `text/plain`, and sending that as a path- * would have the backend try to read a sentence off the disk. A path is- * single-line and either absolute (`/x`, `C:\x`, `\\server\share`) or a- * `file://` URI — a relative-looking fragment is far more likely to be text.- */-function looksLikePath(value: string): boolean {- const trimmed = value.trim();- if (!trimmed || /[\r\n]/.test(trimmed)) return false;- if (/^file:/i.test(trimmed)) return true;- if (/^[a-zA-Z]:[\\/]/.test(trimmed)) return true;- if (trimmed.startsWith("\\\\")) return true;- return trimmed.startsWith("/");-}-/*** Everything usable in a drop, pulled out synchronously.- *- * Files and paths are matched up by NAME so a single drag does not produce- * both a path and a byte copy of the same file: when Explorer gives us the- * path, the `File` object beside it is redundant.*/export function extractPaneDrop(dt: DataTransfer | null): PaneDropPayload {const out: PaneDropPayload = { paths: [], files: [] };if (!dt) return out;- // The app's own explorer, when it is the source. Trusted as-is and taken- // INSTEAD of the text forms rather than alongside them: the same drag also- // carries `text/plain` for the benefit of anything that only understands- // text, and reading both would attach every entry twice.- const internal = dt.getData(WORKSPACE_PATH_TYPE) || "";- if (internal.trim()) {- for (const line of internal.split(/[\r\n]+/)) {- const candidate = line.trim();- if (candidate) out.paths.push(candidate);- }+ const receipt = dt.getData(WORKSPACE_PATH_TYPE);+ const paths = consumeWorkspaceDrag(receipt);+ if (paths) {+ out.paths = paths;return out;}- const raw = dt.getData("text/uri-list") || dt.getData("text/plain") || "";- for (const line of raw.split(/[\r\n]+/)) {- const candidate = line.trim();- if (!candidate || candidate.startsWith("#")) continue;- const unwrapped = unwrapFileUri(candidate);- if (looksLikePath(unwrapped)) out.paths.push(unwrapped);- }-- const named = new Set(- out.paths.map((p) => p.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? ""),- );+ // Never interpret text/plain, file:// URIs or forged workspace MIME as local+ // paths, even alongside real files. Upload only the bytes the browser grants.for (const file of Array.from(dt.files ?? [])) {// A directory dropped into a pane arrives as a zero-byte, type-less entry;// there is nothing to attach and copying it would produce an empty file.if (file.size === 0 && !file.type) continue;- if (named.has(file.name.toLowerCase())) continue;out.files.push(file);}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsxindex 0705ae729d..1177c76385 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx@@ -2,7 +2,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libraimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { renderHook } from "@testing-library/react";import { ExplorerPanel } from "./ExplorerPanel";-import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";+import { extractPaneDrop } from "@/components/agentic/paneDrop";import { activateTerminalLink } from "@/lib/terminalLinks";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";@@ -106,9 +106,13 @@ describe("ExplorerPanel", () => {render(<ExplorerPanel view="changes" />);const [row] = await screen.findAllByTestId("explorer-change-row");const data: Record<string, string> = {};- const dataTransfer = { setData: (type: string, value: string) => { data[type] = value; }, effectAllowed: "" };+ const dataTransfer = {+ setData: (type: string, value: string) => { data[type] = value; },+ getData: (type: string) => data[type] ?? "",+ effectAllowed: "",+ };fireEvent.dragStart(row, { dataTransfer });- expect(data[WORKSPACE_PATH_TYPE]).toBe("/code/app/src/app.ts");+ expect(extractPaneDrop(dataTransfer as DataTransfer).paths).toEqual(["/code/app/src/app.ts"]);});it("opens a changed file as a diff with removed and added lines", async () => {diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsxindex 4eef504a6f..043efec52f 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx@@ -23,7 +23,7 @@ import {type WorkspaceFileItem,type WorkspaceFilePreviewResponse,} from "@/lib/agenticIdeApi";-import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";+import { setWorkspaceDragPaths } from "@/components/agentic/paneDrop";import { AgentMark } from "@/components/agentic/AgentMark";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";@@ -68,7 +68,10 @@ const parentPath = (path: string) => path.split("/").slice(0, -1).join("/");/** Start a drag that a terminal pane turns into a file reference. */function startFileDrag(event: DragEvent, absolute: string): void {- event.dataTransfer.setData(WORKSPACE_PATH_TYPE, absolute);+ if (!setWorkspaceDragPaths(event.dataTransfer, [absolute])) {+ event.preventDefault();+ return;+ }event.dataTransfer.setData("text/plain", absolute);event.dataTransfer.effectAllowed = "copy";}diff --git a/jarvis/ui/web/frontend/src/components/society/office/spawnFiles.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/spawnFiles.test.tsxnew file mode 100644index 0000000000..a3c8db6573--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/office/spawnFiles.test.tsx@@ -0,0 +1,56 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { WORKSPACE_PATH_TYPE, setWorkspaceDragPaths } from "@/components/agentic/paneDrop";+import { NATIVE_DROP_EVENT } from "@/lib/nativeDrop";+import { useSpawnFiles } from "./spawnFiles";++function Holder() {+ const { handlers, held } = useSpawnFiles();+ return <div data-testid="holder" {...handlers}>{JSON.stringify(held.map(({ path, file }) => ({ path, file: file?.name })))}</div>;+}++function transfer(files: File[] = []) {+ const data = new Map<string, string>();+ return {+ types: ["Files", WORKSPACE_PATH_TYPE, "text/uri-list"],+ files,+ items: [],+ getData: (type: string) => data.get(type) ?? "",+ setData: (type: string, value: string) => data.set(type, value),+ } as unknown as DataTransfer;+}++afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++describe("spawn attachments keep the drag source boundary", () => {+ it("rejects a forged workspace path and file URI", () => {+ render(<Holder />);+ const dt = transfer();+ dt.setData(WORKSPACE_PATH_TYPE, "/private/secret.txt");+ dt.setData("text/uri-list", "file:///private/secret.txt");+ fireEvent.drop(screen.getByTestId("holder"), { dataTransfer: dt });+ expect(screen.getByTestId("holder").textContent).toBe("[]");+ });++ it("retains granted bytes without following native path hints", async () => {+ vi.stubGlobal("__JARVIS_EMBEDDED_DESKTOP", true);+ render(<Holder />);+ await act(async () => {+ fireEvent.drop(screen.getByTestId("holder"), {+ dataTransfer: transfer([new File(["offered"], "photo.png", { type: "image/png" })]),+ });+ window.dispatchEvent(new CustomEvent(NATIVE_DROP_EVENT, {+ detail: { paths: ["/private/photo.png"], names: ["photo.png"] },+ }));+ });+ expect(JSON.parse(screen.getByTestId("holder").textContent!)).toEqual([{ file: "photo.png" }]);+ });++ it("retains the selected internal explorer path", () => {+ render(<Holder />);+ const dt = transfer();+ setWorkspaceDragPaths(dt, ["/project/selected.txt"]);+ fireEvent.drop(screen.getByTestId("holder"), { dataTransfer: dt });+ expect(JSON.parse(screen.getByTestId("holder").textContent!)).toEqual([{ path: "/project/selected.txt" }]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/office/spawnFiles.ts b/jarvis/ui/web/frontend/src/components/society/office/spawnFiles.tsindex 0345f8b6b6..ebd2bf1822 100644--- a/jarvis/ui/web/frontend/src/components/society/office/spawnFiles.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/spawnFiles.ts@@ -4,8 +4,7 @@* A drop on a pane goes straight to that pane's terminal. Here the terminal* does not exist yet, so a drop is only READ now and handed to each new pane* once it is live. The reading is the pane's own — the same drag tracking- * (`usePaneFileDrag`), payload extraction (`paneDrop`) and desktop-shell path- * resolution (`waitForNativeDrop`) — so the two surfaces cannot disagree about+ * (`usePaneFileDrag`) and payload extraction (`paneDrop`) so the surfaces agree about* what a drop is.*/import { useCallback, useState, type ClipboardEvent } from "react";@@ -18,7 +17,6 @@ import {} from "@/components/agentic/paneDrop";import { usePaneFileDrag } from "@/components/agentic/paneFileDrag";import type { DropAttachment } from "@/lib/agenticIdeApi";-import { waitForNativeDrop } from "@/lib/nativeDrop";/** One held file: a real path the drag carried, or bytes it gave no path for. */export interface HeldFile {@@ -87,20 +85,9 @@ export function useSpawnFiles() {const { dragging, handlers } = usePaneFileDrag(useCallback((dt: DataTransfer) => {- // Both reads happen BEFORE any await: a DataTransfer empties the moment- // this handler returns, and the desktop shell only answers a listener- // that was already in place when the drop happened.- const payload = extractPaneDrop(dt);- void waitForNativeDrop().then((detail) => {- if (!detail?.paths.length) return hold(payload);- // Inside the desktop shell the real path beats a byte copy of the- // same file; drop the copies the shell just accounted for.- const named = new Set(detail.names.map((n) => n.toLowerCase()));- hold({- paths: Array.from(new Set([...payload.paths, ...detail.paths])),- files: payload.files.filter((f) => !named.has(f.name.toLowerCase())),- });- });+ // Native path hints can originate in foreign drag metadata on some+ // WebViews. Only granted bytes and internal explorer receipts attach.+ hold(extractPaneDrop(dt));},[hold],),