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