forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
1393 lines (1236 loc) · 42 KB
/
main.ts
File metadata and controls
1393 lines (1236 loc) · 42 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
import * as ChildProcess from "node:child_process";
import * as Crypto from "node:crypto";
import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
nativeImage,
nativeTheme,
protocol,
shell,
} from "electron";
import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type {
DesktopTheme,
DesktopUpdateActionResult,
DesktopUpdateState,
} from "@t3tools/contracts";
import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
reduceDesktopUpdateStateOnCheckStart,
reduceDesktopUpdateStateOnDownloadComplete,
reduceDesktopUpdateStateOnDownloadFailure,
reduceDesktopUpdateStateOnDownloadProgress,
reduceDesktopUpdateStateOnDownloadStart,
reduceDesktopUpdateStateOnInstallFailure,
reduceDesktopUpdateStateOnNoUpdate,
reduceDesktopUpdateStateOnUpdateAvailable,
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
syncShellEnvironment();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
const COMMIT_HASH_DISPLAY_LENGTH = 12;
const LOG_DIR = Path.join(STATE_DIR, "logs");
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const LOG_FILE_MAX_FILES = 10;
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess.ChildProcess | null = null;
let backendPort = 0;
let backendAuthToken = "";
let backendWsUrl = "";
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
let desktopProtocolRegistered = false;
let aboutCommitHashCache: string | null | undefined;
let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
function logTimestamp(): string {
return new Date().toISOString();
}
function logScope(scope: string): string {
return `${scope} run=${APP_RUN_ID}`;
}
function sanitizeLogValue(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function writeDesktopLogHeader(message: string): void {
if (!desktopLogSink) return;
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
}
function writeBackendSessionBoundary(phase: "START" | "END", details: string): void {
if (!backendLogSink) return;
const normalizedDetails = sanitizeLogValue(details);
backendLogSink.write(
`[${logTimestamp()}] ---- APP SESSION ${phase} run=${APP_RUN_ID} ${normalizedDetails} ----\n`,
);
}
function formatErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return String(error);
}
function getSafeExternalUrl(rawUrl: unknown): string | null {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return null;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return null;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return null;
}
return parsedUrl.toString();
}
function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
if (rawTheme === "light" || rawTheme === "dark" || rawTheme === "system") {
return rawTheme;
}
return null;
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
encoding: BufferEncoding | undefined,
): void {
if (!desktopLogSink) return;
const buffer = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(String(chunk), typeof chunk === "string" ? encoding : undefined);
desktopLogSink.write(`[${logTimestamp()}] [${logScope(streamName)}] `);
desktopLogSink.write(buffer);
if (buffer.length === 0 || buffer[buffer.length - 1] !== 0x0a) {
desktopLogSink.write("\n");
}
}
function installStdIoCapture(): void {
if (!app.isPackaged || desktopLogSink === null || restoreStdIoCapture !== null) {
return;
}
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
const originalStderrWrite = process.stderr.write.bind(process.stderr);
const patchWrite =
(streamName: "stdout" | "stderr", originalWrite: typeof process.stdout.write) =>
(
chunk: string | Uint8Array,
encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),
callback?: (error?: Error | null) => void,
): boolean => {
const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : undefined;
writeDesktopStreamChunk(streamName, chunk, encoding);
if (typeof encodingOrCallback === "function") {
return originalWrite(chunk, encodingOrCallback);
}
if (callback !== undefined) {
return originalWrite(chunk, encoding, callback);
}
if (encoding !== undefined) {
return originalWrite(chunk, encoding);
}
return originalWrite(chunk);
};
process.stdout.write = patchWrite("stdout", originalStdoutWrite);
process.stderr.write = patchWrite("stderr", originalStderrWrite);
restoreStdIoCapture = () => {
process.stdout.write = originalStdoutWrite;
process.stderr.write = originalStderrWrite;
restoreStdIoCapture = null;
};
}
function initializePackagedLogging(): void {
if (!app.isPackaged) return;
try {
desktopLogSink = new RotatingFileSink({
filePath: Path.join(LOG_DIR, "desktop-main.log"),
maxBytes: LOG_FILE_MAX_BYTES,
maxFiles: LOG_FILE_MAX_FILES,
});
backendLogSink = new RotatingFileSink({
filePath: Path.join(LOG_DIR, "server-child.log"),
maxBytes: LOG_FILE_MAX_BYTES,
maxFiles: LOG_FILE_MAX_FILES,
});
installStdIoCapture();
writeDesktopLogHeader(`runtime log capture enabled logDir=${LOG_DIR}`);
} catch (error) {
// Logging setup should never block app startup.
console.error("[desktop] failed to initialize packaged logging", error);
}
}
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
if (!app.isPackaged || backendLogSink === null) return;
const writeChunk = (chunk: unknown): void => {
if (!backendLogSink) return;
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
backendLogSink.write(buffer);
};
child.stdout?.on("data", writeChunk);
child.stderr?.on("data", writeChunk);
}
initializePackagedLogging();
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
if (process.platform !== "darwin") return undefined;
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache ?? undefined;
}
try {
const icon = nativeImage.createFromNamedImage("trash").resize({
width: 14,
height: 14,
});
if (icon.isEmpty()) {
destructiveMenuIconCache = null;
return undefined;
}
icon.setTemplateImage(true);
destructiveMenuIconCache = icon;
return icon;
} catch {
destructiveMenuIconCache = null;
return undefined;
}
}
let updatePollTimer: ReturnType<typeof setInterval> | null = null;
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
let updateCheckInFlight = false;
let updateDownloadInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateDownloadInFlight) return "download";
if (updateCheckInFlight) return "check";
return updateState.errorContext;
}
protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
function resolveAppRoot(): string {
if (!app.isPackaged) {
return ROOT_DIR;
}
return app.getAppPath();
}
/** Read the baked-in app-update.yml config (if applicable). */
function readAppUpdateYml(): Record<string, string> | null {
try {
// electron-updater reads from process.resourcesPath in packaged builds,
// or dev-app-update.yml via app.getAppPath() in dev.
const ymlPath = app.isPackaged
? Path.join(process.resourcesPath, "app-update.yml")
: Path.join(app.getAppPath(), "dev-app-update.yml");
const raw = FS.readFileSync(ymlPath, "utf-8");
// The YAML is simple key-value pairs — avoid pulling in a YAML parser by
// doing a line-based parse (fields: provider, owner, repo, releaseType, …).
const entries: Record<string, string> = {};
for (const line of raw.split("\n")) {
const match = line.match(/^(\w+):\s*(.+)$/);
if (match?.[1] && match[2]) entries[match[1]] = match[2].trim();
}
return entries.provider ? entries : null;
} catch {
return null;
}
}
function normalizeCommitHash(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
if (!COMMIT_HASH_PATTERN.test(trimmed)) {
return null;
}
return trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase();
}
function resolveEmbeddedCommitHash(): string | null {
const packageJsonPath = Path.join(resolveAppRoot(), "package.json");
if (!FS.existsSync(packageJsonPath)) {
return null;
}
try {
const raw = FS.readFileSync(packageJsonPath, "utf8");
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
return normalizeCommitHash(parsed.t3codeCommitHash);
} catch {
return null;
}
}
function resolveAboutCommitHash(): string | null {
if (aboutCommitHashCache !== undefined) {
return aboutCommitHashCache;
}
const envCommitHash = normalizeCommitHash(process.env.T3CODE_COMMIT_HASH);
if (envCommitHash) {
aboutCommitHashCache = envCommitHash;
return aboutCommitHashCache;
}
// Only packaged builds are required to expose commit metadata.
if (!app.isPackaged) {
aboutCommitHashCache = null;
return aboutCommitHashCache;
}
aboutCommitHashCache = resolveEmbeddedCommitHash();
return aboutCommitHashCache;
}
function resolveBackendEntry(): string {
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
if (!app.isPackaged) {
return resolveAppRoot();
}
return OS.homedir();
}
function resolveDesktopStaticDir(): string | null {
const appRoot = resolveAppRoot();
const candidates = [
Path.join(appRoot, "apps/server/dist/client"),
Path.join(appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
if (FS.existsSync(Path.join(candidate, "index.html"))) {
return candidate;
}
}
return null;
}
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = Path.posix.normalize(rawPath).replace(/^\/+/, "");
if (normalizedPath.includes("..")) {
return Path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
const resolvedPath = Path.join(staticRoot, requestedPath);
if (Path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = Path.join(resolvedPath, "index.html");
if (FS.existsSync(nestedIndex)) {
return nestedIndex;
}
return Path.join(staticRoot, "index.html");
}
function isStaticAssetRequest(requestUrl: string): boolean {
try {
const url = new URL(requestUrl);
return Path.extname(url.pathname).length > 0;
} catch {
return false;
}
}
function handleFatalStartupError(stage: string, error: unknown): void {
const message = formatErrorMessage(error);
const detail =
error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
writeDesktopLogHeader(`fatal startup error stage=${stage} message=${message}`);
console.error(`[desktop] fatal startup error (${stage})`, error);
if (!isQuitting) {
isQuitting = true;
dialog.showErrorBox("T3 Code failed to start", `Stage: ${stage}\n${message}${detail}`);
}
stopBackend();
restoreStdIoCapture?.();
app.quit();
}
function registerDesktopProtocol(): void {
if (isDevelopment || desktopProtocolRegistered) return;
const staticRoot = resolveDesktopStaticDir();
if (!staticRoot) {
throw new Error(
"Desktop static bundle missing. Build apps/server (with bundled client) first.",
);
}
const staticRootResolved = Path.resolve(staticRoot);
const staticRootPrefix = `${staticRootResolved}${Path.sep}`;
const fallbackIndex = Path.join(staticRootResolved, "index.html");
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
try {
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = Path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url);
if (!isInRoot || !FS.existsSync(resolvedCandidate)) {
if (isAssetRequest) {
callback({ error: -6 });
return;
}
callback({ path: fallbackIndex });
return;
}
callback({ path: resolvedCandidate });
} catch {
callback({ path: fallbackIndex });
}
});
desktopProtocolRegistered = true;
}
function dispatchMenuAction(action: string): void {
const existingWindow =
BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
const targetWindow = existingWindow ?? createWindow();
if (!existingWindow) {
mainWindow = targetWindow;
}
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
if (!targetWindow.isVisible()) {
targetWindow.show();
}
targetWindow.focus();
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
}
function handleCheckForUpdatesMenuClick(): void {
const disabledReason = getAutoUpdateDisabledReason({
isDevelopment,
isPackaged: app.isPackaged,
platform: process.platform,
appImage: process.env.APPIMAGE,
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
});
if (disabledReason) {
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
void dialog.showMessageBox({
type: "info",
title: "Updates unavailable",
message: "Automatic updates are not available right now.",
detail: disabledReason,
buttons: ["OK"],
});
return;
}
if (!BrowserWindow.getAllWindows().length) {
mainWindow = createWindow();
}
void checkForUpdatesFromMenu();
}
async function checkForUpdatesFromMenu(): Promise<void> {
await checkForUpdates("menu");
if (updateState.status === "up-to-date") {
void dialog.showMessageBox({
type: "info",
title: "You're up to date!",
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
buttons: ["OK"],
});
} else if (updateState.status === "error") {
void dialog.showMessageBox({
type: "warning",
title: "Update check failed",
message: "Could not check for updates.",
detail: updateState.message ?? "An unknown error occurred. Please try again later.",
buttons: ["OK"],
});
}
}
function configureApplicationMenu(): void {
const template: MenuItemConstructorOptions[] = [];
if (process.platform === "darwin") {
template.push({
label: app.name,
submenu: [
{ role: "about" },
{
label: "Check for Updates...",
click: () => handleCheckForUpdatesMenuClick(),
},
{ type: "separator" },
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
});
}
template.push(
{
label: "File",
submenu: [
...(process.platform === "darwin"
? []
: [
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" as const },
]),
{ role: process.platform === "darwin" ? "close" : "quit" },
],
},
{ role: "editMenu" },
{
label: "View",
submenu: [
{ role: "reload" },
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
{ role: "windowMenu" },
{
role: "help",
submenu: [
{
label: "Check for Updates...",
click: () => handleCheckForUpdatesMenuClick(),
},
],
},
);
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
function resolveResourcePath(fileName: string): string | null {
const candidates = [
Path.join(__dirname, "../resources", fileName),
Path.join(__dirname, "../prod-resources", fileName),
Path.join(process.resourcesPath, "resources", fileName),
Path.join(process.resourcesPath, fileName),
];
for (const candidate of candidates) {
if (FS.existsSync(candidate)) {
return candidate;
}
}
return null;
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
return resolveResourcePath(`icon.${ext}`);
}
/**
* Resolve the Electron userData directory path.
*
* Electron derives the default userData path from `productName` in
* package.json, which currently produces directories with spaces and
* parentheses (e.g. `~/.config/T3 Code (Alpha)` on Linux). This is
* unfriendly for shell usage and violates Linux naming conventions.
*
* We override it to a clean lowercase name (`t3code`). If the legacy
* directory already exists we keep using it so existing users don't
* lose their Chromium profile data (localStorage, cookies, sessions).
*/
function resolveUserDataPath(): string {
const appDataBase =
process.platform === "win32"
? process.env.APPDATA || Path.join(OS.homedir(), "AppData", "Roaming")
: process.platform === "darwin"
? Path.join(OS.homedir(), "Library", "Application Support")
: process.env.XDG_CONFIG_HOME || Path.join(OS.homedir(), ".config");
const legacyPath = Path.join(appDataBase, LEGACY_USER_DATA_DIR_NAME);
if (FS.existsSync(legacyPath)) {
return legacyPath;
}
return Path.join(appDataBase, USER_DATA_DIR_NAME);
}
function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME);
const commitHash = resolveAboutCommitHash();
app.setAboutPanelOptions({
applicationName: APP_DISPLAY_NAME,
applicationVersion: app.getVersion(),
version: commitHash ?? "unknown",
});
if (process.platform === "win32") {
app.setAppUserModelId(APP_USER_MODEL_ID);
}
if (process.platform === "darwin" && app.dock) {
const iconPath = resolveIconPath("png");
if (iconPath) {
app.dock.setIcon(iconPath);
}
}
}
function clearUpdatePollTimer(): void {
if (updateStartupTimer) {
clearTimeout(updateStartupTimer);
updateStartupTimer = null;
}
if (updatePollTimer) {
clearInterval(updatePollTimer);
updatePollTimer = null;
}
}
function emitUpdateState(): void {
for (const window of BrowserWindow.getAllWindows()) {
if (window.isDestroyed()) continue;
window.webContents.send(UPDATE_STATE_CHANNEL, updateState);
}
}
function setUpdateState(patch: Partial<DesktopUpdateState>): void {
updateState = { ...updateState, ...patch };
emitUpdateState();
}
function shouldEnableAutoUpdates(): boolean {
return (
getAutoUpdateDisabledReason({
isDevelopment,
isPackaged: app.isPackaged,
platform: process.platform,
appImage: process.env.APPIMAGE,
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
}) === null
);
}
async function checkForUpdates(reason: string): Promise<void> {
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
if (updateState.status === "downloading" || updateState.status === "downloaded") {
console.info(
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
);
return;
}
updateCheckInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
console.info(`[desktop-updater] Checking for updates (${reason})...`);
try {
await autoUpdater.checkForUpdates();
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
);
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
} finally {
updateCheckInFlight = false;
}
}
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
return { accepted: false, completed: false };
}
updateDownloadInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
console.info("[desktop-updater] Downloading update...");
try {
await autoUpdater.downloadUpdate();
return { accepted: true, completed: true };
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(reduceDesktopUpdateStateOnDownloadFailure(updateState, message));
console.error(`[desktop-updater] Failed to download update: ${message}`);
return { accepted: true, completed: false };
} finally {
updateDownloadInFlight = false;
}
}
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
return { accepted: false, completed: false };
}
isQuitting = true;
clearUpdatePollTimer();
try {
await stopBackendAndWaitForExit();
autoUpdater.quitAndInstall();
return { accepted: true, completed: true };
} catch (error: unknown) {
const message = formatErrorMessage(error);
isQuitting = false;
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
console.error(`[desktop-updater] Failed to install update: ${message}`);
return { accepted: true, completed: false };
}
}
function configureAutoUpdater(): void {
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
if (!enabled) {
return;
}
updaterConfigured = true;
const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
if (githubToken) {
// When a token is provided, re-configure the feed with `private: true` so
// electron-updater uses the GitHub API (api.github.com) instead of the
// public Atom feed (github.com/…/releases.atom) which rejects Bearer auth.
const appUpdateYml = readAppUpdateYml();
if (appUpdateYml?.provider === "github") {
autoUpdater.setFeedURL({
...appUpdateYml,
provider: "github" as const,
private: true,
token: githubToken,
});
}
}
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
// Keep alpha branding, but force all installs onto the stable update track.
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
autoUpdater.allowDowngrade = false;
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
let lastLoggedDownloadMilestone = -1;
if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
console.info(
"[desktop-updater] Apple Silicon host detected while running Intel build; updates will switch to arm64 packages.",
);
}
autoUpdater.on("checking-for-update", () => {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
info.version,
new Date().toISOString(),
),
);
lastLoggedDownloadMilestone = -1;
console.info(`[desktop-updater] Update available: ${info.version}`);
});
autoUpdater.on("update-not-available", () => {
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
console.info("[desktop-updater] No updates available.");
});
autoUpdater.on("error", (error) => {
const message = formatErrorMessage(error);
if (!updateCheckInFlight && !updateDownloadInFlight) {
setUpdateState({
status: "error",
message,
checkedAt: new Date().toISOString(),
downloadPercent: null,
errorContext: resolveUpdaterErrorContext(),
canRetry: updateState.availableVersion !== null || updateState.downloadedVersion !== null,
});
}
console.error(`[desktop-updater] Updater error: ${message}`);
});
autoUpdater.on("download-progress", (progress) => {
const percent = Math.floor(progress.percent);
if (
shouldBroadcastDownloadProgress(updateState, progress.percent) ||
updateState.message !== null
) {
setUpdateState(reduceDesktopUpdateStateOnDownloadProgress(updateState, progress.percent));
}
const milestone = percent - (percent % 10);
if (milestone > lastLoggedDownloadMilestone) {
lastLoggedDownloadMilestone = milestone;
console.info(`[desktop-updater] Download progress: ${percent}%`);
}
});
autoUpdater.on("update-downloaded", (info) => {
setUpdateState(reduceDesktopUpdateStateOnDownloadComplete(updateState, info.version));
console.info(`[desktop-updater] Update downloaded: ${info.version}`);
});
clearUpdatePollTimer();
updateStartupTimer = setTimeout(() => {
updateStartupTimer = null;
void checkForUpdates("startup");
}, AUTO_UPDATE_STARTUP_DELAY_MS);
updateStartupTimer.unref();
updatePollTimer = setInterval(() => {
void checkForUpdates("poll");
}, AUTO_UPDATE_POLL_INTERVAL_MS);
updatePollTimer.unref();
}
function backendEnv(): NodeJS.ProcessEnv {
return {
...process.env,
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_HOME: BASE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
restartAttempt += 1;
console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
restartTimer = setTimeout(() => {
restartTimer = null;
startBackend();
}, delayMs);
}
function startBackend(): void {
if (isQuitting || backendProcess) return;
const backendEntry = resolveBackendEntry();
if (!FS.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
return;
}
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
cwd: resolveBackendCwd(),
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
});
backendProcess = child;
let backendSessionClosed = false;
const closeBackendSession = (details: string) => {
if (backendSessionClosed) return;
backendSessionClosed = true;
writeBackendSessionBoundary("END", details);
};
writeBackendSessionBoundary(
"START",
`pid=${child.pid ?? "unknown"} port=${backendPort} cwd=${resolveBackendCwd()}`,
);
captureBackendOutput(child);
child.once("spawn", () => {
restartAttempt = 0;
});
child.on("error", (error) => {
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
scheduleBackendRestart(error.message);
});
child.on("exit", (code, signal) => {
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
);
if (isQuitting) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});