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

appInit.tsx

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