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

appInit.tsx

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