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