Open History to see the last commit
1import {
2 scopedThreadKey,
3 scopeProjectRef,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import type { ScopedThreadRef } from "@t3tools/contracts";
7import type { ClientSettings } from "@t3tools/contracts/settings";
8import { createBrowserHistory, createHashHistory } from "@tanstack/react-router";
9import * as Schema from "effect/Schema";
10
11import { applyAppearanceContrast } from "./appearanceContrast";
12import { applyAppearanceFontVariables, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "./appearanceFonts";
13import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
14import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter";
15import { startPreviewTitleRecording } from "./browserHistoryStore";
16import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
17import { resolveWindowTitleThreadStatus } from "./components/Sidebar.logic";
18import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
19import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
20import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
21import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
22import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
23import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
24import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
25import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
26import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
27import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
28import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
29import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator";
30import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
31import { resolveServerBackedAppDisplayName, resolveWindowTitle } from "./branding.logic";
32import { isElectron } from "./env";
33import {
34 subscribeComposerDraftModelReconciliation,
35 subscribeDraftThreadPromotion,
36 useComposerDraftStore,
37} from "./composerDraftStore";
38import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
39import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
40import { startThemeBackground } from "./themeBackground";
41import { readLocalStorageValue, subscribeLocalStorageKey } from "./hooks/useLocalStorage";
42import { startHostEnvironmentLookup } from "./state/primaryEnvironment";
43import {
44 getClientSettings,
45 startModelPreferencesMigration,
46 subscribeClientSettings,
47} from "./hooks/useSettings";
48import { syncBrowserChromeTheme } from "./hooks/useTheme";
49import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
50import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
51import {
52 syncDocumentElectronPlatformClasses,
53 syncDocumentWindowControlsOverlayClass,
54} from "./lib/windowControlsOverlay";
55import { startProviderAuthDelivery } from "./providerAuthDelivery";
56import { getRouter, type AppRouter } from "./router";
57import { appAtomRegistry } from "./rpc/atomRegistry";
58import { environmentProjects } from "./state/projects";
59import { primaryServerConfigAtom } from "./state/server";
60import { environmentShell } from "./state/shell";
61import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
62import { startWorkspaceFocus } from "./lib/workspaceFocus";
63import { m } from "./i18n/messages";
64import { startI18n, subscribeI18n } from "./i18n/runtime";
65import { guardDomAgainstPageTranslation } from "./lib/pageTranslationGuard";
66import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
67import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
68import { environmentThreadShells, threadEnvironment } from "./state/threads";
69import { resolveActiveThreadRouteRef, resolveThreadRouteTarget } from "./threadRoutes";
70
71/** Writes appearance settings onto the document, touching only the groups that changed. */
72function startClientAppearance(): void {
73 const root = document.documentElement;
74 let applied: ClientSettings | null = null;
75 let appliedSeparateFonts: boolean | null = null;
76 const apply = () => {
77 const settings = getClientSettings();
78 const previous = applied;
79 applied = settings;
80 const separateFonts = readLocalStorageValue(
81 TYPOGRAPHY_ADVANCED_STORAGE_KEY,
82 false,
83 Schema.Boolean,
84 );
85 const previousSeparateFonts = appliedSeparateFonts;
86 appliedSeparateFonts = separateFonts;
87 if (previous?.diffColorScheme !== settings.diffColorScheme) {
88 root.dataset.diffColorScheme = settings.diffColorScheme;
89 }
90 if (previous?.chatWidth !== settings.chatWidth) {
91 root.dataset.chatWidth = settings.chatWidth;
92 }
93 if (previous?.appearanceContrast !== settings.appearanceContrast) {
94 applyAppearanceContrast(root, settings.appearanceContrast);
95 }
96 if (previous?.glassOpacity !== settings.glassOpacity) {
97 root.style.setProperty("--glass-opacity", `${settings.glassOpacity}%`);
98 if (settings.glassOpacity === 100) {
99 root.style.setProperty("--glass-blur", "0px");
100 } else {
101 root.style.removeProperty("--glass-blur");
102 }
103 }
104 if (
105 previous?.fontFamilySans !== settings.fontFamilySans ||
106 previous.fontFamilyCode !== settings.fontFamilyCode ||
107 previous.fontFamilyComposer !== settings.fontFamilyComposer ||
108 previous.fontSizeInterface !== settings.fontSizeInterface ||
109 previous.fontSizePrompt !== settings.fontSizePrompt ||
110 previous.fontSizeCode !== settings.fontSizeCode ||
111 previous.fontSmoothing !== settings.fontSmoothing ||
112 previousSeparateFonts !== separateFonts
113 ) {
114 applyAppearanceFontVariables(root, {
115 sans: settings.fontFamilySans,
116 code: settings.fontFamilyCode,
117 composer: settings.fontFamilyComposer,
118 sizeInterface: settings.fontSizeInterface,
119 sizePrompt: settings.fontSizePrompt,
120 sizeCode: settings.fontSizeCode,
121 smoothing: settings.fontSmoothing,
122 separate: separateFonts,
123 });
124 }
125 };
126 subscribeClientSettings(apply);
127 subscribeLocalStorageKey(TYPOGRAPHY_ADVANCED_STORAGE_KEY, apply);
128 apply();
129}
130
131function readOpenThreadRef(router: AppRouter): ScopedThreadRef | null {
132 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
133 const draft =
134 target?.kind === "draft"
135 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
136 : null;
137 return resolveActiveThreadRouteRef(target, draft);
138}
139
140function windowTitleThreadStatus(
141 thread: Parameters<typeof resolveWindowTitleThreadStatus>[0] | null,
142): string | null {
143 return thread === null ? null : resolveWindowTitleThreadStatus(thread, m);
144}
145
146/**
147 * Names the open thread and its project in the window title, or the app when none is open.
148 * Screen readers read it on Alt+Tab, so it can lead with the thread and what it's doing.
149 */
150function startDocumentTitle(router: AppRouter): void {
151 const readOnGuestPage = () => router.state.matches.some((match) => match.routeId === "/guest");
152 let openThreadRef = readOpenThreadRef(router);
153 let onGuestPage = readOnGuestPage();
154 const write = () => {
155 // GuestPage titles the tab after the shared thread.
156 if (onGuestPage) return;
157 const thread =
158 openThreadRef === null
159 ? null
160 : appAtomRegistry.get(environmentThreadShells.quietThreadShellAtom(openThreadRef));
161 const project =
162 thread === null
163 ? null
164 : appAtomRegistry.get(
165 environmentProjects.projectAtom(
166 scopeProjectRef(thread.environmentId, thread.projectId),
167 ),
168 );
169 const title = resolveWindowTitle({
170 appDisplayName: resolveServerBackedAppDisplayName({
171 baseName: APP_BASE_NAME,
172 fallbackDisplayName: APP_DISPLAY_NAME,
173 fallbackStageLabel: APP_STAGE_LABEL,
174 primaryServerVersion:
175 appAtomRegistry.get(primaryServerConfigAtom)?.environment.serverVersion ?? null,
176 }),
177 projectTitle: project?.title ?? null,
178 threadTitle: thread?.title ?? null,
179 ...(getClientSettings().screenReaderWindowTitle && {
180 screenReader: {
181 threadStatus: windowTitleThreadStatus(thread),
182 },
183 }),
184 desktop: isElectron,
185 });
186 // Projects change whenever any project does; most changes leave the title alone.
187 if (document.title !== title) document.title = title;
188 };
189 // The open thread's own shell, since the shell lists skip threads hidden by a tag filter.
190 let unsubscribeOpenThread = () => {};
191 const watchOpenThread = () => {
192 unsubscribeOpenThread();
193 unsubscribeOpenThread =
194 openThreadRef === null
195 ? () => {}
196 : appAtomRegistry.subscribe(
197 environmentThreadShells.quietThreadShellAtom(openThreadRef),
198 write,
199 );
200 };
201 // The draft store changes on every keystroke; only a new open thread matters here.
202 const updateOpenThread = () => {
203 const next = readOpenThreadRef(router);
204 const nextOnGuestPage = readOnGuestPage();
205 if (
206 nextOnGuestPage === onGuestPage &&
207 (next && scopedThreadKey(next)) === (openThreadRef && scopedThreadKey(openThreadRef))
208 ) {
209 return;
210 }
211 openThreadRef = next;
212 onGuestPage = nextOnGuestPage;
213 watchOpenThread();
214 write();
215 };
216 watchOpenThread();
217 appAtomRegistry.subscribe(primaryServerConfigAtom, write, { immediate: true });
218 appAtomRegistry.subscribe(environmentProjects.projectsAtom, write);
219 subscribeClientSettings(write);
220 subscribeI18n(write);
221 router.subscribe("onResolved", updateOpenThread);
222 useComposerDraftStore.subscribe(updateOpenThread);
223}
224
225/**
226 * Each route paints its own surface, which the browser chrome samples once it is on screen.
227 * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
228 * can swap the root between the bare outlet and the shell at the same address.
229 */
230function startBrowserChromeThemeSync(router: AppRouter): void {
231 const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
232 router.subscribe("onRendered", resync);
233 router.subscribe("onResolved", resync);
234}
235
236/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
237function startThreadOverlayRetention(router: AppRouter): void {
238 router.subscribe("onResolved", () => {
239 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
240 const draftSession =
241 target?.kind === "draft"
242 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
243 : null;
244 const threadRef =
245 target?.kind === "server"
246 ? target.threadRef
247 : draftSession
248 ? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
249 : null;
250 retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
251 });
252}
253
254/**
255 * Starts every app-lifetime service once, before the first render, and returns the router.
256 * They run for the life of the page, so their disposers are dropped here.
257 */
258export function startAppServices(): AppRouter {
259 // Ahead of the history: the provider auth code must leave the address before anything reads it.
260 startProviderAuthDelivery();
261
262 // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
263 const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());
264
265 if (isElectron) {
266 syncDocumentElectronPlatformClasses(navigator.platform);
267 syncDocumentWindowControlsOverlayClass();
268 }
269
270 installDesktopPasteAsText(window.desktopBridge, window);
271 guardDomAgainstPageTranslation();
272
273 startClientAppearance();
274 startI18n();
275 startDocumentTitle(router);
276 startHostEnvironmentLookup();
277 startEnvironmentThemeRepaint();
278 startThemeBackground();
279 startBrowserChromeThemeSync(router);
280 startDefaultThemeAdoption();
281 startModelPreferencesMigration();
282 startAgentOpenedPreviews();
283 if (isElectron) startElectronBrowserHost();
284 startPreviewTitleRecording();
285 startBrowserProfileReporting();
286 installChatRouteCommands(router);
287 installCommandPaletteCommands(router);
288 registerOpenFavoriteEditorCommand();
289 startThreadOverlayRetention(router);
290 // Drafts promote as their server threads arrive, wherever the user is.
291 subscribeDraftThreadPromotion({
292 registry: appAtomRegistry,
293 threadShellAtom: environmentThreadShells.quietThreadShellAtom,
294 threadRefsAtom: environmentThreadShells.threadRefsAtom,
295 });
296 subscribeComposerDraftModelReconciliation({
297 registry: appAtomRegistry,
298 threadShellAtom: environmentThreadShells.threadShellAtom,
299 threadRefsAtom: environmentThreadShells.threadRefsAtom,
300 shellStateAtom: environmentShell.stateAtom,
301 pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
302 });
303 startMainAppLocationTracking(router);
304 startWorkspaceFocus(router);
305 startBackgroundThreadAnnouncements(appAtomRegistry, router);
306 startThreadVisitedMigration(appAtomRegistry);
307 startSshPasswordPromptQueue();
308
309 startKeybindingsUpdateToasts();
310 startSlowRpcRequestToasts();
311 startHostFreezeToasts();
312 startLegacyThreadMigrationToast();
313 startPermissionUpdateNotices(router);
314 startThreadNotifications(appAtomRegistry, router);
315 startGuideRunNotifications(appAtomRegistry, router);
316 if (isElectron) startDesktopUpdateLaunchNotice();
317
318 return router;
319}