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