TypeScript
fix(desktop): save and copy any image the app can show (#29079)
Theo Browne0338e99fe359
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.tsindex dc9c47e0427..a46dbafab0f 100644--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts@@ -40,6 +40,7 @@ import {getSystemLocale,getWindowFullscreenState,openExternal,+ readMedia,openSystemSettings,checkSystemPermission,pasteAsText,@@ -141,6 +142,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"yield* ipc.handle(setTheme);yield* ipc.handle(showContextMenu);yield* ipc.handle(openExternal);+ yield* ipc.handle(readMedia);yield* ipc.handle(receiveProviderAuthCallback);yield* ipc.handle(cancelProviderAuthCallback);yield* ipc.handle(openSystemSettings);diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.tsindex 538dd06b0b4..0f125c05de3 100644--- a/apps/desktop/src/ipc/channels.ts+++ b/apps/desktop/src/ipc/channels.ts@@ -5,6 +5,7 @@ export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";export const SET_THEME_CHANNEL = "desktop:set-theme";export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";+export const READ_MEDIA_CHANNEL = "desktop:read-media";export const OPEN_SYSTEM_SETTINGS_CHANNEL = "desktop:open-system-settings";export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";export const MENU_ACTION_CHANNEL = "desktop:menu-action";diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.tsindex eacc92c9499..2ddc6728917 100644--- a/apps/desktop/src/ipc/methods/window.test.ts+++ b/apps/desktop/src/ipc/methods/window.test.ts@@ -9,6 +9,7 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import { vi } from "vite-plus/test";+import type * as Electron from "electron";const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({focusedWebContents: vi.fn(),@@ -33,6 +34,7 @@ import {installRelayTelemetryEnabled,pickProjectFavicon,probeRemoteEditors,+ readMedia,} from "./window.ts";const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {@@ -234,6 +236,54 @@ describe("installRelayTelemetryEnabled", () => {);});+describe("readMedia", () => {+ it.effect("reads http(s) media only for the main window", () =>+ Effect.gen(function* () {+ const mib = new Uint8Array(1024 * 1024);+ const fetch = vi.fn(async (url: string) => {+ if (url.endsWith("/missing.png")) return new Response("Not Found", { status: 404 });+ if (url.endsWith("/small.png")) return new Response(new Uint8Array([1, 2]));+ let sent = 0;+ // 257 MiB from one reused chunk: over the cap without allocating it.+ const huge = new ReadableStream<Uint8Array>({+ pull: (controller) => (sent++ < 257 ? controller.enqueue(mib) : controller.close()),+ });+ return new Response(huge);+ });+ const main = {+ webContents: { id: 1, session: { fetch } },+ } as unknown as Electron.BrowserWindow;+ const read = (url: string, senderId: number) =>+ readMedia+ .handler(url, { sender: { id: senderId } })+ .pipe(+ Effect.provide(+ Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(main) }),+ ),+ );++ assert.strictEqual(yield* read("https://example.com/a.png", 2), null);+ assert.strictEqual(yield* read("file:///etc/passwd", 1), null);+ assert.strictEqual(fetch.mock.calls.length, 0);+ assert.deepEqual(yield* read("https://example.com/small.png", 1), {+ status: 200,+ mimeType: "",+ data: Buffer.from([1, 2]),+ });+ assert.deepEqual(yield* read("https://example.com/missing.png", 1), {+ status: 404,+ mimeType: "text/plain;charset=UTF-8",+ data: new Uint8Array(),+ });+ assert.deepEqual(yield* read("https://example.com/huge.mp4", 1), {+ status: 413,+ mimeType: "",+ data: new Uint8Array(),+ });+ }),+ );+});+describe("pickProjectFavicon", () => {const pickerLayer = (pickFiles: () => Effect.Effect<Array<string>>,diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.tsindex 473d1874078..63b8db03dad 100644--- a/apps/desktop/src/ipc/methods/window.ts+++ b/apps/desktop/src/ipc/methods/window.ts@@ -2,6 +2,7 @@ import {ContextMenuItemSchema,DesktopAppBrandingSchema,DesktopEnvironmentBootstrapSchema,+ DesktopMediaReadSchema,DesktopThemeSchema,EDITORS,EditorId,@@ -311,6 +312,47 @@ export const openExternal = DesktopIpc.makeIpcMethod({}),});+const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;++// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.+export const readMedia = DesktopIpc.makeIpcMethod({+ channel: IpcChannels.READ_MEDIA_CHANNEL,+ payload: Schema.String,+ result: Schema.NullOr(DesktopMediaReadSchema),+ handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) {+ const window = yield* (yield* ElectronWindow.ElectronWindow).main;+ if (+ event === undefined ||+ Option.isNone(window) ||+ window.value.webContents.id !== event.sender.id ||+ !/^https?:$/.test(URL.parse(url)?.protocol ?? "")+ ) {+ return null;+ }+ const session = window.value.webContents.session;+ return yield* Effect.tryPromise(async () => {+ // Like an <img>, send the session's cookies.+ const response = await session.fetch(url, { credentials: "include" });+ const mimeType = response.headers.get("content-type") ?? "";+ if (!response.ok || !response.body) {+ await response.body?.cancel();+ return { status: response.status, mimeType, data: new Uint8Array() };+ }+ // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.+ const chunks: Uint8Array[] = [];+ let size = 0;+ for await (const chunk of response.body) {+ size += chunk.byteLength;+ if (size > READ_MEDIA_MAX_BYTES) {+ return { status: 413, mimeType, data: new Uint8Array() };+ }+ chunks.push(chunk);+ }+ return { status: response.status, mimeType, data: Buffer.concat(chunks) };+ }).pipe(Effect.orElseSucceed(() => null));+ }),+});+export const openSystemSettings = DesktopIpc.makeIpcMethod({channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,payload: SystemSettingsPaneSchema,diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 950ed972c64..da56807186a 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -202,6 +202,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {cancelProviderAuthCallback: (url: string) =>ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url),openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),+ readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url),checkSystemPermission: (pane: string) =>ipcRenderer.invoke(IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL, pane),openSystemSettings: (pane: string) =>diff --git a/apps/web/src/components/media/mediaContent.test.ts b/apps/web/src/components/media/mediaContent.test.tsindex fb95a7e0eac..03d5185bb90 100644--- a/apps/web/src/components/media/mediaContent.test.ts+++ b/apps/web/src/components/media/mediaContent.test.ts@@ -55,3 +55,22 @@ it("keeps remote media on the fetch path", async () => {expect(await readMediaPng("https://example.com/image.png")).toEqual(png);expect(fetch).toHaveBeenCalledWith("https://example.com/image.png");});++it("reads media the renderer cannot fetch through the desktop main process", async () => {+ using fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("Failed to fetch"));+ const readMedia = vi.fn().mockResolvedValue({+ status: 200,+ mimeType: "image/png",+ data: new Uint8Array(PNG_BYTES),+ });+ vi.stubGlobal("window", { desktopBridge: { readMedia } });+ try {+ const png = await readMediaPng("https://example.com/image.png");++ expect(fetch).toHaveBeenCalledOnce();+ expect(readMedia).toHaveBeenCalledWith("https://example.com/image.png");+ expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES);+ } finally {+ vi.unstubAllGlobals();+ }+});diff --git a/apps/web/src/components/media/mediaContent.ts b/apps/web/src/components/media/mediaContent.tsindex 4b1edab6a3d..a5a4cec6114 100644--- a/apps/web/src/components/media/mediaContent.ts+++ b/apps/web/src/components/media/mediaContent.ts@@ -40,19 +40,28 @@ function readDataUrlBlob(src: string): Blob {}}+async function fetchMediaBlob(src: string): Promise<Blob> {+ const response = await fetch(src).catch(() => null);+ if (response?.ok) return response.blob();+ // An <img> can show media that fetch() may not read (CORS, CSP, cookies); desktop reads it natively.+ const desktop = typeof window === "undefined" ? undefined : window.desktopBridge;+ const native =+ desktop && /^https?:/i.test(src) ? await desktop.readMedia(src).catch(() => null) : null;+ if (native && native.status >= 200 && native.status < 300) {+ return new Blob([new Uint8Array(native.data)], { type: native.mimeType });+ }+ const status = native?.status ?? response?.status;+ if (status !== undefined) throw new Error(`The file could not be fetched (HTTP ${status}).`);+ throw new Error(+ desktop+ ? "The file could not be fetched. Check the connection and try again."+ : "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.",+ );+}+async function readMediaBlob(src: string): Promise<Blob> {if (/^data:/i.test(src)) return readDataUrlBlob(src);- let response: Response;- try {- response = await fetch(src);- } catch (cause) {- throw new Error(- "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.",- { cause },- );- }- if (!response.ok) throw new Error(`The file could not be fetched (HTTP ${response.status}).`);- const blob = await response.blob();+ const blob = await fetchMediaBlob(src);if (blob.type.split(";", 1)[0] === "text/html") {throw new Error("This link returned a web page instead of media. Open the original URL.");}diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex 59f8fd12c3f..5aa9acf2773 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -1012,6 +1012,13 @@ export const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({data: Schema.Uint8Array,});+export const DesktopMediaReadSchema = Schema.Struct({+ status: Schema.Number,+ mimeType: Schema.String,+ data: Schema.Uint8Array,+});+export type DesktopMediaRead = typeof DesktopMediaReadSchema.Type;+export const SystemSettingsPaneSchema = Schema.Literals(["full-disk-access"]);export type SystemSettingsPane = typeof SystemSettingsPaneSchema.Type;@@ -1099,6 +1106,8 @@ export interface DesktopBridge {receiveProviderAuthCallback: (authorizationUrl: string) => Promise<string>;cancelProviderAuthCallback: (authorizationUrl: string) => Promise<void>;openExternal: (url: string) => Promise<boolean>;+ /** Reads http(s) media in the main process, outside renderer CORS and CSP; null on network failure. */+ readMedia: (url: string) => Promise<DesktopMediaRead | null>;openSystemSettings: (pane: SystemSettingsPane) => Promise<boolean>;checkSystemPermission: (pane: SystemSettingsPane) => Promise<boolean>;probeRemoteEditors: () => Promise<readonly EditorId[]>;