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