Repository navigation
Expand file tree
/
Copy pathwindow-lifecycle.js
More file actions
1829 lines (1726 loc) · 76.2 KB
/
Copy pathwindow-lifecycle.js
File metadata and controls
1829 lines (1726 loc) · 76.2 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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const fs = require("fs");
const path = require("path");
const { createTokenRetryHandler, dashboardRetryPath } = require("./token-retry");
const { createRendererRecovery, withSafeReload, hasSafeReload } = require("./renderer-recovery");
const { createRendererExhaustedNotice } = require("./renderer-exhausted-notice");
const { createHangRecovery } = require("./hang-recovery");
const { armSplashHistoryClear, fileShellPageBasename } = require("./splash-history");
const { armSwipeHistory, browserPanelUnderCursor } = require("./swipe-history");
const { armScrollTouch } = require("./scroll-touch");
const { hideToTray, cancelPendingTrayHide, shouldKeepAppHidden } = require("./hide-to-tray");
const {
createCloseHandler,
getCloseAction,
setCloseAction,
} = require("./close-action");
const { attachHtmlFullScreen } = require("./html-fullscreen");
const { menuBarCanOverlap } = require("./fullscreen-top-reserve");
const {
watchFullScreenTransitions,
repairStalledFullScreenExit,
} = require("./fullscreen-transition-watch");
const { createNavigationGuard, createRedirectGuard, createWindowOpenHandler } = require("./external-scheme");
const { sanitizeWindowState, captureWindowState } = require("./window-state");
const { stepZoomFactor } = require("./zoom");
const { registerCaptureSurface } = require("./capture-trust");
const { isLoopbackUrl } = require("./browser-control");
const { runAnnotateOp } = require("./browser-annotate");
const { attachContextMenu } = require("./context-menu");
const {
TUNNEL_OPTION_LABEL,
parseRemoteCrewFields,
saveRemoteCrewConfig,
tunnelOptionHint,
} = require("./remote-crew-setup");
const {
getRemoteHostConfig,
getRemoteHostConfigForUrl,
getRemoteHostDefaultNameForUrl,
isSelectablePort,
retireLegacyEmptyPortHost,
setRemoteHostConfig,
} = require("./host-config");
const { defaultedPort, portIsSchemeDefault } = require("./gateway-auth-hint");
const { openPathHardened } = require("./open-path");
const { DEFAULT_REMOTE_BIN, DEFAULT_REMOTE_PATH } = require("./remote-token");
const { identityFamily } = require("./instance-guard");
const { decideLinuxFrame, applyWindowControl } = require("./linux-frame");
const { buildMenuTemplate } = require("./app-menu");
const { serializeMenuItems, executeMenuItem } = require("./windows-menu-model");
const {
SYMBOL_DARK: WINDOWS_TITLEBAR_SYMBOL_DARK,
SYMBOL_LIGHT: WINDOWS_TITLEBAR_SYMBOL_LIGHT,
OVERLAY_BACKGROUND: WINDOWS_TITLEBAR_BACKGROUND,
} = require("./windows-titlebar");
const { attachFrameLoadLogging } = require("./frame-load-log");
const { attachPaneAssetJournal } = require("./pane-asset-journal");
const { createMemoryWatchLog } = require("./memory-watch-log");
const { createCageTrace } = require("./cage-trace");
const { profilingEnabled } = require("./perf-metrics");
const {
HEADER_CSS_PX,
trafficLightPositionForZoom,
createWindowChrome,
} = require("./runtime/window/chrome");
const { createWindowPrompts } = require("./runtime/window/prompts");
const { createSessionSecurity } = require("./runtime/window/session-security");
const { injectLinuxCaptionControls } = require("./runtime/window/linux-captions");
const { wireWillDownloadOnce } = require("./download-handler");
const { attachBrowserPanels, dispatchBrowserOp } = require("./runtime/window/browser-panels");
const BROWSER_PARTITION = "persist:kirocrew-browser";
const FULLSCREEN_SETTLE_MS = [250, 1500];
const DASHBOARD_SETTLE_MS = 1500;
// A display rearrange (monitor hot-plug, or dragging the window to a screen
// with a different backing scale factor) changes the window's content bounds,
// but macOS reports the new geometry slightly AFTER the display event fires. An
// immediate recompute plus bounded deferred passes settle the WebContentsView
// onto the new scale — the same rationale as FULLSCREEN_SETTLE_MS. Without it
// the child view keeps its old-scale bounds until the next resize/move/paint,
// which surfaces as the dashboard briefly ghosting across both displays.
const DISPLAY_SETTLE_MS = [0, 250, 1500];
const WINDOW_SAVE_DEBOUNCE_MS = 400;
const WINDOWS_TITLEBAR_MENU_IDS = new Set([
"file-menu",
"edit-menu",
"view-menu",
"connection-menu",
"window-menu",
"help-menu",
]);
/**
* Own every dashboard window and the security policy of the sessions they use.
*
* Electron is injected so node:test can load this module without a live
* Electron runtime. Runtime collaborators stay deliberately narrow: gateway
* boot/recovery remains outside and crosses this boundary through the single
* connectWindow callback.
*/
function createWindowLifecycle(options) {
const {
electron,
store,
backendUrl,
port,
glog = () => {},
// The launch log's path, named in the dead-renderer error dialog so the
// user can attach it to a report.
logPath = () => "",
// Whether a dashboard document has finished loading in this run (the
// gpu-crash-fallback latch). Tells the dead-renderer dialog a renderer that
// never started from one that crashed later.
dashboardLoaded = () => false,
readInternalSecret = () => "",
mintLocalToken,
fetchRemoteToken,
isQuitting = () => false,
requestQuit,
connectWindow,
// Re-apply the launch port's managed-tunnel choice after a save here, so
// ticking or un-ticking it takes effect without a relaunch.
syncTunnel = () => {},
platform = process.platform,
env = process.env,
// Shared single-use registry of downloads the renderer explicitly asked
// for; passed to the will-download handler so only announced downloads
// auto-save (see download-expectations.js).
downloadExpectations = null,
} = options || {};
if (!electron) throw new Error("createWindowLifecycle: electron is required");
if (!store) throw new Error("createWindowLifecycle: store is required");
if (!backendUrl) throw new Error("createWindowLifecycle: backendUrl is required");
if (!Number.isInteger(port)) throw new Error("createWindowLifecycle: port is required");
if (typeof mintLocalToken !== "function") {
throw new Error("createWindowLifecycle: mintLocalToken is required");
}
// Shared by every window, and kept in memory only, so a "Don't ask again"
// ends when the app quits.
const rememberedEditorTargets = new Set();
if (typeof fetchRemoteToken !== "function") {
throw new Error("createWindowLifecycle: fetchRemoteToken is required");
}
if (typeof requestQuit !== "function") {
throw new Error("createWindowLifecycle: requestQuit is required");
}
if (typeof connectWindow !== "function") {
throw new Error("createWindowLifecycle: connectWindow is required");
}
const {
app,
BaseWindow,
BrowserWindow,
WebContentsView,
shell,
dialog,
Tray,
Menu,
nativeImage,
nativeTheme,
webContents,
session,
desktopCapturer,
systemPreferences,
screen,
contentTracing,
} = electron;
const IS_MAC = platform === "darwin";
const IS_WINDOWS = platform === "win32";
const IS_WIN = IS_WINDOWS;
const IS_LINUX = platform === "linux";
// Decide once: every window in the process must agree about native versus
// client-side decorations.
const LINUX_FRAME_DECISION = IS_LINUX
? decideLinuxFrame({ env, override: store.get("linuxFrameless") })
: null;
const LINUX_FRAMELESS = !!(LINUX_FRAME_DECISION && LINUX_FRAME_DECISION.frameless);
let mainWindow = null;
let tray = null;
let appMenu = null;
// The fullscreen-transition watch for the current main window. Its `pending()`
// is what keeps a close-to-tray exit from abandoning a transition AppKit is
// still animating, which is the cause of the orphan overlay rather than a
// symptom of it.
let fullScreenWatch = null;
// The primary window owns both the cheap memory trajectory and the bounded
// process-wide cage trace. Keeping record, crash flush, and quit stop behind
// one façade prevents sibling-window samples from being attributed to this
// renderer and prevents another owner from stopping contentTracing.
const memoryWatchLog = createMemoryWatchLog();
const cageTrace = createCageTrace({
contentTracing,
// Fixed ordinal slots bound disk use across launches; gateway-launch.log
// carries the timestamp that correlates a slot with a renderer death.
tracePath: (slot) => path.join(app.getPath("logs"), `cage-trace-${slot}.json`),
log: glog,
});
// The cohesive owners this facade composes, in the order the process first
// needs them. Each receives only what it reads; window state stays here.
const {
syncNativeTheme,
positionTrafficLights,
reconcileZoomChrome,
trackZoomChrome,
setThemeAccent,
handleFocusMode,
handleWatchFocusCursor,
setThemeMode,
setTitlebarMode,
getZoom,
setZoom,
stepZoom,
} = createWindowChrome({
BaseWindow,
nativeTheme,
screen,
store,
log: glog,
isMac: IS_MAC,
isWindows: IS_WINDOWS,
windowForWebContents,
});
const { getModalCSS, promptConnectionPort, renameFocusedWindow } = createWindowPrompts({
BaseWindow,
BrowserWindow,
nativeTheme,
store,
getMainWindow: () => mainWindow,
});
const { configureSessionSecurity, handleMicDenied } = createSessionSecurity({
session,
webContents,
desktopCapturer,
systemPreferences,
dialog,
shell,
isMac: IS_MAC,
partition: BROWSER_PARTITION,
});
// BaseWindow.fromWebContents does not exist. Match the dashboard view
// explicitly so every window-scoped IPC action targets its sender's window.
function windowForWebContents(wc) {
for (const win of BaseWindow.getAllWindows()) {
try {
if (win._mcView && win._mcView.webContents === wc) return win;
} catch {
// Window is mid-teardown.
}
}
return null;
}
// Is this window's gateway genuinely on THIS machine? A loopback URL is
// necessary but NOT sufficient: a remote gateway reached over a tunnel also
// presents as localhost, so additionally require that no remote host is
// configured for the window's OWN port (each window carries its backendUrl;
// the factory's port is only the primary window's, so a secondary remote
// window must not read the primary's config). Shared by the host-presence
// heartbeat and the wsl:detect sender gate so the two security decisions
// cannot drift apart.
//
// The key comes from `defaultedPort`, not `URL.port`, because the URL API
// leaves a scheme's default port empty: on `http://localhost:80` the raw
// property is `""`, the lookup asks for `remoteHosts[""]`, misses, and a
// tunnelled crew reads as a gateway on this machine -- after which the
// heartbeat sends this machine's internal secret over that tunnel.
//
// The lookup goes through `getRemoteHostConfigForUrl` rather than the port
// alone so a crew an older version recorded UNDER that empty key still reads
// as remote. Resolving the key without honouring those records would turn a
// store that was safe by accident into the exposure above.
//
// The store is the single source of truth for the remote verdict. On a
// scheme-default port (:80/:443) the 'Set Remote Host…' Clear is REFUSED, so
// the record cannot be dropped from under a live `ssh -L` tunnel and a later
// default-port window still resolves REMOTE from the store. On a selectable
// port a Clear that removes the record is the user's own reconfiguration, and
// every window reads that same store, so no per-window latch is needed.
function isGatewayLocalForWindow(win) {
if (!win || win.isDestroyed() || !win._mcBackendUrl) return false;
const url = win._mcBackendUrl;
if (!isLoopbackUrl(url)) return false; // non-loopback: reached off-box, never local
// The store is the source of truth. A crew record under this URL's resolved
// key (including the legacy empty key) marks the window remote; its absence
// marks it local. On a scheme-default port the Clear is REFUSED, so the
// record cannot be dropped from under a live tunnel; on a selectable port a
// Clear that removes the record is the user's own reconfiguration, and a
// fresh window reads that same store, so no window-scoped latch is needed.
return !getRemoteHostConfigForUrl(store, url)?.host;
}
function setupWindowContents(win, windowBackendUrl) {
const windowPort = defaultedPort(windowBackendUrl);
let customName = null;
const view = new WebContentsView({
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
// Frameless Linux is a launch-time decision, not a platform constant.
// The preload reads this argument to reserve caption-control space.
additionalArguments: LINUX_FRAMELESS ? ["--kc-linux-frameless"] : [],
},
});
view.setBackgroundColor("#00000000");
win.contentView.addChildView(view);
// Arm before any handoff. Boot, reconnect and token-prompt pages share this
// WebContents; leaving one in history lets mouse Back reach a dead-end shell.
armSplashHistoryClear(view.webContents, {
isAlive: () => !win.isDestroyed() && !view.webContents.isDestroyed(),
log: glog,
});
// Mouse software such as Logitech's Options sends Back/Forward to macOS apps
// as swipes; the dashboard, or the browser panel under the cursor, takes each
// as a history step.
armSwipeHistory(win, view.webContents, {
isAlive: () => !win.isDestroyed() && !view.webContents.isDestroyed(),
panelUnderCursor: () => browserPanelUnderCursor(win, screen.getCursorScreenPoint()),
});
// The trackpad's real finger-down / finger-up, so a two-finger drag in the
// dashboard releases on the lift-off instead of a guessed gap (macOS only).
armScrollTouch(view.webContents, {
platform,
isAlive: () => !win.isDestroyed() && !view.webContents.isDestroyed(),
});
// Teardown order is load-bearing: no command poller or CDP owner may outlive
// the page it targets. Close the dashboard WebContents only after releasing
// every embedded panel.
win.on("closed", () => {
if (win._mcAgentChannel) void win._mcAgentChannel.stop();
if (win._mcBrowserPanels) {
for (const id of [...win._mcBrowserPanels.keys()]) win._mcDestroyBrowserPanel(id);
}
view.webContents.close();
});
function updateViewBounds() {
if (win.isDestroyed()) return;
const { width, height } = win.getContentBounds();
view.setBounds({ x: 0, y: 0, width, height });
// Embedded browser panels are partial rectangles in the same content
// area, so a host-window resize invalidates their clamp too.
if (win._mcBrowserPanels) {
for (const entry of win._mcBrowserPanels.values()) entry.manager.refreshBounds();
}
}
updateViewBounds();
win.on("resize", updateViewBounds);
// `menuBarOverlap` tells the renderer whether to keep its menu-bar band
// clear: false when macOS already placed the fullscreen window below the
// menu bar (a notched built-in display).
const sendFullScreen = () => {
if (win.isDestroyed() || view.webContents.isDestroyed()) return;
view.webContents.send("fullscreen-changed", win.isFullScreen(), {
menuBarOverlap: menuBarCanOverlap(win, screen),
});
};
// Fullscreen events can precede the window manager's final reflow. Keep the
// immediate recompute (no flash where reflow is synchronous) and bounded
// deferred passes, including the late backstop slow Linux WMs need. Each
// pass re-sends the fullscreen state too, because the menu-bar verdict reads
// the window's position, which is only final once the reflow lands.
let fullscreenSettleTimers = [];
const scheduleFullscreenSettle = () => {
for (const timer of fullscreenSettleTimers) clearTimeout(timer);
fullscreenSettleTimers = [
...FULLSCREEN_SETTLE_MS.map((ms) => setTimeout(updateViewBounds, ms)),
...FULLSCREEN_SETTLE_MS.map((ms) => setTimeout(sendFullScreen, ms)),
];
};
win.on("closed", () => {
for (const timer of fullscreenSettleTimers) clearTimeout(timer);
fullscreenSettleTimers = [];
});
win.on("enter-full-screen", () => {
updateViewBounds();
sendFullScreen();
scheduleFullscreenSettle();
});
win.on("leave-full-screen", () => {
updateViewBounds();
sendFullScreen();
scheduleFullscreenSettle();
});
// DOM fullscreen is separate from native window fullscreen. Bridge it so a
// video can grow the BaseWindow, and retain provenance so persistence never
// mistakes a video-raised transition for the user's launch preference.
win._mcHtmlFullScreen = attachHtmlFullScreen({
win,
webContents: view.webContents,
});
win.on("show", updateViewBounds);
win.on("restore", updateViewBounds);
win.on("move", updateViewBounds);
// A display rearrange does not reliably fire a "resize"/"move" on the
// window, yet it changes the backing scale factor and content bounds. Bind
// the screen-level display events and re-run the reflow on a settle
// schedule so the child view tracks the new geometry instead of ghosting on
// the old display. Paired with an unbind in "closed" below — the bind/unbind
// discipline the pet-overlay leak (#4673) established: a screen listener
// that outlives its window keeps firing against a destroyed view.
let displaySettleTimers = [];
const onDisplayReflow = () => {
if (win.isDestroyed()) return;
for (const timer of displaySettleTimers) clearTimeout(timer);
displaySettleTimers = DISPLAY_SETTLE_MS.map((ms) =>
ms === 0 ? (updateViewBounds(), null) : setTimeout(updateViewBounds, ms),
).filter(Boolean);
};
const DISPLAY_EVENTS = ["display-metrics-changed", "display-added", "display-removed"];
if (screen && typeof screen.on === "function") {
for (const event of DISPLAY_EVENTS) screen.on(event, onDisplayReflow);
}
win.on("closed", () => {
for (const timer of displaySettleTimers) clearTimeout(timer);
displaySettleTimers = [];
if (screen && typeof screen.removeListener === "function") {
for (const event of DISPLAY_EVENTS) screen.removeListener(event, onDisplayReflow);
}
});
view.webContents.on("did-finish-load", () => {
updateViewBounds();
sendFullScreen();
setTimeout(updateViewBounds, DASHBOARD_SETTLE_MS);
});
// BaseWindow has no webContents. Preserve the shell's compatibility alias
// before any caller can load the splash or dashboard into this window.
win.webContents = view.webContents;
function applyTitle() {
// Resolve the name through the URL so a title an older version pinned under
// the empty key on a scheme-default port still renders until the record is
// retired onto the resolved key. Reading `getRemoteHostConfig(store,
// windowPort)` alone would miss it and the suffix would revert to `[:80]`.
const remoteName = getRemoteHostDefaultNameForUrl(store, windowBackendUrl);
if (!IS_WIN) {
const suffix = customName || remoteName || `[:${windowPort}]`;
win.setTitle(`Kiro Crew ${suffix}`);
return;
}
// Windows omits the default local port; secondary/remote windows retain a
// suffix so they remain distinguishable in the taskbar.
let suffix = customName || remoteName || "";
if (!suffix && windowPort && String(windowPort) !== "5476") {
suffix = `[:${windowPort}]`;
}
win.setTitle(suffix ? `Kiro Crew ${suffix}` : "Kiro Crew");
}
win._mcSetCustomName = (name) => {
customName = name;
applyTitle();
};
win._mcGetCustomName = () => customName;
win._mcBackendUrl = windowBackendUrl;
// The dashboard SPA is a capture surface (the chat composer's snip and the
// web-preview crop). Registered against the gateway origin THIS window was
// opened on, so a secondary window pointed at a remote gateway is bound to
// its own origin and never to a sibling's.
registerCaptureSurface(view.webContents, windowBackendUrl);
win._mcView = view;
// One native browser view/control plane per dashboard panel, plus the agent
// command channel that drives them (runtime/window/browser-panels.js).
const browserPanels = attachBrowserPanels(win, view, {
WebContentsView,
shell,
partition: BROWSER_PARTITION,
readInternalSecret,
isGatewayLocalForWindow,
});
// The dashboard's own webContents, so the link block also gets the origin --
// which is what turns a `/abs/path` link into a bare-path copy instead of a
// useless localhost URL. The embedded browser panel passes no origin: an
// arbitrary site's same-origin pathname is not a local file.
attachContextMenu(view.webContents, { getAppOrigin: () => windowBackendUrl });
trackZoomChrome(win, view);
// Frameless macOS exposes a native system context menu on the drag region.
win.on("system-context-menu", (event, point) => {
event.preventDefault();
Menu.buildFromTemplate([
{ label: "Rename Window…", click: () => renameCurrentWindow() },
{ label: "Set Remote Host…", click: () => promptRemoteHost() },
{ label: "Refresh Token", click: () => refreshToken() },
{ type: "separator" },
{ label: "New Connection Window…", click: () => openNewConnectionWindow() },
]).popup({ window: win, x: point.x, y: point.y });
});
view.webContents.on("did-finish-load", applyTitle);
view.webContents.on("page-title-updated", (event) => {
event.preventDefault();
applyTitle();
});
view.webContents.on("did-finish-load", () => {
// Every frameless platform needs a drag region. It collapses with the
// focus-mode header: app-region hit-testing happens before DOM pointer
// hit-testing, so pointer-events:none alone cannot stop an invisible drag
// strip from swallowing the transcript's mouse input.
if (IS_MAC || IS_WIN || LINUX_FRAMELESS) {
view.webContents.insertCSS(`
#electron-drag-bar {
position: fixed;
top: 0; left: 0; right: ${IS_WIN ? "var(--mc-win-drag-reserve, 138px)" : LINUX_FRAMELESS ? "108px" : "0"};
height: 42px;
-webkit-app-region: drag;
z-index: 99999;
pointer-events: none;
}
a, button, input, select, textarea,
[role="button"], [tabindex], iframe {
-webkit-app-region: no-drag;
}
body.mc-focus-mode #electron-drag-bar {
height: 0;
}
body.mc-focus-mode.mc-focus-chrome #electron-drag-bar {
height: 42px;
}
`);
view.webContents.executeJavaScript(`
if (!document.getElementById('electron-drag-bar')) {
const bar = document.createElement('div');
bar.id = 'electron-drag-bar';
document.body.prepend(bar);
}
`);
}
// Frameless Linux has no OS caption controls, so the shell draws them.
if (LINUX_FRAMELESS) injectLinuxCaptionControls(win, view);
view.webContents.executeJavaScript(
`getComputedStyle(document.documentElement).getPropertyValue('--bg').trim()`,
).then((bg) => {
if (bg && !win.isDestroyed()) win.setBackgroundColor(bg);
}).catch(() => {});
syncNativeTheme(view, win);
});
// Native themeSource is process-global, so a focused connection window must
// refresh it from its own dashboard before native chrome is painted.
win.on("focus", () => syncNativeTheme(view, win));
// On re-activation the platform re-resolves which child view receives
// keystrokes and may pick a hidden browser view again; each panel heals
// that by handing focus back to the dashboard view (see browser-view.js
// header note 3). A visible or unfocused panel is left alone.
win.on("focus", () => {
for (const entry of browserPanels.values()) entry.manager.reclaimFocus();
});
// Same-origin windows remain in-app. Cross-origin web URLs and the audited
// custom-scheme allowlist go to the OS; every other target fails closed.
const windowOpenHandler = createWindowOpenHandler({
openExternal: (url) => shell.openExternal(url),
getAppOrigin: () => windowBackendUrl,
confirmOpen: async (url) => {
const { response, checkboxChecked } = await dialog.showMessageBox(win, {
type: "question",
buttons: ["Open", "Cancel"],
defaultId: 0,
cancelId: 1,
message: "Open this link in your editor?",
detail: url,
checkboxLabel: "Don't ask again for this machine until Kiro Crew quits",
});
return { open: response === 0, remember: checkboxChecked === true };
},
rememberedEditorTargets,
log: glog,
});
// An allowed same-origin window.open (the session pop-out) is a child window
// Electron creates on its own. Give it, and each of its own children, the
// same handler, or its external links open yet another in-app window.
// A pane iframe can top-navigate the dashboard (or a pop-out) to its own
// document, which would then hold the dashboard's session grants. Refuse
// every renderer-started navigation off this window's own origin.
const navigationGuard = createNavigationGuard({
getAppOrigin: () => windowBackendUrl,
log: glog,
});
const redirectGuard = createRedirectGuard({
getAppOrigin: () => windowBackendUrl,
log: glog,
});
const armWindowOpen = (contents) => {
contents.setWindowOpenHandler(windowOpenHandler);
contents.on("will-navigate", navigationGuard);
contents.on("will-redirect", redirectGuard);
contents.on("did-create-window", (child) => armWindowOpen(child.webContents));
};
armWindowOpen(view.webContents);
// Do not leak the dashboard URL/token as a Referer to resources it embeds.
// This listener remains attached at the same per-window setup point; moving
// it to a one-time global policy would be a behavior change.
view.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
delete details.requestHeaders.Referer;
callback({ requestHeaders: details.requestHeaders });
});
// Give renderer-triggered downloads (e.g. the Portability "Download Export
// (.zip)" button's <a download> blob) a real save path. The dashboard view
// is a WebContentsView under a BaseWindow, which Chromium cannot parent a
// native "Save As" dialog to, so without this the DownloadItem never
// resolves a path and nothing lands on disk (issue #13047). Attached once
// per session (every window shares the default session), so N windows do
// not stack N handlers.
//
// Because the single handler is shared by every window, it must resolve the
// dashboard origin for the window that OWNS each download rather than
// capturing one window's URL: a later window on a different gateway (the
// remote-host secondary windows main supports) would otherwise fail the
// origin checks and its export would never land. `resolveDashboardUrl` maps
// the download's own `webContents` back to its window's `_mcBackendUrl`;
// `dashboardUrl` is the fallback for the first window / an unmatched sender.
wireWillDownloadOnce(view.webContents.session, {
app,
log: glog,
dashboardUrl: windowBackendUrl,
resolveDashboardUrl: (wc) => windowForWebContents(wc)?._mcBackendUrl,
pending: downloadExpectations,
platform,
});
return view;
}
function applyDashboardChrome(opts, { includeIcon = false } = {}) {
if (IS_MAC) {
opts.titleBarStyle = "hidden";
opts.trafficLightPosition = trafficLightPositionForZoom(1);
}
if (IS_WINDOWS) {
opts.titleBarStyle = "hidden";
opts.autoHideMenuBar = true;
opts.titleBarOverlay = {
color: WINDOWS_TITLEBAR_BACKGROUND,
symbolColor: nativeTheme.shouldUseDarkColors
? WINDOWS_TITLEBAR_SYMBOL_DARK
: WINDOWS_TITLEBAR_SYMBOL_LIGHT,
height: HEADER_CSS_PX,
};
}
if (LINUX_FRAMELESS) {
opts.frame = false;
// Keep the application menu reachable with Alt without stacking a native
// menu bar above the dashboard's own header.
opts.autoHideMenuBar = true;
}
if (includeIcon && (IS_WIN || IS_LINUX)) {
const iconFile = identityFamily(app.getVersion()) === "nightly"
&& fs.existsSync(path.join(__dirname, "icon-nightly.png"))
? "icon-nightly.png"
: "icon.png";
opts.icon = path.join(__dirname, iconFile);
}
return opts;
}
function persistMainWindowState() {
const state = captureWindowState(mainWindow, {
// DOM fullscreen belongs to the playing element, not the user's launch
// preference. The bridge is the only owner that can identify it.
transientFullScreen:
mainWindow?._mcHtmlFullScreen?.raisedWindow() === true,
});
if (state) store.set("windowState", state);
}
function createWindow() {
const state = sanitizeWindowState(store.get("windowState"), {
displays: screen.getAllDisplays().map((display) => ({
workArea: display.workArea,
})),
defaults: { width: 1280, height: 860 },
minSize: { width: 550, height: 600 },
});
const opts = applyDashboardChrome({
width: state.width,
height: state.height,
minWidth: 550,
minHeight: 600,
backgroundColor: "#0f1117",
}, { includeIcon: true });
// Restore fullscreen/always-on-top as constructor options so the window
// never flashes in the wrong state. Normal bounds remain the restore frame.
if (state.fullScreen) opts.fullscreen = true;
if (state.alwaysOnTop) opts.alwaysOnTop = true;
if (typeof state.x === "number" && typeof state.y === "number") {
opts.x = state.x;
opts.y = state.y;
}
mainWindow = new BaseWindow(opts);
if (IS_WINDOWS && typeof mainWindow.setMenuBarVisibility === "function") {
mainWindow.setMenuBarVisibility(false);
}
setupWindowContents(mainWindow, backendUrl);
// Persist continuously (debounced), then synchronously on real quit so the
// final geometry cannot be lost behind a pending timer.
let saveTimer = null;
const persist = persistMainWindowState;
const persistDebounced = () => {
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(persist, WINDOW_SAVE_DEBOUNCE_MS);
};
mainWindow.on("resize", persistDebounced);
mainWindow.on("move", persistDebounced);
mainWindow.on("enter-full-screen", persist);
mainWindow.on("leave-full-screen", persist);
// Journal the terminal events so a stalled transition is legible in
// gateway-launch.log; until this existed a frozen fullscreen exit left no
// evidence anywhere. The watch below is the only detector the main process
// has for that stall (fullscreen-transition-watch.js explains why), and its
// repair is the only thing that clears the AppKit overlay short of a quit.
mainWindow.on("enter-full-screen", () => {
glog(`fullscreen: entered bounds=${JSON.stringify(mainWindow.getBounds())}`);
});
mainWindow.on("leave-full-screen", () => {
glog(`fullscreen: left bounds=${JSON.stringify(mainWindow.getBounds())}`);
});
fullScreenWatch = watchFullScreenTransitions(mainWindow, {
isMac: IS_MAC,
onStall: ({ target, fullScreen, visible, elapsedMs }) => {
glog(
`fullscreen: ${target ? "enter" : "exit"} transition did not complete` +
` after ${elapsedMs}ms (isFullScreen=${fullScreen} visible=${visible})`,
);
if (target) return; // an unfinished ENTER has no known overlay to clear
const outcome = repairStalledFullScreenExit({
app,
win: mainWindow,
isMac: IS_MAC,
keepHidden: () => shouldKeepAppHidden(mainWindow),
});
glog(
`fullscreen: stalled exit repair hidden=${outcome.hidden}` +
` unhideScheduled=${outcome.unhideScheduled}`,
);
},
onArm: ({ target }) => {
glog(`fullscreen: ${target ? "enter" : "exit"} transition started`);
},
// A transition abandoned mid-animation orphans its overlay just as a stall
// does, and its replacement fires normally so nothing else notices. The
// close path no longer causes this (hide-to-tray serialises its exit), but
// a user toggling fullscreen twice inside one animation still can, and
// AppKit gives no way to reach the overlay other than this repair.
onAbort: ({ target, fullScreen, visible, elapsedMs }) => {
const keepHiddenNow = shouldKeepAppHidden(mainWindow);
glog(
`fullscreen: ${target ? "enter" : "exit"} transition abandoned after ${elapsedMs}ms` +
` (isFullScreen=${fullScreen} visible=${visible} pendingTrayHide=${keepHiddenNow})`,
);
const outcome = repairStalledFullScreenExit({
app,
win: mainWindow,
isMac: IS_MAC,
keepHidden: () => shouldKeepAppHidden(mainWindow),
});
glog(
`fullscreen: abandoned transition repair hidden=${outcome.hidden}` +
` unhideScheduled=${outcome.unhideScheduled}`,
);
},
});
// A 403 means the gateway secret may have rotated. Re-enter through the
// same local-then-remote token order used at boot. A recovery reload keeps
// its `safe=1` through the retry: a bare URL here reopens the remembered
// chat, and the crash that chat caused repeats.
let retrySafe = false;
const onNavigate = createTokenRetryHandler(async () => {
let tokenValue = await mintLocalToken(backendUrl);
if (!tokenValue) {
({ token: tokenValue } = await fetchRemoteToken(port));
}
if (tokenValue && !mainWindow.isDestroyed()) {
const target = `${backendUrl}?token=${tokenValue}`;
mainWindow.webContents.loadURL(retrySafe ? withSafeReload(target) : target);
}
});
mainWindow.webContents.on("did-navigate", (_event, url, httpCode) => {
retrySafe = hasSafeReload(url);
onNavigate(httpCode).catch((error) => {
console.error("Token retry failed:", error);
});
});
// Journal frame-level load outcomes into gateway-launch.log. The remote-crew
// panes are iframes of THIS webContents, and until this existed a pane that
// never became a live document left no evidence anywhere: the remote gateway
// keeps no HTTP access log and a packaged app has no devtools console. The
// navigation lines are what separate "never requested" from "requested and
// refused" — the two failures that look identical on screen.
//
// `backendUrl` is passed as the trusted origin: it is the ONE document whose
// `[pane]` journal lines are the dashboard's own. Being the top frame is not
// enough on its own, because a pane can navigate the top-level window to a
// remote document and inherit that position.
attachFrameLoadLogging(mainWindow.webContents, glog, backendUrl);
// The pane's module graph is the one load stage no renderer-side line can
// report: a stalled hashed-chunk fetch leaves the entry module unevaluated,
// so nothing of ours runs in that frame to say so. The main process sees the
// request either way. See pane-asset-journal.js.
attachPaneAssetJournal(mainWindow.webContents.session, glog, backendUrl);
function reloadDashboard() {
if (mainWindow.isDestroyed()) return;
(async () => {
let tokenValue = await mintLocalToken(backendUrl);
if (!tokenValue) {
({ token: tokenValue } = await fetchRemoteToken(port));
}
if (mainWindow.isDestroyed()) return;
// `safe=1`: do not reopen the chat that may have caused the crash.
mainWindow.webContents.loadURL(withSafeReload(
tokenValue ? `${backendUrl}?token=${tokenValue}` : backendUrl,
));
})().catch((error) => {
glog(`renderer recovery reload failed: ${error && error.message}`);
});
}
const rendererExhaustedNotice = createRendererExhaustedNotice({
dialog,
openExternal: (url) => shell.openExternal(url),
requestQuit,
// "Try again" in the dialog: a fresh reload budget, then one more load.
// `rendererRecovery` is created just below; this runs only after the
// dialog it belongs to, long after both exist.
retry: () => {
rendererRecovery.reset();
reloadDashboard();
},
dashboardLoaded,
parentWindow: () => mainWindow,
isQuitting,
platform,
logPath,
log: glog,
});
const rendererRecovery = createRendererRecovery({
isQuitting,
log: glog,
describeProcesses: () => {
const metrics = app.getAppMetrics() || [];
let totalCpu = 0;
let totalMb = 0;
let worst = null;
for (const metric of metrics) {
const cpu = (metric.cpu && metric.cpu.percentCPUUsage) || 0;
const mb = ((metric.memory && metric.memory.workingSetSize) || 0) / 1024;
totalCpu += cpu;
totalMb += mb;
if (!worst || mb > worst.mb) {
worst = { type: metric.type, pid: metric.pid, mb, cpu };
}
}
const parts = [
`procs=${metrics.length}`,
`totalCpu=${totalCpu.toFixed(1)}%`,
`totalWorkingSet=${Math.round(totalMb)}MB`,
];
if (worst) {
parts.push(
`largest=${worst.type}:${worst.pid}@${Math.round(worst.mb)}MB/${worst.cpu.toFixed(1)}%`,
);
}
return parts.join(" ");
},
reload: reloadDashboard,
// The budget is spent: say so on screen. A dead renderer leaves the
// window black with no text, so this is the only readable error the
// user gets (renderer-exhausted-notice.js). Never awaited here: the
// dialog outlives this event handler.
onGiveUp: (info) => {
void rendererExhaustedNotice.show(info);
},
});
// A renderer that HANGS never reaches the `render-process-gone` handler
// below: it emits `unresponsive` instead, and with no listener the window
// stayed frozen until the user rebooted (#8264). Convert a sustained hang
// into the crash the bounded recovery already heals; `responsive` within
// the grace window cancels the kill so a transient stall keeps its state.
const hangRecovery = createHangRecovery({
isQuitting,
log: glog,
forceCrash: () => {
if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) return;
mainWindow.webContents.forcefullyCrashRenderer();
},
});
mainWindow.webContents.on("unresponsive", () => hangRecovery.handleUnresponsive());
mainWindow.webContents.on("responsive", () => hangRecovery.handleResponsive());
mainWindow.webContents.on("render-process-gone", (_event, details) => {
// Flush the trajectory before the terminal event so the log stays causal.
// An in-flight content trace is write-or-lose: stopRecording is the only
// operation that lands it, and a renderer death is its most useful end.
for (const line of memoryWatchLog.flush()) glog(line);
void cageTrace.stopForCrash();
// A hung renderer can die on its own inside the grace window; the armed
// force-crash must not survive into the reloaded replacement renderer.
hangRecovery.handleGone();
rendererRecovery.handleGone(details || {});
});
mainWindow.on("close", createCloseHandler({
isQuitting,
getAction: () => getCloseAction(store),
cancelPendingHide: () => {
glog("close: quitting (closeAction=quit)");
cancelPendingTrayHide(mainWindow);
},
requestQuit,
hide: () => {
// macOS must leave its native fullscreen Space before hiding or the Space
// becomes an orphaned black surface, and the hide that follows is an
// app-level one: AppKit may have left a full-display overlay on screen
// that only `app.hide()` can reach (see hide-to-tray.js).
glog(`close: hiding to tray (fullScreen=${mainWindow.isFullScreen()})`);
hideToTray(mainWindow, {
log: glog,
// isFullScreen() already reports the target while AppKit is still
// exiting. Carry the watch target so the helper attaches to that exit
// instead of issuing another toggle or treating the window as stable.
transitionTarget: fullScreenWatch ? fullScreenWatch.pending() : null,
// The exit must not be issued while AppKit is still animating; the watch
// is what knows how long the window has been still. Its terminal-exit
// clock also covers AppKit's final order-in after pending() clears.
quietFor: () => (fullScreenWatch ? fullScreenWatch.quietFor() : Infinity),
exitSettlingFor: () => (
fullScreenWatch ? fullScreenWatch.exitSettlingFor() : Infinity
),
});
},
persist: () => {
if (saveTimer) {
clearTimeout(saveTimer);
saveTimer = null;
}
persist();
},
}));
return mainWindow;
}
// A tray hide out of fullscreen hides the whole APP (hide-to-tray.js explains
// why: it is the only call that also orders out AppKit's abandoned overlay).
// A hidden app ignores `win.show()`, so every user-intent show has to unhide
// the app first. Harmless when the app was never hidden, and macOS-only
// because `app.hide()` is.
function unhideApp() {
if (!IS_MAC || typeof app.show !== "function") return;
try {
app.show();
} catch {
/* best effort — the window show below is what the user asked for */
}
}
function showMainWindow({ focus = false } = {}) {
if (!mainWindow || mainWindow.isDestroyed()) return false;
cancelPendingTrayHide(mainWindow);
unhideApp();
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();