-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathpreload.ts
More file actions
719 lines (670 loc) · 25.6 KB
/
Copy pathpreload.ts
File metadata and controls
719 lines (670 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
// GRIDA-GG: desktop — install the `gg` bridge namespace (docs/wg/platform/hosted-ai.md)
// GRIDA-SEC-008 — expose only secret-free native-provider operations.
/**
* GRIDA-SEC-004 — Desktop agent-sidecar trust boundary (renderer side).
*
* Exposes `window.grida` via `contextBridge` **only when** the page
* pathname is `/desktop` or starts with `/desktop/`. Without this scope, any XSS on
* grida.co — a marketing page, a blog comment, a user-uploaded SVG
* preview — that ends up rendered inside the Electron window would
* see the bridge and reach the agent server.
*
* Path-check is fail-closed at preload-run time. `contextBridge.exposeInMainWorld`
* has no revocation API, so navigation after exposure is guarded in
* `desktop/src/window.ts`.
*
* See /SECURITY.md `GRIDA-SEC-004`.
*/
import { contextBridge, ipcRenderer, webUtils } from "electron";
import { AgentTransport } from "@grida/agent/transport";
import type {
AgentRunOptions,
AgentUIMessageChunk,
CreateSessionOptions,
DirectoryScopeDescriptor,
PatchSessionOptions,
SessionListFilter,
} from "@grida/agent";
import {
DESKTOP_BRIDGE_PROTOCOL,
IPC_CHANNELS,
type ConfirmOptions,
type DesktopBridge,
type DesktopHostAppInfo,
type HandshakeResponse,
type NavigationState,
type OpenDialogOptions,
type SaveDialogOptions,
type TerminalCreateOptions,
type TerminalHandlers,
type WorkspaceChangeEvent,
type WorkspaceChangeHandler,
} from "./bridge/contract";
const DESKTOP_PATH_ROOT = "/desktop";
const DESKTOP_PATH_PREFIX = `${DESKTOP_PATH_ROOT}/`;
function getCliArg(name: string): string | undefined {
const prefix = `--${name}=`;
const arg = process.argv.find((a) => a.startsWith(prefix));
return arg ? arg.slice(prefix.length) : undefined;
}
const appVersion = getCliArg("grida-version") ?? "0.0.0";
const appPlatform = process.platform;
function isDesktopPath(pathname: string): boolean {
return (
pathname === DESKTOP_PATH_ROOT || pathname.startsWith(DESKTOP_PATH_PREFIX)
);
}
const agentServerFetch: AgentTransport.Fetcher = async (path, init) => {
// GRIDA-SEC-004 — fetch fresh connection info for every request.
// The sidecar can restart on a new port with a new password; caching
// `{port,password}` in preload would make the next renderer call leak
// stale Authorization to whatever process later binds the old port.
const info = (await ipcRenderer.invoke(IPC_CHANNELS.AGENT_SERVER_INFO)) as {
port: number;
password: string;
};
const fetcher = AgentTransport.makeFetcher({
port: info.port,
password: info.password,
});
return await fetcher(path, init);
};
const agentClient = new AgentTransport.Client({ fetcher: agentServerFetch });
// One controller per active agent stream, keyed by sessionId. The
// AgentHost's StreamRegistry enforces one-run-per-session so a Map keyed
// by sessionId is enough — we don't need a separate streamId reverse-
// index. Fresh runs hold a UUID placeholder until the server's in-band
// `grida-session` frame yields the real id; the entry is then re-keyed.
const agentRuns = new Map<string, AbortController>();
// Long-lived session-status subscriptions, keyed by a per-subscription id so
// two subscribers to the same session never collide (cf. `agentRuns`, keyed by
// session). Each owns an AbortController that `unsubscribe_status` trips.
const statusSubs = new Map<string, AbortController>();
async function handshake(): Promise<HandshakeResponse> {
return await agentClient.handshake();
}
/**
* Per-window nav-history subscribers. The preload registers a single
* `ipcRenderer.on` for `WINDOW_NAVIGATION_CHANGED` and fans out to
* every React `useNavigationState()` consumer in this renderer.
*
* GRIDA-SEC-004 — the Electron event object is intentionally NOT
* forwarded to subscribers; only the structured-clone-safe payload
* crosses the contextBridge boundary (callbacks with `IpcRendererEvent`
* arguments would leak Node primitives like `sender` into the renderer
* realm, per Doyensec's preload analysis).
*/
const navigationListeners = new Set<(state: NavigationState) => void>();
ipcRenderer.on(
IPC_CHANNELS.WINDOW_NAVIGATION_CHANGED,
(_event, payload: NavigationState) => {
for (const listener of navigationListeners) {
try {
listener(payload);
} catch {
// Defensive — a misbehaving consumer shouldn't break dispatch
// for the rest. The error is intentionally swallowed; consumers
// own their try/catch boundaries.
}
}
}
);
ipcRenderer.on(IPC_CHANNELS.WORKSPACE_COMMAND, (_event, command: unknown) => {
if (!isDesktopPath(location.pathname)) return;
window.dispatchEvent(
new CustomEvent(IPC_CHANNELS.WORKSPACE_COMMAND, { detail: command })
);
});
// Main → renderer "bring this session into view" push (RFC `events`
// §click-to-attend): a notification click focused this window; the agent
// pane selects the named session. Same re-dispatch pattern as
// WORKSPACE_COMMAND — only the structured-clone payload crosses, never the
// Electron event object (GRIDA-SEC-004).
ipcRenderer.on(IPC_CHANNELS.AGENT_FOCUS_SESSION, (_event, payload: unknown) => {
if (!isDesktopPath(location.pathname)) return;
window.dispatchEvent(
new CustomEvent(IPC_CHANNELS.AGENT_FOCUS_SESSION, { detail: payload })
);
});
/**
* Per-terminal handler fanout for the PTY host's push channels. The
* preload mints each terminal id and registers its handlers here
* BEFORE invoking TERMINAL_CREATE, so the shell's first output frame
* (emitted as soon as the PTY spawns) can never race the subscription.
* Same payload-only discipline as the other `ipcRenderer.on` fanouts —
* the Electron event object never crosses the contextBridge
* (GRIDA-SEC-004).
*/
const terminalHandlers = new Map<string, TerminalHandlers>();
ipcRenderer.on(
IPC_CHANNELS.TERMINAL_DATA,
(_event, payload: { id: string; data: string }) => {
terminalHandlers.get(payload.id)?.on_data(payload.data);
}
);
ipcRenderer.on(
IPC_CHANNELS.TERMINAL_EXIT,
(_event, payload: { id: string; exit_code: number }) => {
const handlers = terminalHandlers.get(payload.id);
terminalHandlers.delete(payload.id);
handlers?.on_exit({ exit_code: payload.exit_code });
}
);
/**
* Workspace file-change fanout (issue #805). Same payload-only discipline
* as the terminal fanout: one module-level `ipcRenderer.on` routes each
* pushed batch to the renderer-supplied handler by subscription id; the
* Electron event object never crosses the contextBridge (GRIDA-SEC-004).
* The handler is registered under a preload-minted id BEFORE the
* SUBSCRIBE_CHANGES invoke, so no early event can race the subscription.
*/
const workspaceChangeHandlers = new Map<string, WorkspaceChangeHandler>();
ipcRenderer.on(
IPC_CHANNELS.WORKSPACE_CHANGE,
(
_event,
payload: { subscription_id: string; events: WorkspaceChangeEvent[] }
) => {
workspaceChangeHandlers.get(payload.subscription_id)?.(payload.events);
}
);
function installDesktopNavigationGuard(): void {
const assertAllowed = (url: string | URL | null | undefined) => {
if (url === null || url === undefined) return;
const next = new URL(String(url), window.location.href);
if (
next.origin === window.location.origin &&
!isDesktopPath(next.pathname)
) {
throw new Error(
`[grida] blocked desktop bridge navigation to ${next.pathname}`
);
}
};
const pushState = window.history.pushState.bind(window.history);
window.history.pushState = (data, unused, url) => {
assertAllowed(url);
return pushState(data, unused, url);
};
const replaceState = window.history.replaceState.bind(window.history);
window.history.replaceState = (data, unused, url) => {
assertAllowed(url);
return replaceState(data, unused, url);
};
window.addEventListener("popstate", () => {
if (!isDesktopPath(window.location.pathname)) {
window.location.replace("/desktop/welcome");
}
});
}
/**
* Open an agent SSE stream and fan out chunks to `onChunk`. Returns `null` only on the
* reconnect path when the agent server has no in-flight run for the given
* session — the caller falls back to DB hydration.
*
* Resolves with `{streamId, sessionId, done}`:
* - `streamId` is internal preload bookkeeping (today: equals the
* sessionId once the server echoes it; a UUID placeholder before
* that for fresh runs).
* - `done` resolves when upstream emits `[DONE]` or the socket
* closes cleanly; rejects on transport error; resolves on abort.
*
* **Why a hand-rolled SSE reader.** The browser's `EventSource` doesn't
* support custom headers (we need `Authorization: Basic`) and can't
* carry a request body. We use `fetch` + a manual line buffer on the
* `ReadableStream<Uint8Array>` body. `TextDecoderStream` would be
* cleaner but isn't reliably available across all Electron webContents.
*
* **Frame format**: standard AI SDK UI-message SSE —
* `data: <UIMessageChunk JSON>\n\n`, then `data: [DONE]\n\n`.
*/
type AgentOpenSpec =
| { kind: "run"; opts: AgentRunOptions }
| { kind: "reconnect"; session_id: string; last_event_id: number };
async function openAgentStream(
spec: AgentOpenSpec,
onChunk: (chunk: AgentUIMessageChunk) => void
): Promise<{
stream_id: string;
session_id: string;
done: Promise<void>;
} | null> {
const placeholderKey =
spec.kind === "reconnect" ? spec.session_id : crypto.randomUUID();
const controller = new AbortController();
agentRuns.set(placeholderKey, controller);
let handle: AgentTransport.AgentStreamHandle | null;
try {
handle =
spec.kind === "run"
? await agentClient.agent.run(spec.opts, onChunk, {
signal: controller.signal,
})
: await agentClient.agent.reconnect(
spec.session_id,
spec.last_event_id,
onChunk,
{ signal: controller.signal }
);
} catch (err) {
agentRuns.delete(placeholderKey);
throw err;
}
if (handle === null) {
agentRuns.delete(placeholderKey);
return null;
}
// Promote the registry key from the placeholder UUID to the real
// session id once the server echoes it. `abort(sessionId)` can then
// hit the controller in O(1) without scanning a reverse-index map.
const sessionId =
spec.kind === "reconnect" ? spec.session_id : handle.session_id;
let runKey = placeholderKey;
if (sessionId && sessionId !== placeholderKey) {
agentRuns.delete(placeholderKey);
agentRuns.set(sessionId, controller);
runKey = sessionId;
}
const done = handle.done.finally(() => {
agentRuns.delete(runKey);
});
return { stream_id: runKey, session_id: sessionId, done };
}
const bridge: DesktopBridge = {
protocol: DESKTOP_BRIDGE_PROTOCOL,
app: { version: appVersion, platform: appPlatform },
caps: {
agent: {
// This host accepts `{ path, base64 }` scratch seeds on agent runs.
scratch_seed_base64: true,
// Windows intentionally withholds confined run_command; a scratch-only
// PDF/archive would therefore be a path the agent cannot operate on.
scratch_binary_tools: process.platform !== "win32",
},
native: {
host_apps: true,
// Native-OS surfaces — always present in a desktop build.
window: true,
dialog: true,
// Native shell helpers only: external URLs, Finder/Explorer reveal,
// and File -> path resolution. Command execution is agent-host-internal
// for V1, not a public renderer bridge capability.
shell: true,
// Human-interactive terminal pane (GRIDA-SEC-004) — distinct from
// `shell` above and from the agent's sandboxed `run_command`.
terminal: true,
// Workspace file-change watcher (issue #805).
workspace_watch: true,
},
},
handshake,
account: {
sign_out: () => ipcRenderer.invoke(IPC_CHANNELS.ACCOUNT_SIGN_OUT),
},
// GRIDA-SEC-004 — onboarding gets two purpose-scoped main-process
// operations, never the daemon connection tuple or a generic dialog.
onboarding: {
get_default_workspace: () =>
ipcRenderer.invoke(IPC_CHANNELS.ONBOARDING_WORKSPACE_DEFAULT),
choose_workspace: () =>
ipcRenderer.invoke(IPC_CHANNELS.ONBOARDING_WORKSPACE_CHOOSE),
},
window: {
set_document_edited: (edited) =>
ipcRenderer.invoke(IPC_CHANNELS.WINDOW_SET_DOCUMENT_EDITED, edited),
set_represented_filename: (filePath) =>
ipcRenderer.invoke(
IPC_CHANNELS.WINDOW_SET_REPRESENTED_FILENAME,
filePath
),
close: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_CLOSE),
complete_onboarding: (workspaceId) =>
ipcRenderer.invoke(IPC_CHANNELS.WINDOW_COMPLETE_ONBOARDING, workspaceId),
navigation: {
state: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_NAVIGATION_STATE),
subscribe: (cb) => {
navigationListeners.add(cb);
return () => {
navigationListeners.delete(cb);
};
},
back: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_NAVIGATION_BACK),
forward: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_NAVIGATION_FORWARD),
},
},
dialog: {
confirm: (opts: ConfirmOptions) =>
ipcRenderer.invoke(IPC_CHANNELS.DIALOG_CONFIRM, opts),
open: (opts: OpenDialogOptions) =>
ipcRenderer.invoke(IPC_CHANNELS.DIALOG_OPEN, opts),
save_as: (opts: SaveDialogOptions) =>
ipcRenderer.invoke(IPC_CHANNELS.DIALOG_SAVE_AS, opts),
},
shell: {
open_external: (url) =>
ipcRenderer.invoke(IPC_CHANNELS.SHELL_OPEN_EXTERNAL, url),
show_item_in_folder: (filePath) =>
ipcRenderer.invoke(IPC_CHANNELS.SHELL_SHOW_ITEM_IN_FOLDER, filePath),
// Synchronous — `webUtils.getPathForFile` is itself sync, and the
// File object must reach this function with its internal path tag
// intact. The proxy `contextBridge` builds preserves that for live
// File refs (a structured-clone copy would lose it).
get_path_for_file: (file) => {
try {
return webUtils.getPathForFile(file);
} catch {
// No resolvable path (in-memory Blob, etc).
return "";
}
},
},
files: {
read: (docId) => agentClient.files.read(docId),
write: (docId, content) => agentClient.files.write(docId, content),
},
recent: {
list: () => agentClient.recent.list(),
touch: async (filePath) => {
await agentClient.recent.touch(filePath);
},
pin: async (filePath, pinned) => {
await agentClient.recent.pin(filePath, pinned);
},
forget: async (filePath) => {
await agentClient.recent.forget(filePath);
},
},
// GRIDA-SEC-004 — app-managed media stays behind purpose-scoped native IPC.
// The renderer receives opaque ids, path-free descriptors, and bytes only;
// unlike generation and workspace APIs, none of these calls use daemon HTTP.
media: {
list: () => ipcRenderer.invoke(IPC_CHANNELS.MEDIA_LIST),
read: (id) => ipcRenderer.invoke(IPC_CHANNELS.MEDIA_READ, id),
reveal: async (id) => {
await ipcRenderer.invoke(IPC_CHANNELS.MEDIA_REVEAL, id);
},
open_folder: async () => {
await ipcRenderer.invoke(IPC_CHANNELS.MEDIA_OPEN_FOLDER);
},
},
workspaces: {
list: () => agentClient.workspaces.list(),
open: (rootPath) => agentClient.workspaces.open(rootPath),
create: (input) => agentClient.workspaces.create(input),
pin: async (id, pinned) => {
await agentClient.workspaces.pin(id, pinned);
},
forget: async (id) => {
await agentClient.workspaces.forget(id);
},
readdir: (workspaceId, relPath) =>
agentClient.workspaces.readdir(workspaceId, relPath ?? ""),
read_file: (workspaceId, relPath) =>
agentClient.workspaces.read_file(workspaceId, relPath),
read_file_bytes: (workspaceId, relPath) =>
agentClient.workspaces.read_file_bytes(workspaceId, relPath),
// #924 — the streamable media `src` for the read-only viewer. Pure string
// build: a `grida-workspace://` URL the main-process protocol handler
// resolves by proxying to the sidecar's streamed `/workspaces/file` route.
// No credentials cross into the renderer (GRIDA-SEC-004). Constant host +
// both ids in the path so host canonicalization can't lowercase the id;
// keep in lockstep with `main/workspace-media-protocol.ts`.
media_url: (workspaceId, relPath) =>
`grida-workspace://workspace/${encodeURIComponent(workspaceId)}/${relPath
.split("/")
.map(encodeURIComponent)
.join("/")}`,
write_file: (workspaceId, relPath, content, expectedMtime) =>
agentClient.workspaces.write_file(
workspaceId,
relPath,
content,
expectedMtime
),
// Unlike its siblings, trash is a native host capability rather than
// an agent-sidecar operation: it routes to the main process (which
// re-validates workspace containment) and calls `shell.trashItem`.
trash_entry: (workspaceId, relPath) =>
ipcRenderer.invoke(IPC_CHANNELS.WORKSPACE_TRASH_ENTRY, {
workspace_id: workspaceId,
rel_path: relPath,
}) as Promise<void>,
subscribe_changes: async (workspaceId, onChange) => {
// Caller-mints-id (cf. terminal.create): register the handler under
// a preload-minted id before the invoke so no pushed event can land
// before the subscription exists.
const id = crypto.randomUUID();
workspaceChangeHandlers.set(id, onChange);
try {
await ipcRenderer.invoke(IPC_CHANNELS.WORKSPACE_SUBSCRIBE_CHANGES, {
id,
workspace_id: workspaceId,
});
} catch (err) {
workspaceChangeHandlers.delete(id);
throw err;
}
return { subscription_id: id };
},
unsubscribe_changes: async (subscriptionId) => {
workspaceChangeHandlers.delete(subscriptionId);
await ipcRenderer.invoke(
IPC_CHANNELS.WORKSPACE_UNSUBSCRIBE_CHANGES,
subscriptionId
);
},
},
terminal: {
create: async (opts: TerminalCreateOptions, handlers: TerminalHandlers) => {
// Caller-mints-id (cf. sessions.enqueue): registering the handlers
// under a preload-minted id before the invoke means no PTY output
// frame can be emitted before the subscription exists.
const id = crypto.randomUUID();
terminalHandlers.set(id, handlers);
try {
await ipcRenderer.invoke(IPC_CHANNELS.TERMINAL_CREATE, {
id,
workspace_id: opts.workspace_id,
cols: opts.cols,
rows: opts.rows,
});
} catch (err) {
terminalHandlers.delete(id);
throw err;
}
return { id };
},
write: (id: string, data: string) =>
ipcRenderer.invoke(IPC_CHANNELS.TERMINAL_WRITE, { id, data }),
resize: (id: string, cols: number, rows: number) =>
ipcRenderer.invoke(IPC_CHANNELS.TERMINAL_RESIZE, { id, cols, rows }),
kill: async (id: string) => {
terminalHandlers.delete(id);
await ipcRenderer.invoke(IPC_CHANNELS.TERMINAL_KILL, id);
},
},
host_apps: {
resolve_preferred: ({
workspace_id: workspaceId,
preferred_apps: preferredApps,
}) =>
ipcRenderer.invoke(IPC_CHANNELS.HOST_APPS_RESOLVE_PREFERRED, {
workspace_id: workspaceId,
preferred_apps: preferredApps,
}) as Promise<DesktopHostAppInfo[]>,
open_workspace: async ({ workspace_id: workspaceId, app_id: appId }) => {
await ipcRenderer.invoke(IPC_CHANNELS.HOST_APPS_OPEN_WORKSPACE, {
workspace_id: workspaceId,
app_id: appId,
});
},
},
secrets: {
has: (providerId) => agentClient.secrets.has(providerId),
set: async (providerId, key) => {
await agentClient.secrets.set(providerId, key);
},
delete: async (providerId) => {
await agentClient.secrets.delete(providerId);
},
},
providers: {
list_endpoints: () => agentClient.providers.list_endpoints(),
set_endpoint: async (config) => {
await ipcRenderer.invoke(IPC_CHANNELS.PROVIDER_ENDPOINT_SET, config);
},
delete_endpoint: async (id) => {
await ipcRenderer.invoke(IPC_CHANNELS.PROVIDER_ENDPOINT_DELETE, id);
},
info: () => agentClient.providers.info(),
probe_endpoint: (baseUrl) =>
ipcRenderer.invoke(IPC_CHANNELS.PROVIDER_ENDPOINT_PROBE, baseUrl),
detect_claude: () => agentClient.providers.detect_claude(),
},
// GRIDA-SEC-006 — hosted-session custody push (renderer → sidecar).
gg: {
set_session: async (session) => {
await agentClient.gg.set_session(session);
},
clear_session: async () => {
await agentClient.gg.clear_session();
},
status: () => agentClient.gg.status(),
},
// Native provider OAuth is main-owned. The renderer can start/cancel the
// user gesture and read secret-free status, but never receives codes,
// verifier/state values, or provider credentials.
chatgpt: {
connect: () => ipcRenderer.invoke(IPC_CHANNELS.CHATGPT_CONNECT),
cancel: async () => {
await ipcRenderer.invoke(IPC_CHANNELS.CHATGPT_CANCEL);
},
status: () => ipcRenderer.invoke(IPC_CHANNELS.CHATGPT_STATUS),
sign_out: () => ipcRenderer.invoke(IPC_CHANNELS.CHATGPT_SIGN_OUT),
},
images: {
generate: (req) => agentClient.images.generate(req),
},
video: {
generate: (req) => agentClient.video.generate(req),
},
threeD: {
generate: (req) => agentClient.threeD.generate(req),
},
audio: {
music: {
generate: (req) => agentClient.audio.music.generate(req),
},
soundEffects: {
generate: (req) => agentClient.audio.soundEffects.generate(req),
},
},
agent: {
attach_directory: async (file): Promise<DirectoryScopeDescriptor> => {
// GRIDA-SEC-004 — keep trusted-gesture provenance and path custody in
// preload. `getPathForFile` resolves only an OS-backed File (a JS-created
// File yields an empty string); the renderer receives only the daemon's
// opaque scope descriptor, never this absolute path.
let directoryPath = "";
try {
directoryPath = webUtils.getPathForFile(file);
} catch {
// Invalid/non-File values fail closed below; no daemon call is made.
}
if (!directoryPath) {
throw new Error("directory drop is not backed by a local path");
}
return await agentClient.directory_scopes.attach(directoryPath);
},
run: (opts, onChunk) =>
// Fresh runs always return a stream (only `reconnect` may return
// null on 404); cast to the non-nullable shape DesktopBridge expects.
openAgentStream({ kind: "run", opts }, onChunk) as Promise<{
stream_id: string;
session_id: string;
done: Promise<void>;
}>,
abort: async (sessionId) => {
await agentClient.agent.abort(sessionId);
const controller = agentRuns.get(sessionId);
if (controller) {
agentRuns.delete(sessionId);
controller.abort();
}
},
reconnect: (sessionId, lastEventId, onChunk) =>
openAgentStream(
{
kind: "reconnect",
session_id: sessionId,
last_event_id: lastEventId,
},
onChunk
),
},
sessions: {
list: (filter?: SessionListFilter) => agentClient.sessions.list(filter),
get: (id: string) => agentClient.sessions.get(id),
create: (opts: CreateSessionOptions) => agentClient.sessions.create(opts),
patch: (id: string, opts: PatchSessionOptions) =>
agentClient.sessions.patch(id, opts),
delete: (id: string) => agentClient.sessions.delete(id),
list_messages: (id: string) => agentClient.sessions.list_messages(id),
rewind: (id: string, fromMessageId: string, opts?: { restore?: boolean }) =>
agentClient.sessions.rewind(id, fromMessageId, opts),
fork: (
id: string,
fromMessageId: string,
metadata?: Record<string, unknown>
) => agentClient.sessions.fork(id, fromMessageId, metadata),
compact: (id: string) => agentClient.sessions.compact(id),
enqueue: (id: string, message: { id?: string; text: string }) =>
agentClient.sessions.enqueue(id, message),
list_queued: (id: string) => agentClient.sessions.list_queued(id),
cancel_queued: (id: string, messageId: string) =>
agentClient.sessions.cancel_queued(id, messageId),
subscribe_status: async (id, onStatus) => {
const subscriptionId = crypto.randomUUID();
const controller = new AbortController();
statusSubs.set(subscriptionId, controller);
try {
const { done } = await agentClient.sessions.subscribe_status(
id,
onStatus,
{ signal: controller.signal }
);
return {
subscription_id: subscriptionId,
done: done.finally(() => {
statusSubs.delete(subscriptionId);
}),
};
} catch (err) {
// `useSessionStatus` reconnects indefinitely. A failed handshake has
// no `done` promise whose finally can clean this registry entry, so
// release it here or every retry leaks one controller in preload.
if (statusSubs.get(subscriptionId) === controller) {
statusSubs.delete(subscriptionId);
}
controller.abort();
throw err;
}
},
unsubscribe_status: async (subscriptionId) => {
const controller = statusSubs.get(subscriptionId);
if (controller) {
statusSubs.delete(subscriptionId);
controller.abort();
}
},
},
};
// On Electron 42+ `window.location` is populated at preload-run time;
// the bridge is installed synchronously when the URL is under
// `/desktop/*`. A pathname outside that prefix is the structural
// guarantee that XSS on the main grida.co marketing pages can't
// reach the agent server (`GRIDA-SEC-004`).
if (isDesktopPath(window.location.pathname)) {
installDesktopNavigationGuard();
contextBridge.exposeInMainWorld("grida", bridge);
}