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?.htmlPreviewWidth !== settings.htmlPreviewWidth) {
94 root.dataset.htmlPreviewWidth = settings.htmlPreviewWidth;
95 }
96 if (previous?.appearanceContrast !== settings.appearanceContrast) {
97 applyAppearanceContrast(root, settings.appearanceContrast);
98 }
99 if (previous?.glassOpacity !== settings.glassOpacity) {
100 root.style.setProperty("--glass-opacity", `${settings.glassOpacity}%`);
101 if (settings.glassOpacity === 100) {
102 root.style.setProperty("--glass-blur", "0px");
103 } else {
104 root.style.removeProperty("--glass-blur");
105 }
106 }
107 if (
108 previous?.fontFamilySans !== settings.fontFamilySans ||
109 previous.fontFamilyCode !== settings.fontFamilyCode ||
110 previous.fontFamilyComposer !== settings.fontFamilyComposer ||
111 previous.fontSizeInterface !== settings.fontSizeInterface ||
112 previous.fontSizePrompt !== settings.fontSizePrompt ||
113 previous.fontSizeCode !== settings.fontSizeCode ||
114 previous.fontSmoothing !== settings.fontSmoothing ||
115 previousSeparateFonts !== separateFonts
116 ) {
117 applyAppearanceFontVariables(root, {
118 sans: settings.fontFamilySans,
119 code: settings.fontFamilyCode,
120 composer: settings.fontFamilyComposer,
121 sizeInterface: settings.fontSizeInterface,
122 sizePrompt: settings.fontSizePrompt,
123 sizeCode: settings.fontSizeCode,
124 smoothing: settings.fontSmoothing,
125 separate: separateFonts,
126 });
127 }
128 };
129 subscribeClientSettings(apply);
130 subscribeLocalStorageKey(TYPOGRAPHY_ADVANCED_STORAGE_KEY, apply);
131 apply();
132}
133
134function readOpenThreadRef(router: AppRouter): ScopedThreadRef | null {
135 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
136 const draft =
137 target?.kind === "draft"
138 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
139 : null;
140 return resolveActiveThreadRouteRef(target, draft);
141}
142
143function windowTitleThreadStatus(
144 thread: Parameters<typeof resolveWindowTitleThreadStatus>[0] | null,
145): string | null {
146 return thread === null ? null : resolveWindowTitleThreadStatus(thread, m);
147}
148
149/**
150 * Names the open thread and its project in the window title, or the app when none is open.
151 * Screen readers read it on Alt+Tab, so it can lead with the thread and what it's doing.
152 */
153function startDocumentTitle(router: AppRouter): void {
154 const readOnGuestPage = () => router.state.matches.some((match) => match.routeId === "/guest");
155 let openThreadRef = readOpenThreadRef(router);
156 let onGuestPage = readOnGuestPage();
157 const write = () => {
158 // GuestPage titles the tab after the shared thread.
159 if (onGuestPage) return;
160 const thread =
161 openThreadRef === null
162 ? null
163 : appAtomRegistry.get(environmentThreadShells.quietThreadShellAtom(openThreadRef));
164 const project =
165 thread === null
166 ? null
167 : appAtomRegistry.get(
168 environmentProjects.projectAtom(
169 scopeProjectRef(thread.environmentId, thread.projectId),
170 ),
171 );
172 const title = resolveWindowTitle({
173 appDisplayName: resolveServerBackedAppDisplayName({
174 baseName: APP_BASE_NAME,
175 fallbackDisplayName: APP_DISPLAY_NAME,
176 fallbackStageLabel: APP_STAGE_LABEL,
177 primaryServerVersion:
178 appAtomRegistry.get(primaryServerConfigAtom)?.environment.serverVersion ?? null,
179 }),
180 projectTitle: project?.title ?? null,
181 threadTitle: thread?.title ?? null,
182 ...(getClientSettings().screenReaderWindowTitle && {
183 screenReader: {
184 threadStatus: windowTitleThreadStatus(thread),
185 },
186 }),
187 desktop: isElectron,
188 });
189 // Projects change whenever any project does; most changes leave the title alone.
190 if (document.title !== title) document.title = title;
191 };
192 // The open thread's own shell, since the shell lists skip threads hidden by a tag filter.
193 let unsubscribeOpenThread = () => {};
194 const watchOpenThread = () => {
195 unsubscribeOpenThread();
196 unsubscribeOpenThread =
197 openThreadRef === null
198 ? () => {}
199 : appAtomRegistry.subscribe(
200 environmentThreadShells.quietThreadShellAtom(openThreadRef),
201 write,
202 );
203 };
204 // The draft store changes on every keystroke; only a new open thread matters here.
205 const updateOpenThread = () => {
206 const next = readOpenThreadRef(router);
207 const nextOnGuestPage = readOnGuestPage();
208 if (
209 nextOnGuestPage === onGuestPage &&
210 (next && scopedThreadKey(next)) === (openThreadRef && scopedThreadKey(openThreadRef))
211 ) {
212 return;
213 }
214 openThreadRef = next;
215 onGuestPage = nextOnGuestPage;
216 watchOpenThread();
217 write();
218 };
219 watchOpenThread();
220 appAtomRegistry.subscribe(primaryServerConfigAtom, write, { immediate: true });
221 appAtomRegistry.subscribe(environmentProjects.projectsAtom, write);
222 subscribeClientSettings(write);
223 subscribeI18n(write);
224 router.subscribe("onResolved", updateOpenThread);
225 useComposerDraftStore.subscribe(updateOpenThread);
226}
227
228/**
229 * Each route paints its own surface, which the browser chrome samples once it is on screen.
230 * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
231 * can swap the root between the bare outlet and the shell at the same address.
232 */
233function startBrowserChromeThemeSync(router: AppRouter): void {
234 const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
235 router.subscribe("onRendered", resync);
236 router.subscribe("onResolved", resync);
237}
238
239/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
240function startThreadOverlayRetention(router: AppRouter): void {
241 router.subscribe("onResolved", () => {
242 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
243 const draftSession =
244 target?.kind === "draft"
245 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
246 : null;
247 const threadRef =
248 target?.kind === "server"
249 ? target.threadRef
250 : draftSession
251 ? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
252 : null;
253 retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
254 });
255}
256
257/**
258 * Starts every app-lifetime service once, before the first render, and returns the router.
259 * They run for the life of the page, so their disposers are dropped here.
260 */
261export function startAppServices(): AppRouter {
262 // Ahead of the history: the provider auth code must leave the address before anything reads it.
263 startProviderAuthDelivery();
264
265 // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
266 const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());
267
268 if (isElectron) {
269 syncDocumentElectronPlatformClasses(navigator.platform);
270 syncDocumentWindowControlsOverlayClass();
271 }
272
273 installDesktopPasteAsText(window.desktopBridge, window);
274 guardDomAgainstPageTranslation();
275
276 startClientAppearance();
277 startI18n();
278 startDocumentTitle(router);
279 startHostEnvironmentLookup();
280 startEnvironmentThemeRepaint();
281 startThemeBackground();
282 startBrowserChromeThemeSync(router);
283 startDefaultThemeAdoption();
284 startModelPreferencesMigration();
285 startAgentOpenedPreviews();
286 if (isElectron) startElectronBrowserHost();
287 startPreviewTitleRecording();
288 startBrowserProfileReporting();
289 installChatRouteCommands(router);
290 installCommandPaletteCommands(router);
291 registerOpenFavoriteEditorCommand();
292 startThreadOverlayRetention(router);
293 // Drafts promote as their server threads arrive, wherever the user is.
294 subscribeDraftThreadPromotion({
295 registry: appAtomRegistry,
296 threadShellAtom: environmentThreadShells.quietThreadShellAtom,
297 threadRefsAtom: environmentThreadShells.threadRefsAtom,
298 });
299 subscribeComposerDraftModelReconciliation({
300 registry: appAtomRegistry,
301 threadShellAtom: environmentThreadShells.threadShellAtom,
302 threadRefsAtom: environmentThreadShells.threadRefsAtom,
303 shellStateAtom: environmentShell.stateAtom,
304 pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
305 });
306 startMainAppLocationTracking(router);
307 startWorkspaceFocus(router);
308 startBackgroundThreadAnnouncements(appAtomRegistry, router);
309 startThreadVisitedMigration(appAtomRegistry);
310 startSshPasswordPromptQueue();
311
312 startKeybindingsUpdateToasts();
313 startSlowRpcRequestToasts();
314 startHostFreezeToasts();
315 startLegacyThreadMigrationToast();
316 startPermissionUpdateNotices(router);
317 startThreadNotifications(appAtomRegistry, router);
318 startGuideRunNotifications(appAtomRegistry, router);
319 if (isElectron) startDesktopUpdateLaunchNotice();
320
321 return router;
322}