Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

appInit.tsx

326 lines13.7 KB

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