-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathindex.ts
More file actions
549 lines (494 loc) · 16 KB
/
Copy pathindex.ts
File metadata and controls
549 lines (494 loc) · 16 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
import path from "node:path";
import { pathToFileURL } from "node:url";
import {
setAgentSetupTemplatesDir,
setupAgentIntegrations,
writeSharedDisabledAgentIds,
} from "@superset/agent-setup";
import { settings } from "@superset/local-db";
import { app, dialog, Notification, net, protocol, session } from "electron";
import { makeAppSetup } from "lib/electron-app/factories/app/setup";
import {
authEvents,
handleAuthCallback,
loadToken,
parseAuthDeepLink,
} from "lib/trpc/routers/auth/utils/auth-functions";
import { applyShellEnvToProcess } from "lib/trpc/routers/workspaces/utils/shell-env";
import { env as mainEnv } from "main/env.main";
import {
DEFAULT_CONFIRM_ON_QUIT,
PLATFORM,
PROTOCOL_SCHEME,
} from "shared/constants";
import { initAppState } from "./lib/app-state";
import { requestAppleEventsAccess } from "./lib/apple-events-permission";
import { isUpdateReadyToInstall, setupAutoUpdater } from "./lib/auto-updater";
import { startBrowserBridge } from "./lib/browser/browser-bridge";
import { installBundledCliShim } from "./lib/bundled-cli";
import { resolveDevWorkspaceName } from "./lib/dev-workspace-name";
import { setWorkspaceDockIcon } from "./lib/dock-icon";
import { loadWebviewBrowserExtension } from "./lib/extensions";
import { getHostServiceCoordinator } from "./lib/host-service-coordinator";
import { localDb } from "./lib/local-db";
import { requestLocalNetworkAccess } from "./lib/local-network-permission";
import { PAGE_SCHEME, pageProtocolHandler } from "./lib/pageContent";
import {
initTanstackDbPersistence,
shutdownTanstackDbPersistence,
} from "./lib/persistence/persistence";
import { syncInstalledPluginMcpServers } from "./lib/plugin-installs";
import { portForwardManager } from "./lib/port-forward";
import { ensureProjectIconsDir, getProjectIconPath } from "./lib/project-icons";
import { runQuitCleanup } from "./lib/quit-sequence";
import { initSentry } from "./lib/sentry";
import {
prewarmTerminalRuntime,
reconcileDaemonSessions,
} from "./lib/terminal";
import {
disposeTerminalHostClient,
getTerminalHostClient,
} from "./lib/terminal-host/client";
import { disposeTray, initTray } from "./lib/tray";
import { getFocusedOrLastWindow } from "./lib/window-registry/window-registry";
import { sweepNetworkLogs } from "./network-logger-sweep";
import {
createPlatformWindow,
initAppServices,
markAppQuitting,
persistOpenWindows,
restoreWindows,
} from "./windows/main";
console.log("[main] Local database ready:", !!localDb);
const IS_DEV = process.env.NODE_ENV === "development";
void applyShellEnvToProcess().catch((error) => {
console.error("[main] Failed to apply shell environment:", error);
});
// Dev mode: label the app with the workspace name so multiple worktrees are distinguishable
if (IS_DEV) {
const workspaceName = resolveDevWorkspaceName();
if (workspaceName) {
app.setName(`Superset (${workspaceName})`);
}
}
// Dev mode: register with execPath + app script so macOS launches Electron with our entry point
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(PROTOCOL_SCHEME, process.execPath, [
path.resolve(process.argv[1]),
]);
}
} else {
app.setAsDefaultProtocolClient(PROTOCOL_SCHEME);
}
async function processDeepLink(url: string): Promise<void> {
const authLink = parseAuthDeepLink(url);
if (authLink.type !== "not-auth") {
// Never log the auth URL: it contains the desktop session token.
console.log("[main] Processing auth deep link");
const result =
authLink.type === "valid"
? await handleAuthCallback(authLink.params)
: {
success: false as const,
error: "The sign-in link was incomplete. Please try again.",
};
if (result.success) {
focusMainWindow();
} else {
console.error("[main] Auth deep link failed:", result.error);
focusMainWindow();
dialog.showErrorBox(
"Sign-in failed",
result.error ??
"Superset could not complete sign-in. Please try again.",
);
}
return;
}
console.log("[main] Processing deep link:", url);
// Non-auth deep links: extract path and navigate in renderer
// e.g. superset://tasks/my-slug -> /tasks/my-slug
const path = `/${url.split("://")[1]}`;
focusMainWindow();
const target = getFocusedOrLastWindow();
target?.webContents.send("deep-link-navigate", path);
}
function findDeepLinkInArgv(argv: string[]): string | undefined {
return argv.find((arg) => arg.startsWith(`${PROTOCOL_SCHEME}://`));
}
export function focusMainWindow(): void {
const target = getFocusedOrLastWindow();
if (target) {
if (target.isMinimized()) {
target.restore();
}
target.show();
target.focus();
} else {
// Triggers window creation via makeAppSetup's activate handler
app.emit("activate");
}
}
function registerWithMacOSNotificationCenter() {
if (!PLATFORM.IS_MAC || !Notification.isSupported()) return;
const registrationNotification = new Notification({
title: app.name,
body: " ",
silent: true,
});
let handled = false;
const cleanup = () => {
if (handled) return;
handled = true;
registrationNotification.close();
};
registrationNotification.on("show", () => {
cleanup();
console.log("[notifications] Registered with Notification Center");
});
// Fallback timeout in case macOS doesn't fire events
setTimeout(cleanup, 1000);
registrationNotification.show();
}
// macOS open-url can fire before the window exists (cold-start via protocol link).
// Queue the URL and process it after initialization.
let pendingDeepLinkUrl: string | null = null;
let appReady = false;
app.on("open-url", async (event, url) => {
event.preventDefault();
if (appReady) {
await processDeepLink(url);
} else {
pendingDeepLinkUrl = url;
}
});
let isQuitting = false;
let skipQuitConfirmation = false;
let forceFullCleanup = false;
export function setSkipQuitConfirmation(): void {
skipQuitConfirmation = true;
}
export function quitApp(): void {
setSkipQuitConfirmation();
app.quit();
}
/** Quit + also stop background services. Tray "Quit Completely". */
export function quitAppCompletely(): void {
forceFullCleanup = true;
setSkipQuitConfirmation();
app.quit();
}
/** Bypasses before-quit. Host-service children self-exit via the parent watchdog. */
export function exitImmediately(): void {
app.exit(0);
}
function getConfirmOnQuitSetting(): boolean {
try {
const row = localDb.select().from(settings).get();
return row?.confirmOnQuit ?? DEFAULT_CONFIRM_ON_QUIT;
} catch {
return DEFAULT_CONFIRM_ON_QUIT;
}
}
app.on("before-quit", async (event) => {
if (isQuitting) return;
const isDev = process.env.NODE_ENV === "development";
if (!skipQuitConfirmation && !isDev && getConfirmOnQuitSetting()) {
event.preventDefault();
try {
const { response } = await dialog.showMessageBox({
type: "question",
buttons: ["Quit", "Cancel"],
defaultId: 0,
cancelId: 1,
title: "Quit Superset",
message: "Are you sure you want to quit?",
});
if (response === 1) {
return;
}
} catch (error) {
console.error("[main] Quit confirmation dialog failed:", error);
}
}
isQuitting = true;
// Local port-forward listeners hold no state worth draining; drop them so
// nothing keeps 127.0.0.1:<port> bound after the app is gone.
portForwardManager.stopAll();
// Snapshot all open windows (bounds + org) before they close, so relaunch
// restores them. markAppQuitting() stops per-window close handlers from
// shrinking the set as windows close one-by-one.
markAppQuitting();
persistOpenWindows();
await runQuitCleanup({
isDev,
forceFullCleanup,
isUpdateInstalling: isUpdateReadyToInstall(),
stopHostServices: () => getHostServiceCoordinator().stopAll(),
teardownTerminalHost,
disposeTerminalHostClient,
shutdownPersistence: shutdownTanstackDbPersistence,
disposeTray,
forceExit: (code) => app.exit(code),
});
});
/**
* Fully stop the v1 terminal-host process. Do not call this for update
* installs: terminal-host owns the PTY subprocesses, so shutdown is
* destructive and prevents reattach on next launch.
*/
async function teardownTerminalHost(): Promise<void> {
try {
await getTerminalHostClient().shutdownIfRunning({ killSessions: true });
} catch (err) {
console.warn("[main] terminal-host dev shutdown failed:", err);
}
disposeTerminalHostClient();
}
process.on("uncaughtException", (error) => {
if (isQuitting) return;
console.error("[main] Uncaught exception:", error);
});
process.on("unhandledRejection", (reason) => {
if (isQuitting) return;
console.error("[main] Unhandled rejection:", reason);
});
// Without these handlers, Electron may not quit when electron-vite sends SIGTERM
if (process.env.NODE_ENV === "development") {
let signalHandled = false;
const handleTerminationSignal = (signal: string) => {
if (signalHandled) return;
signalHandled = true;
console.log(`[main] Received ${signal}, quitting...`);
getHostServiceCoordinator().stopAll();
void Promise.allSettled([teardownTerminalHost()]).finally(() =>
app.exit(0),
);
};
process.on("SIGTERM", () => handleTerminationSignal("SIGTERM"));
process.on("SIGINT", () => handleTerminationSignal("SIGINT"));
// Fallback: electron-vite may exit without signaling the child Electron process
const parentPid = process.ppid;
const isParentAlive = (): boolean => {
try {
process.kill(parentPid, 0);
return true;
} catch {
return false;
}
};
const parentCheckInterval = setInterval(() => {
if (!isParentAlive()) {
console.log("[main] Parent process exited, quitting...");
clearInterval(parentCheckInterval);
handleTerminationSignal("parent-exit");
}
}, 1000);
parentCheckInterval.unref();
}
protocol.registerSchemesAsPrivileged([
{
scheme: "superset-icon",
privileges: {
standard: true,
secure: true,
bypassCSP: true,
supportFetchAPI: true,
},
},
{
scheme: "superset-font",
privileges: {
standard: true,
secure: true,
bypassCSP: true,
supportFetchAPI: true,
},
},
{
scheme: PAGE_SCHEME,
privileges: {
standard: true,
secure: true,
},
},
]);
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.exit(0);
} else {
// Windows/Linux: protocol URL arrives as argv on the second instance
app.on("second-instance", async (_event, argv) => {
focusMainWindow();
const url = findDeepLinkInArgv(argv);
if (url) {
await processDeepLink(url);
}
});
(async () => {
await app.whenReady();
registerWithMacOSNotificationCenter();
requestAppleEventsAccess();
requestLocalNetworkAccess();
// Must register on both default session and the app's custom partition
const iconProtocolHandler = (request: Request) => {
const url = new URL(request.url);
const projectId = url.pathname.replace(/^\//, "");
const iconPath = getProjectIconPath(projectId);
if (!iconPath) {
return new Response("Not found", { status: 404 });
}
return net.fetch(pathToFileURL(iconPath).toString());
};
protocol.handle("superset-icon", iconProtocolHandler);
session
.fromPartition("persist:superset")
.protocol.handle("superset-icon", iconProtocolHandler);
protocol.handle(PAGE_SCHEME, pageProtocolHandler);
session
.fromPartition("persist:superset")
.protocol.handle(PAGE_SCHEME, pageProtocolHandler);
// Serve system fonts (e.g. SF Mono on macOS) via custom protocol
// so the renderer can use @font-face with font-src 'self' CSP
if (process.platform === "darwin") {
const SYSTEM_FONT_DIRS = [
"/System/Applications/Utilities/Terminal.app/Contents/Resources/Fonts",
"/System/Library/Fonts",
"/Library/Fonts",
];
const fontProtocolHandler = async (request: Request) => {
const url = new URL(request.url);
const filename = path.basename(url.pathname);
if (!/\.(otf|ttf|woff2?)$/i.test(filename)) {
return new Response("Not found", { status: 404 });
}
for (const dir of SYSTEM_FONT_DIRS) {
const fontPath = path.join(dir, filename);
try {
return await net.fetch(pathToFileURL(fontPath).toString());
} catch {
// Not in this directory
}
}
return new Response("Not found", { status: 404 });
};
protocol.handle("superset-font", fontProtocolHandler);
session
.fromPartition("persist:superset")
.protocol.handle("superset-font", fontProtocolHandler);
}
ensureProjectIconsDir();
setWorkspaceDockIcon();
initSentry();
await initAppState();
initTanstackDbPersistence();
sweepNetworkLogs();
await loadWebviewBrowserExtension();
// Must happen before renderer restore runs
await reconcileDaemonSessions();
prewarmTerminalRuntime();
// Must be listening before any host-service spawns: the child learns the
// bridge endpoint/secret from its env, so a late bridge means browser
// control stays dark until the next respawn.
try {
await startBrowserBridge();
} catch (error) {
console.error("[main] Failed to start browser bridge:", error);
}
const hostServiceCoordinator = getHostServiceCoordinator();
hostServiceCoordinator.setConfigProvider(async () => {
const { token } = await loadToken();
if (!token) return null;
return { authToken: token, cloudApiUrl: mainEnv.NEXT_PUBLIC_API_URL };
});
// The authenticated session's cached membership is the source of truth.
// Host data on disk can outlive membership and must never resurrect an
// obsolete service. This cache keeps subsequent launches offline-capable.
let authGeneration = 0;
const reconcileHostServices = async (providedAuth?: {
token: string;
organizationIds: string[];
}) => {
const generation = authGeneration;
try {
const storedAuth = providedAuth ?? (await loadToken());
if (generation !== authGeneration) return;
if (!storedAuth.token || !storedAuth.organizationIds) return;
await hostServiceCoordinator.reconcile(storedAuth.organizationIds, {
authToken: storedAuth.token,
cloudApiUrl: mainEnv.NEXT_PUBLIC_API_URL,
});
} catch (error) {
console.error("[main] host-service reconcile failed:", error);
}
};
void reconcileHostServices();
// A new token can belong to a different account. Stop immediately and wait
// for that account's session membership before starting anything.
authEvents.on("token-saved", () => {
authGeneration++;
hostServiceCoordinator.stopAll();
});
authEvents.on("token-cleared", () => {
authGeneration++;
hostServiceCoordinator.stopAll();
});
authEvents.on(
"organization-ids-saved",
(data: { token: string; organizationIds: string[] }) => {
authGeneration++;
void reconcileHostServices(data);
},
);
try {
// The vite build copies @superset/agent-setup's templates (plus the
// bundled Claude plugin) next to this bundle; see vite/helpers.ts.
setAgentSetupTemplatesDir(path.join(__dirname, "templates"));
const disabledAgentHooks =
localDb.select().from(settings).get()?.disabledAgentHooks ?? [];
// Mirror the disable list so CLI-launched host-services on this
// machine honor it instead of re-provisioning disabled agents.
writeSharedDisabledAgentIds(disabledAgentHooks);
setupAgentIntegrations({ disabledAgentIds: disabledAgentHooks });
} catch (error) {
console.error("[main] Failed to set up agent integrations:", error);
}
try {
// Converge agent MCP configs on the installed-plugin set, so
// installs/uninstalls that missed a mid-session sync land here.
syncInstalledPluginMcpServers();
} catch (error) {
console.error("[main] Failed to sync installed plugins:", error);
}
try {
installBundledCliShim();
} catch (error) {
console.error("[main] Failed to install bundled CLI shim:", error);
}
if (IS_DEV) {
hostServiceCoordinator.enableDevReload(async () => {
const { token } = await loadToken();
if (!token) return null;
return { authToken: token, cloudApiUrl: mainEnv.NEXT_PUBLIC_API_URL };
});
}
initAppServices();
await makeAppSetup(
() => createPlatformWindow({ orgId: null }),
restoreWindows,
);
setupAutoUpdater();
initTray();
const coldStartUrl = findDeepLinkInArgv(process.argv);
if (coldStartUrl) {
await processDeepLink(coldStartUrl);
}
if (pendingDeepLinkUrl) {
await processDeepLink(pendingDeepLinkUrl);
pendingDeepLinkUrl = null;
}
appReady = true;
})();
}