-
Notifications
You must be signed in to change notification settings - Fork 598
Expand file tree
/
Copy pathmain.ts
More file actions
879 lines (787 loc) · 28 KB
/
main.ts
File metadata and controls
879 lines (787 loc) · 28 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
import {
BrowserWindow,
Notification,
shell,
nativeTheme,
ipcMain,
app,
clipboard,
session,
nativeImage,
dialog,
} from "electron"
import { join } from "path"
import { readFileSync, existsSync, writeFileSync, mkdirSync } from "fs"
import { createIPCHandler } from "trpc-electron/main"
import { createAppRouter } from "../lib/trpc/routers"
import { getAuthManager, handleAuthCode, getBaseUrl } from "../index"
import { registerGitWatcherIPC } from "../lib/git/watcher"
import { hasActiveClaudeSessions, abortAllClaudeSessions } from "../lib/trpc/routers/claude"
import { hasActiveCodexStreams, abortAllCodexStreams } from "../lib/trpc/routers/codex"
import { registerThemeScannerIPC } from "../lib/vscode-theme-scanner"
import { windowManager } from "./window-manager"
// Flag to bypass close confirmation when app.quit() has already been confirmed
let isQuitting = false
export function setIsQuitting(value: boolean): void {
isQuitting = value
}
// Helper to get window from IPC event
function getWindowFromEvent(
event: Electron.IpcMainInvokeEvent,
): BrowserWindow | null {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
return win && !win.isDestroyed() ? win : null
}
// Register IPC handlers for window operations (only once)
let ipcHandlersRegistered = false
function registerIpcHandlers(): void {
if (ipcHandlersRegistered) return
ipcHandlersRegistered = true
// App info
ipcMain.handle("app:version", () => app.getVersion())
ipcMain.handle("app:isPackaged", () => app.isPackaged)
// Windows: Frame preference persistence
ipcMain.handle("window:set-frame-preference", (_event, useNativeFrame: boolean) => {
try {
const settingsPath = join(app.getPath("userData"), "window-settings.json")
const settingsDir = app.getPath("userData")
mkdirSync(settingsDir, { recursive: true })
writeFileSync(settingsPath, JSON.stringify({ useNativeFrame }, null, 2))
return true
} catch (error) {
console.error("[Main] Failed to save frame preference:", error)
return false
}
})
// Windows: Get current window frame state
ipcMain.handle("window:get-frame-state", () => {
if (process.platform !== "win32") return false
try {
const settingsPath = join(app.getPath("userData"), "window-settings.json")
if (existsSync(settingsPath)) {
const settings = JSON.parse(readFileSync(settingsPath, "utf-8"))
return settings.useNativeFrame === true
}
return false // Default: frameless
} catch {
return false
}
})
// Note: Update checking is now handled by auto-updater module (lib/auto-updater.ts)
ipcMain.handle("app:set-badge", (event, count: number | null) => {
const win = getWindowFromEvent(event)
if (process.platform === "darwin") {
app.dock.setBadge(count ? String(count) : "")
} else if (process.platform === "win32" && win) {
// Windows: Update title with count as fallback
if (count !== null && count > 0) {
win.setTitle(`1Code (${count})`)
} else {
win.setTitle("1Code")
win.setOverlayIcon(null, "")
}
}
})
// Windows: Badge overlay icon
ipcMain.handle("app:set-badge-icon", (event, imageData: string | null) => {
const win = getWindowFromEvent(event)
if (process.platform === "win32" && win) {
if (imageData) {
const image = nativeImage.createFromDataURL(imageData)
win.setOverlayIcon(image, "New messages")
} else {
win.setOverlayIcon(null, "")
}
}
})
ipcMain.handle(
"app:show-notification",
(event, options: { title: string; body: string }) => {
try {
if (!Notification.isSupported()) {
console.warn("[Main] Notifications not supported on this system")
return
}
// On macOS, the app icon is used automatically — no custom icon needed.
// On Windows, use .ico; on Linux, use .png.
let icon: Electron.NativeImage | undefined
if (process.platform !== "darwin") {
const ext = process.platform === "win32" ? "icon.ico" : "icon.png"
const iconPath = join(__dirname, "../../build", ext)
icon = existsSync(iconPath) ? nativeImage.createFromPath(iconPath) : undefined
}
const notification = new Notification({
title: options.title,
body: options.body,
...(icon && { icon }),
...(process.platform === "win32" && { silent: false }),
})
notification.on("click", () => {
const win = getWindowFromEvent(event)
if (win) {
if (win.isMinimized()) win.restore()
win.focus()
}
})
notification.show()
} catch (error) {
console.error("[Main] Failed to show notification:", error)
}
},
)
// API base URL for fetch requests
ipcMain.handle("app:get-api-base-url", () => getBaseUrl())
// Window controls - use event.sender to identify window
ipcMain.handle("window:minimize", (event) => {
getWindowFromEvent(event)?.minimize()
})
ipcMain.handle("window:maximize", (event) => {
const win = getWindowFromEvent(event)
if (win?.isMaximized()) {
win.unmaximize()
} else {
win?.maximize()
}
})
ipcMain.handle("window:close", (event) => {
getWindowFromEvent(event)?.close()
})
ipcMain.handle("window:is-maximized", (event) => {
return getWindowFromEvent(event)?.isMaximized() ?? false
})
ipcMain.handle("window:toggle-fullscreen", (event) => {
const win = getWindowFromEvent(event)
if (win) {
win.setFullScreen(!win.isFullScreen())
}
})
ipcMain.handle("window:is-fullscreen", (event) => {
return getWindowFromEvent(event)?.isFullScreen() ?? false
})
// Traffic light visibility control (for hybrid native/custom approach)
ipcMain.handle(
"window:set-traffic-light-visibility",
(event, visible: boolean) => {
const win = getWindowFromEvent(event)
if (win && process.platform === "darwin") {
// In fullscreen, always show native traffic lights (don't let React hide them)
if (win.isFullScreen()) {
win.setWindowButtonVisibility(true)
} else {
win.setWindowButtonVisibility(visible)
}
}
},
)
// Zoom controls
ipcMain.handle("window:zoom-in", (event) => {
const win = getWindowFromEvent(event)
if (win) {
const zoom = win.webContents.getZoomFactor()
win.webContents.setZoomFactor(Math.min(zoom + 0.1, 3))
}
})
ipcMain.handle("window:zoom-out", (event) => {
const win = getWindowFromEvent(event)
if (win) {
const zoom = win.webContents.getZoomFactor()
win.webContents.setZoomFactor(Math.max(zoom - 0.1, 0.5))
}
})
ipcMain.handle("window:zoom-reset", (event) => {
getWindowFromEvent(event)?.webContents.setZoomFactor(1)
})
ipcMain.handle("window:get-zoom", (event) => {
return getWindowFromEvent(event)?.webContents.getZoomFactor() ?? 1
})
// New window - optionally open with specific chat/subchat
ipcMain.handle("window:new", (_event, options?: { chatId?: string; subChatId?: string }) => {
// If chatId specified, check ownership atomically via focusChatOwner
if (options?.chatId && windowManager.focusChatOwner(options.chatId)) {
return { blocked: true }
}
const win = createWindow(options)
// Pre-claim the chat for the new window
if (options?.chatId) {
windowManager.claimChat(options.chatId, win.id)
}
return { blocked: false }
})
// Chat ownership — prevent same chat open in multiple windows
ipcMain.handle("chat:claim", (event, chatId: string) => {
const win = getWindowFromEvent(event)
if (!win) return { ok: false, ownerStableId: "unknown" }
return windowManager.claimChat(chatId, win.id)
})
ipcMain.handle("chat:release", (event, chatId: string) => {
const win = getWindowFromEvent(event)
if (!win) return
windowManager.releaseChat(chatId, win.id)
})
ipcMain.handle("chat:focus-owner", (_event, chatId: string) => {
return windowManager.focusChatOwner(chatId)
})
// Set window title
ipcMain.handle("window:set-title", (event, title: string) => {
const win = getWindowFromEvent(event)
if (win) {
// Show just the title, or default app name if empty
win.setTitle(title || "1Code")
}
})
// DevTools - only allowed in dev mode or when unlocked
ipcMain.handle("window:toggle-devtools", (event) => {
const win = getWindowFromEvent(event)
// Check if devtools are unlocked (or in dev mode)
const isUnlocked = !app.isPackaged || (global as any).__devToolsUnlocked
if (win && isUnlocked) {
win.webContents.toggleDevTools()
}
})
// Unlock DevTools (hidden feature - 5 clicks on Beta tab)
ipcMain.handle("window:unlock-devtools", () => {
// Mark as unlocked locally for IPC check
;(global as any).__devToolsUnlocked = true
// Call the global function to rebuild menu
if ((global as any).__unlockDevTools) {
;(global as any).__unlockDevTools()
}
})
// Analytics
ipcMain.handle("analytics:set-opt-out", async (_event, optedOut: boolean) => {
const { setOptOut } = await import("../lib/analytics")
setOptOut(optedOut)
})
// Shell
ipcMain.handle("shell:open-external", (_event, url: string) =>
shell.openExternal(url),
)
// Clipboard
ipcMain.handle("clipboard:write", (_event, text: string) =>
clipboard.writeText(text),
)
ipcMain.handle("clipboard:read", () => clipboard.readText())
// Save file with native dialog
ipcMain.handle(
"dialog:save-file",
async (
event,
options: { base64Data: string; filename: string; filters?: { name: string; extensions: string[] }[] },
) => {
const win = getWindowFromEvent(event)
if (!win) return { success: false }
// Ensure window is focused before showing dialog (required on macOS)
if (!win.isFocused()) {
win.focus()
await new Promise((resolve) => setTimeout(resolve, 100))
}
const result = await dialog.showSaveDialog(win, {
defaultPath: options.filename,
filters: options.filters || [
{ name: "Images", extensions: ["png", "jpg", "jpeg", "webp", "gif"] },
{ name: "All Files", extensions: ["*"] },
],
})
if (result.canceled || !result.filePath) return { success: false }
try {
const buffer = Buffer.from(options.base64Data, "base64")
writeFileSync(result.filePath, buffer)
return { success: true, filePath: result.filePath }
} catch (err) {
console.error("[dialog:save-file] Failed to write file:", err)
return { success: false }
}
},
)
// Auth IPC handlers
const validateSender = (event: Electron.IpcMainInvokeEvent): boolean => {
const senderUrl = event.sender.getURL()
try {
const parsed = new URL(senderUrl)
if (parsed.protocol === "file:") return true
const hostname = parsed.hostname.toLowerCase()
const trusted = ["21st.dev", "localhost", "127.0.0.1"]
return trusted.some((h) => hostname === h || hostname.endsWith(`.${h}`))
} catch {
return false
}
}
ipcMain.handle("auth:get-user", (event) => {
if (!validateSender(event)) return null
return getAuthManager().getUser()
})
ipcMain.handle("auth:is-authenticated", (event) => {
if (!validateSender(event)) return false
return getAuthManager().isAuthenticated()
})
ipcMain.handle("auth:logout", async (event) => {
if (!validateSender(event)) return
getAuthManager().logout()
// Clear cookie from persist:main partition
const ses = session.fromPartition("persist:main")
try {
await ses.cookies.remove(getBaseUrl(), "x-desktop-token")
console.log("[Auth] Cookie cleared on logout")
} catch (err) {
console.error("[Auth] Failed to clear cookie:", err)
}
// Show login page in all windows
for (const win of windowManager.getAll()) {
showLoginPageInWindow(win)
}
})
ipcMain.handle("auth:start-flow", (event) => {
if (!validateSender(event)) return
const win = getWindowFromEvent(event)
getAuthManager().startAuthFlow(win)
})
ipcMain.handle("auth:submit-code", async (event, code: string) => {
if (!validateSender(event)) return
if (!code || typeof code !== "string") {
getWindowFromEvent(event)?.webContents.send(
"auth:error",
"Invalid authorization code",
)
return
}
await handleAuthCode(code)
})
ipcMain.handle("auth:update-user", async (event, updates: { name?: string }) => {
if (!validateSender(event)) return null
try {
return await getAuthManager().updateUser(updates)
} catch (error) {
console.error("[Auth] Failed to update user:", error)
throw error
}
})
ipcMain.handle("auth:get-token", async (event) => {
if (!validateSender(event)) return null
return getAuthManager().getValidToken()
})
// Signed fetch - proxies requests through main process (no CORS)
ipcMain.handle(
"api:signed-fetch",
async (
event,
url: string,
options?: { method?: string; body?: string; headers?: Record<string, string> },
) => {
console.log("[SignedFetch] IPC handler called with URL:", url)
if (!validateSender(event)) {
console.log("[SignedFetch] Unauthorized sender")
return { ok: false, status: 403, data: null, error: "Unauthorized sender" }
}
console.log("[SignedFetch] Sender validated OK")
const token = await getAuthManager().getValidToken()
console.log("[SignedFetch] Token:", token ? "present" : "missing", "URL:", url)
if (!token) {
return { ok: false, status: 401, data: null, error: "Not authenticated" }
}
try {
const response = await fetch(url, {
method: options?.method || "GET",
body: options?.body,
headers: {
...options?.headers,
"X-Desktop-Token": token,
"Content-Type": "application/json",
},
})
const data = await response.json().catch(() => null)
console.log("[SignedFetch] Response:", response.status, response.ok ? "OK" : "FAILED")
return {
ok: response.ok,
status: response.status,
data,
error: response.ok ? null : `Request failed: ${response.status}`,
}
} catch (error) {
console.log("[SignedFetch] Error:", error)
return {
ok: false,
status: 0,
data: null,
error: error instanceof Error ? error.message : "Network error",
}
}
},
)
// Streaming fetch - for SSE responses (chat streaming)
// Uses a unique stream ID to match chunks with the right request
ipcMain.handle(
"api:stream-fetch",
async (
event,
streamId: string,
url: string,
options?: { method?: string; body?: string; headers?: Record<string, string> },
) => {
console.log("[StreamFetch] Starting stream:", streamId, url)
if (!validateSender(event)) {
console.log("[StreamFetch] Unauthorized sender")
return { ok: false, status: 403, error: "Unauthorized sender" }
}
const token = await getAuthManager().getValidToken()
if (!token) {
return { ok: false, status: 401, error: "Not authenticated" }
}
try {
const response = await fetch(url, {
method: options?.method || "POST",
body: options?.body,
headers: {
...options?.headers,
"X-Desktop-Token": token,
"Content-Type": "application/json",
},
})
console.log("[StreamFetch] Response:", response.status, response.ok)
if (!response.ok) {
const errorText = await response.text().catch(() => "Unknown error")
return { ok: false, status: response.status, error: errorText }
}
// Stream the response body back to renderer
const reader = response.body?.getReader()
if (!reader) {
return { ok: false, status: 500, error: "No response body" }
}
// Send chunks asynchronously
;(async () => {
try {
while (true) {
const { done, value } = await reader.read()
if (done) {
event.sender.send(`stream:${streamId}:done`)
break
}
// Send chunk to renderer
event.sender.send(`stream:${streamId}:chunk`, value)
}
} catch (err) {
console.error("[StreamFetch] Stream error:", err)
event.sender.send(`stream:${streamId}:error`, err instanceof Error ? err.message : "Stream error")
}
})()
return { ok: true, status: response.status }
} catch (error) {
console.error("[StreamFetch] Fetch error:", error)
return {
ok: false,
status: 0,
error: error instanceof Error ? error.message : "Network error",
}
}
},
)
// Register git watcher IPC handlers
registerGitWatcherIPC()
// Register VS Code theme scanner IPC handlers
registerThemeScannerIPC()
}
/**
* Show login page in a specific window
*/
function showLoginPageInWindow(window: BrowserWindow): void {
console.log("[Main] Showing login page in window", window.id)
// In dev mode, login.html is in src/renderer, not out/renderer
if (process.env.ELECTRON_RENDERER_URL) {
// Dev mode: load from source directory
const loginPath = join(app.getAppPath(), "src/renderer/login.html")
console.log("[Main] Loading login from:", loginPath)
window.loadFile(loginPath)
} else {
// Production: load from built output
window.loadFile(join(__dirname, "../renderer/login.html"))
}
}
/**
* Show login page in the focused window (or first window)
*/
export function showLoginPage(): void {
const win = windowManager.getFocused() || windowManager.getAll()[0]
if (!win) return
showLoginPageInWindow(win)
}
// Singleton IPC handler (prevents duplicate handlers on macOS window recreation)
let ipcHandler: ReturnType<typeof createIPCHandler> | null = null
/**
* Get the focused window reference
* Used by tRPC procedures that need window access
*/
export function getWindow(): BrowserWindow | null {
return windowManager.getFocused()
}
/**
* Get all windows
*/
export function getAllWindows(): BrowserWindow[] {
return windowManager.getAll()
}
/**
* Read window frame preference from settings file (Windows only)
* Returns true if native frame should be used, false for frameless
*/
function getUseNativeFramePreference(): boolean {
if (process.platform !== "win32") return false
try {
const settingsPath = join(app.getPath("userData"), "window-settings.json")
if (existsSync(settingsPath)) {
const settings = JSON.parse(readFileSync(settingsPath, "utf-8"))
return settings.useNativeFrame === true
}
return false // Default: frameless (dark title bar)
} catch {
return false
}
}
/**
* Create a new application window
* @param options Optional settings for the new window
* @param options.chatId Open this chat in the new window
* @param options.subChatId Open this sub-chat in the new window
*/
export function createWindow(options?: { chatId?: string; subChatId?: string }): BrowserWindow {
// Register IPC handlers before creating first window
registerIpcHandlers()
// Read Windows frame preference
const useNativeFrame = getUseNativeFramePreference()
const window = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 500, // Allow narrow mobile-like mode
minHeight: 600,
show: false,
title: "1Code",
backgroundColor: nativeTheme.shouldUseDarkColors ? "#09090b" : "#ffffff",
// hiddenInset shows native traffic lights inset in the window
// hiddenInset hides the native title bar but keeps traffic lights visible
titleBarStyle: process.platform === "darwin" ? "hiddenInset" : "default",
trafficLightPosition:
process.platform === "darwin" ? { x: 15, y: 12 } : undefined,
// Windows: Use native frame or frameless based on user preference
...(process.platform === "win32" && {
frame: useNativeFrame,
autoHideMenuBar: true,
}),
webPreferences: {
preload: join(__dirname, "../preload/index.js"),
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // Required for electron-trpc
webSecurity: true,
partition: "persist:main", // Use persistent session for cookies
},
})
let attemptedRendererRecovery = false
// Register window with manager and get stable ID for localStorage namespacing
const stableWindowId = windowManager.register(window)
console.log(
`[Main] Created window ${window.id} with stable ID "${stableWindowId}" (total: ${windowManager.count()})`,
)
// Setup tRPC IPC handler (singleton pattern)
if (ipcHandler) {
// Reuse existing handler, just attach new window
ipcHandler.attachWindow(window)
} else {
// Create new handler with context
ipcHandler = createIPCHandler({
router: createAppRouter(getWindow),
windows: [window],
createContext: async () => ({
getWindow,
}),
})
}
// Show window when ready
window.on("ready-to-show", () => {
console.log("[Main] Window", window.id, "ready to show")
// Start with traffic lights hidden - the renderer will show them
// after hydration based on the persisted sidebar state
if (process.platform === "darwin") {
window.setWindowButtonVisibility(false)
}
window.show()
})
// Emit fullscreen change events and manage traffic lights
window.on("enter-full-screen", () => {
// Always show native traffic lights in fullscreen
if (process.platform === "darwin") {
window.setWindowButtonVisibility(true)
}
window.webContents.send("window:fullscreen-change", true)
})
window.on("leave-full-screen", () => {
// Don't force traffic lights visible here - the renderer will
// restore the correct visibility based on sidebar state when
// it receives the fullscreen-change event
window.webContents.send("window:fullscreen-change", false)
})
// Emit focus change events
window.on("focus", () => {
window.webContents.send("window:focus-change", true)
})
window.on("blur", () => {
window.webContents.send("window:focus-change", false)
})
// Disable Cmd+R / Ctrl+R to prevent accidental page refresh
// Cmd+Shift+R / Ctrl+Shift+R is allowed but warns if there are active streams
window.webContents.on("before-input-event", (event, input) => {
const isMac = process.platform === "darwin"
const modifierKey = isMac ? input.meta : input.control
if (modifierKey && input.key.toLowerCase() === "r") {
if (!input.shift) {
// Block Cmd+R entirely
event.preventDefault()
} else if (hasActiveClaudeSessions() || hasActiveCodexStreams()) {
// Cmd+Shift+R with active streams — intercept and confirm
event.preventDefault()
dialog
.showMessageBox(window, {
type: "warning",
buttons: ["Cancel", "Reload Anyway"],
defaultId: 0,
cancelId: 0,
title: "Active Sessions",
message: "There are active agent sessions running.",
detail:
"Reloading will interrupt them. The current progress will be saved. Are you sure you want to reload?",
})
.then(({ response }) => {
if (response === 1) {
abortAllClaudeSessions()
abortAllCodexStreams()
window.webContents.reloadIgnoringCache()
}
})
}
}
})
// Handle external links
window.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url)
return { action: "deny" }
})
window.webContents.on("render-process-gone", (_event, details) => {
console.error("[Main] Renderer process gone in window", window.id, details)
if (attemptedRendererRecovery || window.isDestroyed()) {
return
}
attemptedRendererRecovery = true
setTimeout(() => {
if (!window.isDestroyed()) {
console.log("[Main] Attempting one-shot renderer recovery in window", window.id)
window.webContents.reloadIgnoringCache()
}
}, 150)
})
// Prevent window close if there are active streaming sessions
window.on("close", (event) => {
// Skip confirmation if app quit was already confirmed by the user
if (isQuitting) {
// Still abort sessions gracefully so partial state is saved
abortAllClaudeSessions()
abortAllCodexStreams()
return
}
if (hasActiveClaudeSessions() || hasActiveCodexStreams()) {
event.preventDefault()
dialog
.showMessageBox(window, {
type: "warning",
buttons: ["Cancel", "Close Anyway"],
defaultId: 0,
cancelId: 0,
title: "Active Sessions",
message: "There are active agent sessions running.",
detail:
"Closing this window will interrupt them. The current progress will be saved. Are you sure you want to close?",
})
.then(({ response }) => {
if (response === 1) {
abortAllClaudeSessions()
abortAllCodexStreams()
window.destroy()
}
})
}
})
// Handle window close
window.on("closed", () => {
console.log(`[Main] Window ${window.id} closed`)
// windowManager handles cleanup via 'closed' event listener
})
// Load the renderer - check auth first
const devServerUrl = process.env.ELECTRON_RENDERER_URL
const authManager = getAuthManager()
console.log("[Main] ========== AUTH CHECK ==========")
console.log("[Main] AuthManager exists:", !!authManager)
const isAuth = authManager.isAuthenticated()
console.log("[Main] isAuthenticated():", isAuth)
const user = authManager.getUser()
console.log("[Main] getUser():", user ? user.email : "null")
console.log("[Main] ================================")
if (isAuth) {
console.log("[Main] ✓ User authenticated, loading app")
// Get stable window ID from manager (assigned during register)
// "main" for first window, "window-2", "window-3", etc. for additional windows
const windowId = windowManager.getStableId(window)
// Build URL params including optional chatId/subChatId
const buildParams = (params: URLSearchParams) => {
params.set("windowId", windowId)
if (options?.chatId) params.set("chatId", options.chatId)
if (options?.subChatId) params.set("subChatId", options.subChatId)
}
if (devServerUrl) {
// Pass params via query for dev mode
const url = new URL(devServerUrl)
buildParams(url.searchParams)
window.loadURL(url.toString())
// Only open devtools for first window in development
if (!app.isPackaged && windowId === "main") {
window.webContents.openDevTools()
}
} else {
// Pass params via hash for production (file:// URLs)
const hashParams = new URLSearchParams()
buildParams(hashParams)
window.loadFile(join(__dirname, "../renderer/index.html"), {
hash: hashParams.toString(),
})
}
} else {
console.log("[Main] ✗ Not authenticated, showing login page")
// In dev mode, login.html is in src/renderer
if (devServerUrl) {
const loginPath = join(app.getAppPath(), "src/renderer/login.html")
window.loadFile(loginPath)
} else {
window.loadFile(join(__dirname, "../renderer/login.html"))
}
}
// Log page load - traffic light visibility is managed by the renderer
window.webContents.on("did-finish-load", () => {
attemptedRendererRecovery = false
console.log("[Main] Page finished loading in window", window.id)
})
window.webContents.on(
"did-fail-load",
(_event, errorCode, errorDescription) => {
console.error(
"[Main] Page failed to load in window",
window.id,
":",
errorCode,
errorDescription,
)
},
)
return window
}
/**
* Create the main application window (alias for createWindow for backwards compatibility)
*/
export function createMainWindow(): BrowserWindow {
return createWindow()
}