Open History to see the last commit
1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { ClientSettings } from "@t3tools/contracts/settings";
3import { createBrowserHistory, createHashHistory } from "@tanstack/react-router";
4
5import { applyAppearanceContrast } from "./appearanceContrast";
6import { applyAppearanceFontVariables } from "./appearanceFonts";
7import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
8import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter";
9import { startPreviewTitleRecording } from "./browserHistoryStore";
10import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
11import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
12import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
13import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
14import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
15import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
16import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
17import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
18import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
19import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
20import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
21import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
22import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator";
23import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
24import { resolveServerBackedAppDisplayName } from "./branding.logic";
25import { isElectron } from "./env";
26import { subscribeDraftThreadPromotion, useComposerDraftStore } from "./composerDraftStore";
27import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
28import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
29import {
30 getClientSettings,
31 startModelPreferencesMigration,
32 subscribeClientSettings,
33} from "./hooks/useSettings";
34import { syncBrowserChromeTheme } from "./hooks/useTheme";
35import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
36import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
37import {
38 syncDocumentElectronPlatformClasses,
39 syncDocumentWindowControlsOverlayClass,
40} from "./lib/windowControlsOverlay";
41import { startProviderAuthDelivery } from "./providerAuthDelivery";
42import { getRouter, type AppRouter } from "./router";
43import { appAtomRegistry } from "./rpc/atomRegistry";
44import { primaryServerConfigAtom } from "./state/server";
45import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
46import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
47import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
48import { environmentThreadShells } from "./state/threads";
49import { resolveThreadRouteTarget } from "./threadRoutes";
50
51/** Writes appearance settings onto the document, touching only the groups that changed. */
52function startClientAppearance(): void {
53 const root = document.documentElement;
54 let applied: ClientSettings | null = null;
55 const apply = () => {
56 const settings = getClientSettings();
57 const previous = applied;
58 applied = settings;
59 if (previous?.diffColorScheme !== settings.diffColorScheme) {
60 root.dataset.diffColorScheme = settings.diffColorScheme;
61 }
62 if (previous?.chatWidth !== settings.chatWidth) {
63 root.dataset.chatWidth = settings.chatWidth;
64 }
65 if (previous?.redesignEnabled !== settings.redesignEnabled) {
66 root.toggleAttribute("data-redesign", settings.redesignEnabled);
67 }
68 if (previous?.appearanceContrast !== settings.appearanceContrast) {
69 applyAppearanceContrast(root, settings.appearanceContrast);
70 }
71 if (previous?.glassOpacity !== settings.glassOpacity) {
72 root.style.setProperty("--glass-opacity", `${settings.glassOpacity}%`);
73 if (settings.glassOpacity === 100) {
74 root.style.setProperty("--glass-blur", "0px");
75 } else {
76 root.style.removeProperty("--glass-blur");
77 }
78 }
79 if (
80 previous?.fontFamilySans !== settings.fontFamilySans ||
81 previous.fontFamilyCode !== settings.fontFamilyCode ||
82 previous.fontFamilyComposer !== settings.fontFamilyComposer ||
83 previous.fontSizeInterface !== settings.fontSizeInterface ||
84 previous.fontSizePrompt !== settings.fontSizePrompt ||
85 previous.fontSizeCode !== settings.fontSizeCode ||
86 previous.fontSmoothing !== settings.fontSmoothing
87 ) {
88 applyAppearanceFontVariables(root, {
89 sans: settings.fontFamilySans,
90 code: settings.fontFamilyCode,
91 composer: settings.fontFamilyComposer,
92 sizeInterface: settings.fontSizeInterface,
93 sizePrompt: settings.fontSizePrompt,
94 sizeCode: settings.fontSizeCode,
95 smoothing: settings.fontSmoothing,
96 });
97 }
98 };
99 subscribeClientSettings(apply);
100 apply();
101}
102
103function startDocumentTitle(): void {
104 appAtomRegistry.subscribe(
105 primaryServerConfigAtom,
106 (config) => {
107 document.title = resolveServerBackedAppDisplayName({
108 baseName: APP_BASE_NAME,
109 fallbackDisplayName: APP_DISPLAY_NAME,
110 fallbackStageLabel: APP_STAGE_LABEL,
111 primaryServerVersion: config?.environment.serverVersion ?? null,
112 });
113 },
114 { immediate: true },
115 );
116}
117
118/**
119 * Each route paints its own surface, which the browser chrome samples once it is on screen.
120 * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
121 * can swap the root between the bare outlet and the shell at the same address.
122 */
123function startBrowserChromeThemeSync(router: AppRouter): void {
124 const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
125 router.subscribe("onRendered", resync);
126 router.subscribe("onResolved", resync);
127}
128
129/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
130function startThreadOverlayRetention(router: AppRouter): void {
131 router.subscribe("onResolved", () => {
132 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
133 const draftSession =
134 target?.kind === "draft"
135 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
136 : null;
137 const threadRef =
138 target?.kind === "server"
139 ? target.threadRef
140 : draftSession
141 ? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
142 : null;
143 retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
144 });
145}
146
147/**
148 * Starts every app-lifetime service once, before the first render, and returns the router.
149 * They run for the life of the page, so their disposers are dropped here.
150 */
151export function startAppServices(): AppRouter {
152 // Ahead of the history: the provider auth code must leave the address before anything reads it.
153 startProviderAuthDelivery();
154
155 // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
156 const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());
157
158 if (isElectron) {
159 syncDocumentElectronPlatformClasses(navigator.platform);
160 syncDocumentWindowControlsOverlayClass();
161 }
162
163 installDesktopPasteAsText(window.desktopBridge, window);
164
165 startClientAppearance();
166 startDocumentTitle();
167 startEnvironmentThemeRepaint();
168 startBrowserChromeThemeSync(router);
169 startDefaultThemeAdoption();
170 startModelPreferencesMigration();
171 startAgentOpenedPreviews();
172 if (isElectron) startElectronBrowserHost();
173 startPreviewTitleRecording();
174 startBrowserProfileReporting();
175 installChatRouteCommands(router);
176 installCommandPaletteCommands(router);
177 registerOpenFavoriteEditorCommand();
178 startThreadOverlayRetention(router);
179 // Drafts promote as their server threads arrive, wherever the user is.
180 subscribeDraftThreadPromotion({
181 registry: appAtomRegistry,
182 threadShellAtom: environmentThreadShells.quietThreadShellAtom,
183 threadRefsAtom: environmentThreadShells.threadRefsAtom,
184 });
185 startMainAppLocationTracking(router);
186 startBackgroundThreadAnnouncements(appAtomRegistry, router);
187 startThreadVisitedMigration(appAtomRegistry);
188 startSshPasswordPromptQueue();
189
190 startKeybindingsUpdateToasts();
191 startSlowRpcRequestToasts();
192 startHostFreezeToasts();
193 startLegacyThreadMigrationToast();
194 startPermissionUpdateNotices(router);
195 startThreadNotifications(appAtomRegistry, router);
196 startGuideRunNotifications(appAtomRegistry, router);
197 if (isElectron) startDesktopUpdateLaunchNotice();
198
199 return router;
200}