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

appInit.tsx

208 lines9.0 KB

1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { ClientSettings } from "@t3tools/contracts/settings";
3import { createBrowserHistory, createHashHistory } from "@tanstack/react-router";
4​
5import { applyAppearanceContrast } from "./appearanceContrast";
6import { applyAppearanceFontVariables } from "./appearanceFonts";
7import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
8import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter";
9import { startPreviewTitleRecording } from "./browserHistoryStore";
10import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
11import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
12import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
13import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
14import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
15import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
16import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
17import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
18import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
19import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
20import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
21import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
22import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator";
23import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
24import { resolveServerBackedAppDisplayName } from "./branding.logic";
25import { isElectron } from "./env";
26import {
27 subscribeComposerDraftModelReconciliation,
28 subscribeDraftThreadPromotion,
29 useComposerDraftStore,
30} from "./composerDraftStore";
31import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
32import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
33import {
34 getClientSettings,
35 startModelPreferencesMigration,
36 subscribeClientSettings,
37} from "./hooks/useSettings";
38import { syncBrowserChromeTheme } from "./hooks/useTheme";
39import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
40import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
41import {
42 syncDocumentElectronPlatformClasses,
43 syncDocumentWindowControlsOverlayClass,
44} from "./lib/windowControlsOverlay";
45import { startProviderAuthDelivery } from "./providerAuthDelivery";
46import { getRouter, type AppRouter } from "./router";
47import { appAtomRegistry } from "./rpc/atomRegistry";
48import { primaryServerConfigAtom } from "./state/server";
49import { environmentShell } from "./state/shell";
50import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
51import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
52import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
53import { environmentThreadShells } from "./state/threads";
54import { resolveThreadRouteTarget } from "./threadRoutes";
55​
56/** Writes appearance settings onto the document, touching only the groups that changed. */
57function startClientAppearance(): void {
58 const root = document.documentElement;
59 let applied: ClientSettings | null = null;
60 const apply = () => {
61 const settings = getClientSettings();
62 const previous = applied;
63 applied = settings;
64 if (previous?.diffColorScheme !== settings.diffColorScheme) {
65 root.dataset.diffColorScheme = settings.diffColorScheme;
66 }
67 if (previous?.chatWidth !== settings.chatWidth) {
68 root.dataset.chatWidth = settings.chatWidth;
69 }
70 if (previous?.appearanceContrast !== settings.appearanceContrast) {
71 applyAppearanceContrast(root, settings.appearanceContrast);
72 }
73 if (previous?.glassOpacity !== settings.glassOpacity) {
74 root.style.setProperty("--glass-opacity", `${settings.glassOpacity}%`);
75 if (settings.glassOpacity === 100) {
76 root.style.setProperty("--glass-blur", "0px");
77 } else {
78 root.style.removeProperty("--glass-blur");
79 }
80 }
81 if (
82 previous?.fontFamilySans !== settings.fontFamilySans ||
83 previous.fontFamilyCode !== settings.fontFamilyCode ||
84 previous.fontFamilyComposer !== settings.fontFamilyComposer ||
85 previous.fontSizeInterface !== settings.fontSizeInterface ||
86 previous.fontSizePrompt !== settings.fontSizePrompt ||
87 previous.fontSizeCode !== settings.fontSizeCode ||
88 previous.fontSmoothing !== settings.fontSmoothing
89 ) {
90 applyAppearanceFontVariables(root, {
91 sans: settings.fontFamilySans,
92 code: settings.fontFamilyCode,
93 composer: settings.fontFamilyComposer,
94 sizeInterface: settings.fontSizeInterface,
95 sizePrompt: settings.fontSizePrompt,
96 sizeCode: settings.fontSizeCode,
97 smoothing: settings.fontSmoothing,
98 });
99 }
100 };
101 subscribeClientSettings(apply);
102 apply();
104​
105function startDocumentTitle(): void {
106 appAtomRegistry.subscribe(
107 primaryServerConfigAtom,
108 (config) => {
109 document.title = resolveServerBackedAppDisplayName({
110 baseName: APP_BASE_NAME,
111 fallbackDisplayName: APP_DISPLAY_NAME,
112 fallbackStageLabel: APP_STAGE_LABEL,
113 primaryServerVersion: config?.environment.serverVersion ?? null,
114 });
115 },
116 { immediate: true },
117 );
119​
120/**
121 * Each route paints its own surface, which the browser chrome samples once it is on screen.
122 * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
123 * can swap the root between the bare outlet and the shell at the same address.
124 */
125function startBrowserChromeThemeSync(router: AppRouter): void {
126 const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
127 router.subscribe("onRendered", resync);
128 router.subscribe("onResolved", resync);
130​
131/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
132function startThreadOverlayRetention(router: AppRouter): void {
133 router.subscribe("onResolved", () => {
134 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
135 const draftSession =
136 target?.kind === "draft"
137 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
138 : null;
139 const threadRef =
140 target?.kind === "server"
141 ? target.threadRef
142 : draftSession
143 ? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
144 : null;
145 retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
146 });
148​
149/**
150 * Starts every app-lifetime service once, before the first render, and returns the router.
151 * They run for the life of the page, so their disposers are dropped here.
152 */
153export function startAppServices(): AppRouter {
154 // Ahead of the history: the provider auth code must leave the address before anything reads it.
155 startProviderAuthDelivery();
156​
157 // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
158 const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());
159​
160 if (isElectron) {
161 syncDocumentElectronPlatformClasses(navigator.platform);
162 syncDocumentWindowControlsOverlayClass();
163 }
164​
165 installDesktopPasteAsText(window.desktopBridge, window);
166​
167 startClientAppearance();
168 startDocumentTitle();
169 startEnvironmentThemeRepaint();
170 startBrowserChromeThemeSync(router);
171 startDefaultThemeAdoption();
172 startModelPreferencesMigration();
173 startAgentOpenedPreviews();
174 if (isElectron) startElectronBrowserHost();
175 startPreviewTitleRecording();
176 startBrowserProfileReporting();
177 installChatRouteCommands(router);
178 installCommandPaletteCommands(router);
179 registerOpenFavoriteEditorCommand();
180 startThreadOverlayRetention(router);
181 // Drafts promote as their server threads arrive, wherever the user is.
182 subscribeDraftThreadPromotion({
183 registry: appAtomRegistry,
184 threadShellAtom: environmentThreadShells.quietThreadShellAtom,
185 threadRefsAtom: environmentThreadShells.threadRefsAtom,
186 });
187 subscribeComposerDraftModelReconciliation({
188 registry: appAtomRegistry,
189 threadShellAtom: environmentThreadShells.threadShellAtom,
190 threadRefsAtom: environmentThreadShells.threadRefsAtom,
191 shellStateAtom: environmentShell.stateAtom,
192 });
193 startMainAppLocationTracking(router);
194 startBackgroundThreadAnnouncements(appAtomRegistry, router);
195 startThreadVisitedMigration(appAtomRegistry);
196 startSshPasswordPromptQueue();
197​
198 startKeybindingsUpdateToasts();
199 startSlowRpcRequestToasts();
200 startHostFreezeToasts();
201 startLegacyThreadMigrationToast();
202 startPermissionUpdateNotices(router);
203 startThreadNotifications(appAtomRegistry, router);
204 startGuideRunNotifications(appAtomRegistry, router);
205 if (isElectron) startDesktopUpdateLaunchNotice();
206​
207 return router;