Repository navigation
Expand file tree
/
Copy pathpreload.js
More file actions
430 lines (416 loc) · 24.3 KB
/
Copy pathpreload.js
File metadata and controls
430 lines (416 loc) · 24.3 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
const { contextBridge, ipcRenderer, webUtils } = require("electron");
// Live `watchCursorAway` subscriptions in this renderer; see that method.
let cursorAwaySubscribers = 0;
// Whether this document has sent `navigate-ready`; see `onNavigate`.
let navigateReadySent = false;
contextBridge.exposeInMainWorld("kirocrew", {
platform: process.platform,
isElectron: true,
// True when this window is a frameless Linux window (a runtime decision --
// desktop environment + operator override -- made in main.js, carried here
// via webPreferences.additionalArguments). The SPA reserves header space
// for the injected caption controls only when this is set.
linuxFrameless: process.argv.includes("--kc-linux-frameless"),
// Absolute filesystem path for a File the OS handed the renderer (drag-drop,
// file input). Browsers deliberately hide real paths, and Electron removed
// File.path, so webUtils in the preload is the only remaining bridge. Returns
// "" when no path can be resolved (synthetic File) so callers can treat any
// falsy result as "no path available" and keep their browser fallback.
getPathForFile: (file) => {
try {
return webUtils.getPathForFile(file) || "";
} catch {
return "";
}
},
// Caption controls for the frameless Linux window. macOS keeps its traffic
// lights and Windows its titleBarOverlay when frameless; Linux gets neither,
// so main.js injects header buttons that round-trip through this channel.
// The splash (loading.html) also sends `close` through it on every
// platform, since it can be painted into a window whose native close
// control is hidden. The action vocabulary and the per-platform admission
// are validated in the main process (handleWindowControl /
// applyWindowControl).
windowControl: (action) => ipcRenderer.send("window-control", String(action || "")),
// Announce a download the app is about to start, so the Electron shell's
// will-download handler auto-saves ONLY downloads the app explicitly asked
// for (the export path). Without a matching announcement a same-origin or
// blob download gets the normal Save dialog instead of a silent save. The
// main process keys the expectation by THIS frame's own origin; `filename`
// is the leaf name the download will carry. No-op (absent) in a plain
// browser, where downloadBlob falls back to the browser's own handling.
expectDownload: (filename) => ipcRenderer.send("download:expect", String(filename || "")),
});
contextBridge.exposeInMainWorld("electronAPI", {
// Evict the HTTP cache of one remote-crew pane origin (a loopback tunnel
// port) before reloading it. Used when the pane's module graph reports a
// load error: a hashed chunk the gateway once answered 404+immutable is
// replayed from cache forever, and only eviction gets the pane past Loading.
// Resolves to whether a purge ran; the caller reloads regardless.
clearPaneHttpCache: (origin) =>
ipcRenderer.invoke("pane:clear-http-cache", String(origin || "")),
// Copy the image drawn at a main-frame point (CSS pixels) to the OS clipboard.
copyImageAt: (x, y) => ipcRenderer.invoke("image:copy-at", Number(x), Number(y)),
onStatus: (cb) => {
const handler = (_e, msg) => cb(msg);
ipcRenderer.on("status", handler);
return () => ipcRenderer.removeListener("status", handler);
},
// Boot-reveal handshake: main.js sends "boot-ready" once the gateway is up;
// loading.html replies "boot-complete" after its reveal animation fades out.
onBootReady: (cb) => {
const handler = () => cb();
ipcRenderer.on("boot-ready", handler);
return () => ipcRenderer.removeListener("boot-ready", handler);
},
bootComplete: () => ipcRenderer.send("boot-complete"),
// Persist the user's resolved theme accent (a hex string) so the next launch's
// boot splash (loading.html) can paint in the user's chosen colour. Read back
// by main.js and injected as a query param — see showLoadingThenConnect.
setThemeAccent: (hex) => ipcRenderer.send("theme-accent-changed", String(hex || "")),
// Report the user's dark/light mode PREFERENCE ("system" | "dark" | "light")
// so main.js can set `nativeTheme.themeSource` to match. Must be the
// preference, not the resolved mode: pinning themeSource to dark/light also
// pins `prefers-color-scheme`, which is what Auto resolves through.
setThemeMode: (pref) => ipcRenderer.send("theme-mode-changed", String(pref || "")),
// Report the RESOLVED dark/light mode ("dark" | "light") so main.js can sync
// the Windows titleBarOverlay colors. Separate from setThemeMode because that
// carries the preference (system/dark/light) while this carries the outcome.
setTitleBarOverlayTheme: (mode) => ipcRenderer.send("titlebar-overlay-theme", String(mode || "")),
// Focus mode: report whether the dashboard header is on screen so the native
// macOS traffic lights can follow it. They are AppKit views painted at a window
// coordinate, so the renderer cannot hide or move them itself — with the header
// collapsed they would sit over the reclaimed content.
setFocusModeChrome: (visible) => ipcRenderer.send("focus-mode-chrome", !!visible),
// Focus mode: how far the cursor has travelled OUTSIDE this window, reduced to
// the single transition the reveal overlays care about. Call it once the
// pointer has left the window with an overlay open; the callback fires exactly
// once, with `true` when the cursor is far enough away that the overlay should
// be dismissed and `false` when it came back inside instead. Returns an
// unsubscribe that also disarms the main-process poll, so nothing polls while
// no overlay is waiting on an answer.
//
// This cannot be done in the page: the renderer gets no mouse events past a
// window edge, which is why the reveal's own dismissal has to round-trip
// through the main process at all. A plain browser has no bridge here.
//
// The main process keeps ONE watch per window, but several callers in this
// renderer can be waiting at once (the top bar, the rail, a pane relayed
// through this frame). So subscriptions are counted here: every subscribe
// (re-)arms the watch, and only the last unsubscribe disarms it -- one caller
// letting go must not cancel the answer another is still waiting for.
watchCursorAway: (cb) => {
const handler = (_e, away) => cb(!!away);
ipcRenderer.on("focus-mode:cursor-away", handler);
cursorAwaySubscribers += 1;
ipcRenderer.send("focus-mode-watch-cursor", true);
let live = true;
return () => {
if (!live) return;
live = false;
ipcRenderer.removeListener("focus-mode:cursor-away", handler);
cursorAwaySubscribers -= 1;
if (cursorAwaySubscribers === 0) ipcRenderer.send("focus-mode-watch-cursor", false);
};
},
// Renderer signals main process to show/hide the DevTools menu item.
setDevMode: (enabled) => ipcRenderer.send("dev-mode-changed", !!enabled),
// Windows custom titlebar: menu surfaces render in the dashboard so hover
// can switch between them; command execution stays in the main process.
getAppMenuItems: (id) => ipcRenderer.invoke("app-menu:items", id),
executeAppMenuItem: (id, index) => ipcRenderer.send("app-menu:execute", id, index),
// App-menu navigation: main.js sends an in-app path ("/settings",
// "/settings/about") when the user picks Settings…/About from the
// native application menu; the SPA routes to it (see App.tsx).
onNavigate: (cb) => {
const handler = (_e, path) => cb(path);
ipcRenderer.on("navigate", handler);
// Tell the main process this document now has a `navigate` listener, so a
// kirocrew:// link it is holding goes to a listener instead of to nobody.
// Once per document: the SPA re-subscribes whenever its router callbacks
// change identity, and only the first subscription is news.
if (!navigateReadySent) {
navigateReadySent = true;
ipcRenderer.send("navigate-ready");
}
return () => ipcRenderer.removeListener("navigate", handler);
},
// View > Toggle Focus Mode: main.js asks the dashboard to flip focus mode,
// whose own toggle is hidden while it is on.
onToggleFocusMode: (cb) => {
const handler = () => cb();
ipcRenderer.on("focus-mode:toggle", handler);
return () => ipcRenderer.removeListener("focus-mode:toggle", handler);
},
// A macOS swipe main.js relays as one route-history step: -1 Back, 1 Forward
// (see swipe-history.js). The SPA takes it through its guarded history step.
onHistoryStep: (cb) => {
const handler = (_e, delta) => cb(delta);
ipcRenderer.on("history:step", handler);
return () => ipcRenderer.removeListener("history:step", handler);
},
// The trackpad's real finger-down ("begin") and finger-up ("end"), which
// main.js reads off Chromium's gesture-scroll events (see scroll-touch.js).
// macOS only; the page's swipe reader uses it to release a drag on the real
// lift-off. Anything but the two words is dropped here.
onScrollTouch: (cb) => {
const handler = (_e, phase) => {
if (phase === "begin" || phase === "end") cb(phase);
};
ipcRenderer.on("scroll-touch", handler);
return () => ipcRenderer.removeListener("scroll-touch", handler);
},
// Second argument: whether the macOS menu bar can slide over the window.
// Only an explicit `menuBarOverlap: false` from main turns it off, so a
// missing or malformed payload keeps the renderer's menu-bar band.
onFullScreenChanged: (callback) => {
const handler = (_event, isFullScreen, info) =>
callback(!!isFullScreen, !(info && info.menuBarOverlap === false));
ipcRenderer.on("fullscreen-changed", handler);
return () => ipcRenderer.removeListener("fullscreen-changed", handler);
},
// Dock/taskbar badge (RFC notification bus Phase 4): the renderer pushes
// its unread (critical+default) count; main.js applies app.setBadgeCount.
// No-op on platforms without badge support (Windows) -- Electron handles it.
setBadgeCount: (count) => ipcRenderer.send("badge:set", count),
// Mic-denial recovery. The renderer only ever sees getUserMedia's
// NotAllowedError — it cannot tell "the OS refused" from "Electron refused",
// and it cannot open System Settings itself. So when a mic capture is denied
// it pings the main process, which checks the real OS status and shows the
// Privacy-pane dialog only if macOS is actually the one saying no. Without
// this the toast is a dead end: macOS never re-prompts after a denial.
reportMicDenied: () => ipcRenderer.send("mic:denied"),
// Renderer memory trajectory (see src/lib/memoryWatch.ts). Fields are coerced
// here because preload is the trust boundary: the main process writes them into
// a log line, so a renderer bug must not be able to put an object or an
// unbounded string there. Fire-and-forget — the renderer never waits on a
// diagnostic.
//
// A null metric is forwarded as null, NOT as 0 or -1. "this channel does not
// exist in this realm" and "this channel read zero" lead to opposite
// conclusions, and the instrument this replaces collapsed a genuine 0 into a
// sentinel with `Number(x) || -1`.
reportMemorySample: (s) =>
ipcRenderer.send("memory-sample", {
realm: String((s && s.realm) || "?").slice(0, 60),
usedHeapKB: Number.isFinite(s && s.usedHeapKB) ? s.usedHeapKB : null,
limitHeapKB: Number.isFinite(s && s.limitHeapKB) ? s.limitHeapKB : null,
externalKB: Number.isFinite(s && s.externalKB) ? s.externalKB : null,
}),
// The object-heap half of the external-memory subtraction. The main world has
// no `process` under contextIsolation, but the preload shares the renderer's
// v8::Isolate, so `usedHeapSize` here describes the same heap that
// `performance.memory` reports in the page — which is what makes
// `usedJSHeapSize - usedHeapSize` a valid read of V8 external memory rather
// than a comparison of two different heaps. Returns null when Electron does not
// expose the API, so the caller reports the channel as unavailable instead of
// inventing a figure.
heapStatisticsKB: () => {
try {
if (typeof process.getHeapStatistics !== "function") return null;
const stats = process.getHeapStatistics();
const used = stats && stats.usedHeapSize;
return { usedHeapKB: Number.isFinite(used) ? used : null };
} catch {
return null;
}
},
// The system-wide summon hotkey as ACTUALLY bound by main.js (registration
// can degrade to the default or to nothing when a key is taken), so the
// shortcuts UI advertises what really works. Resolves
// { accelerator, default } — accelerator is "" when nothing is bound.
getGlobalHotkey: () => ipcRenderer.invoke("global-hotkey:get"),
});
// Local-gateway switch for the Settings > Developer toggle. The choice lives in
// the app's own config, which page JS cannot read or write, so the renderer
// round-trips through main.js. Both calls resolve with the stored value.
// Absent in plain browsers and in the PWA — the renderer hides the toggle when
// the bridge is missing, since a browser tab has no local gateway to manage.
contextBridge.exposeInMainWorld("localGatewayAPI", {
get: () => ipcRenderer.invoke("local-gateway:get"),
set: (enabled) => ipcRenderer.invoke("local-gateway:set", !!enabled),
});
// First-run setup's "connect to a crew on another machine" exit. `available`
// resolves true only where `start` can work; `start` opens the remote-crew form
// and resolves "switching", "cancelled" or "unavailable". Neither takes an
// argument: the main process decides everything from the sender. Absent in
// plain browsers, where setup has no local gateway to replace.
contextBridge.exposeInMainWorld("remoteCrewSetupAPI", {
available: () => ipcRenderer.invoke("first-run:can-use-remote-crew"),
start: () => ipcRenderer.invoke("first-run:use-remote-crew"),
});
// Crash-artifact notice for the dashboard banner (CrashReportNotice).
//
// The app already captures a minidump and, on macOS, the OS writes an .ips
// report — and until now nothing ever mentioned that either exists, which is how
// a main-process crash reaches us as "it closed by itself" with the evidence
// still unread on the reporter's disk. This bridge is what closes that loop.
//
// `get` resolves { newCount } and NOTHING else: no paths, no filenames, no
// exception codes, not even a timestamp. `reveal` takes no argument — main.js knows
// where the log is from the scan it performed, so this cannot be turned into a
// request to open an arbitrary file. Absent in plain browsers and in the PWA,
// where there is no local disk to reveal; the banner hides itself.
contextBridge.exposeInMainWorld("crashReportsAPI", {
get: () => ipcRenderer.invoke("crash-reports:get"),
reveal: () => ipcRenderer.invoke("crash-reports:reveal"),
});
// Read-only WSL2 host-runtime readout for the Host runtime card on System >
// Services (HostRuntimeCard). Detection only — no config writes, no
// persistence. The main-process handler rejects every sender whose gateway is
// not genuinely local, so a connection window pointed at a remote gateway
// gets a rejection here rather than the host's distro inventory. Absent in
// plain browsers — the card treats a missing bridge as "not an Electron
// shell" and renders nothing.
contextBridge.exposeInMainWorld("wslAPI", {
detect: () => ipcRenderer.invoke("wsl:detect"),
});
// What the main window's close button does: "background" or "quit". The main
// process returns the stored value only to the main window's own dashboard.
// Absent in plain browsers and in the PWA.
contextBridge.exposeInMainWorld("closeActionAPI", {
get: () => ipcRenderer.invoke("close-action:get"),
set: (action) => ipcRenderer.invoke("close-action:set", String(action || "")),
});
// File-open bridge for the chat path chip's "Open in editor" affordance. Hands
// a filesystem PATH — never a URL scheme — to the main process, which validates
// it and calls shell.openPath so the file opens in the OS default handler on the
// user's own machine. Resolves { ok, error? }. Absent in a plain browser and in
// the PWA — the renderer treats a missing bridge as "cannot open externally" and
// hides the control, keeping the built-in viewer as the only path there.
contextBridge.exposeInMainWorld("fileOpenAPI", {
open: (filePath) => ipcRenderer.invoke("dashboard:open-file", String(filePath || "")),
});
// Native folder chooser for the project picker's "Open system folder picker"
// button. Neither call passes anything to the main process: the dialog's
// options are fixed there. `available()` resolves whether this window's gateway
// runs on this machine (the main process answers false for a connection window
// pointed at a remote gateway).
// `pick()` invokes `dashboard:pick-folder`, which runs the same checks and opens
// the dialog; it resolves the chosen absolute folder, or null when the user
// cancels, and rejects when the shell refuses or no dialog could be shown.
// Absent in a plain browser and in the PWA -- the picker hides the button there
// and keeps its in-app browser as the only path.
contextBridge.exposeInMainWorld("folderPickAPI", {
available: () => ipcRenderer.invoke("dashboard:can-pick-folder"),
pick: () => ipcRenderer.invoke("dashboard:pick-folder"),
});
// External terminal bridge for the Files tab's "Open in external terminal" row
// and its Settings picker. `detect` resolves { apps: [{id, label}], capable },
// the allowlisted terminal apps installed on this machine; for a window whose
// gateway is not this machine's it resolves { apps: [], capable: false }, so the
// row and the picker stay hidden there. `open` hands the main process the
// opaque grant the gateway answered POST /api/terminal/external with, and
// resolves { ok, app?, error? }; the main process redeems the grant at the
// gateway and starts nothing without it, so no app name, path or argument
// crosses this bridge. `open` rejects for a window whose gateway is not this
// machine's. Absent in a plain browser and the PWA, where the row is hidden.
contextBridge.exposeInMainWorld("externalTerminalAPI", {
detect: () => ipcRenderer.invoke("external-terminal:detect"),
open: (grant) => ipcRenderer.invoke("external-terminal:open", String(grant || "")),
});
// Native zoom bridge for the Settings > Display "Zoom Level" stepper.
// Chromium's per-origin zoom (the thing Cmd/Ctrl +/- changes) is not
// reachable from page JS, so the renderer round-trips through main.js.
// All three calls resolve with the applied zoom factor. Absent in plain
// browsers — the renderer treats a missing bridge as "zoom not controllable"
// and shows a shortcut hint instead of the stepper.
contextBridge.exposeInMainWorld("zoomAPI", {
get: () => ipcRenderer.invoke("zoom:get"),
set: (factor) => ipcRenderer.invoke("zoom:set", factor),
step: (dir) => ipcRenderer.invoke("zoom:step", dir),
});
// Native browser panel bridge. The Browser side panel is a real embedded
// Chromium view owned by the main process, composited over the panel rect —
// not an iframe and not in the React tree. So the renderer has to (a) report
// the rectangle it laid out, and (b) report when one of its own overlays covers
// that rectangle, since the native layer paints above the SPA and would occlude
// it. Every call resolves with the view's state ({open, visible, bounds, url}).
//
// Every call takes a `panelId` — the dashboard renders one Browser panel per
// chat session, and each gets its own view, control plane and agent-act
// authorization. A single per-window slot let two sessions clobber each other.
//
// Absent in a plain browser — the renderer treats a missing bridge as "no native
// panel available" and falls back to the streamed-frame transport.
contextBridge.exposeInMainWorld("browserAPI", {
open: (panelId, url) => ipcRenderer.invoke("browser:open", panelId, url),
navigate: (panelId, url) => ipcRenderer.invoke("browser:navigate", panelId, url),
setBounds: (panelId, rect, viewport) =>
ipcRenderer.invoke("browser:set-bounds", panelId, rect, viewport),
setOverlayActive: (panelId, active) =>
ipcRenderer.invoke("browser:set-overlay", panelId, !!active),
// Hides the view without destroying the page — for a panel whose tab is not
// currently visible. `close` is the destructive one.
setInactive: (panelId, value) =>
ipcRenderer.invoke("browser:set-inactive", panelId, !!value),
close: (panelId) => ipcRenderer.invoke("browser:close", panelId),
getState: (panelId) => ipcRenderer.invoke("browser:get-state", panelId),
// Agent control. `setAgentAct` mirrors the dashboard's general "let the agent
// act" authorization into the main process, which evaluates the control gate
// itself on every owner transition. `control` takes a CLOSED verb set, never a
// raw CDP method — the surface cannot be widened from here.
setAgentAct: (panelId, enabled) =>
ipcRenderer.invoke("browser:set-agent-act", panelId, !!enabled),
setControlOwner: (panelId, owner) =>
ipcRenderer.invoke("browser:set-control-owner", panelId, owner),
getControl: (panelId) => ipcRenderer.invoke("browser:get-control", panelId),
control: (panelId, op, args) => ipcRenderer.invoke("browser:control", panelId, op, args),
// Human-initiated element annotation on the page in the native view:
// start/stop pick mode, poll the notes the user typed in the in-page
// overlay, remove/edit/clear, capture a screenshot with the markers. Read
// through executeJavaScript + capturePage, not the agent control plane.
annotate: (panelId, op, args) => ipcRenderer.invoke("browser:annotate", panelId, op, args),
// Declares that a chat session may host a browser panel, so the agent command
// channel polls for it even before the Browser tab is ever opened. Grants no
// authorization — authorization to drive the built-in browser is Browser Mode
// (the Settings toggle), and the gate is just the view precondition. This is
// the ONLY session-declaration channel: reachability is simply the active slots
// the renderer declares here.
trackSession: (panelId, tracked) =>
ipcRenderer.invoke("browser:track-session", panelId, !!tracked),
// Events carry their own panelId so a listener can ignore other panels'.
// `onAgentOpened` fires when the AGENT bootstrapped a native view for a
// session whose Browser panel may not be mounted yet — the dashboard must
// surface that panel so it can report bounds, or the page would render to
// nowhere.
onAgentOpened: (cb) => {
const handler = (_e, payload) => cb(payload);
ipcRenderer.on("browser:agent-opened", handler);
return () => ipcRenderer.removeListener("browser:agent-opened", handler);
},
onDidNavigate: (cb) => {
const handler = (_e, payload) => cb(payload);
ipcRenderer.on("browser:did-navigate", handler);
return () => ipcRenderer.removeListener("browser:did-navigate", handler);
},
onTitleUpdated: (cb) => {
const handler = (_e, payload) => cb(payload);
ipcRenderer.on("browser:title-updated", handler);
return () => ipcRenderer.removeListener("browser:title-updated", handler);
},
});
// Desktop auto-update bridge. Drives the in-app UpdateModal + Settings > About.
// onState pushes update lifecycle events ({state, version, notes, channel});
// check/install/getInfo are promise-based round-trips to the main process.
contextBridge.exposeInMainWorld("updateAPI", {
onState: (cb) => {
const handler = (_e, payload) => cb(payload);
ipcRenderer.on("update-state", handler);
return () => ipcRenderer.removeListener("update-state", handler);
},
check: () => ipcRenderer.invoke("update:check"),
download: () => ipcRenderer.invoke("update:download"),
install: () => ipcRenderer.invoke("update:install"),
getInfo: () => ipcRenderer.invoke("update:get-info"),
// Channel switcher (Settings > About): "" follows the build stamp,
// "insider"|"stable" opts the production app onto that lane.
setChannel: (channel) => ipcRenderer.invoke("update:set-channel", channel),
// Auto-download opt-out (Settings > About). ON by default: a discovered
// update downloads in the background and installs on the next quit.
setAutoDownload: (enabled) => ipcRenderer.invoke("update:set-auto-download", enabled),
// Notify the main process that a security policy provider now governs (or no
// longer governs) this install's updates. Called from useUpdateSubscription
// whenever update_bundled_by_app and update_managed_by align. Fire-and-forget.
notifyPolicyGoverned: (governed) => ipcRenderer.send("update:notify-policy-governed", governed),
});