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

appInit.tsx

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