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

__root.tsx

327 lines11.0 KB

1import { ThreadId } from "@t3tools/contracts";
2import {
3 Outlet,
4 createRootRouteWithContext,
5 type ErrorComponentProps,
6 useNavigate,
7 useRouterState,
8} from "@tanstack/react-router";
9import { useEffect, useRef } from "react";
10import { QueryClient, useQueryClient } from "@tanstack/react-query";
11import { Throttler } from "@tanstack/react-pacer";
12​
13import { APP_DISPLAY_NAME } from "../branding";
14import { Button } from "../components/ui/button";
15import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
16import { resolveAndPersistPreferredEditor } from "../editorPreferences";
17import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
18import { readNativeApi } from "../nativeApi";
19import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore";
20import { useStore } from "../store";
21import { useTerminalStateStore } from "../terminalStateStore";
22import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
23import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
24import { providerQueryKeys } from "../lib/providerReactQuery";
25import { projectQueryKeys } from "../lib/projectReactQuery";
26import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
27​
28export const Route = createRootRouteWithContext<{
29 queryClient: QueryClient;
30}>()({
31 component: RootRouteView,
32 errorComponent: RootRouteErrorView,
33 head: () => ({
34 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
35 }),
36});
37​
38function RootRouteView() {
39 if (!readNativeApi()) {
40 return (
41 <div className="flex h-screen flex-col bg-background text-foreground">
42 <div className="flex flex-1 items-center justify-center">
43 <p className="text-sm text-muted-foreground">
44 Connecting to {APP_DISPLAY_NAME} server...
45 </p>
46 </div>
47 </div>
48 );
49 }
50​
51 return (
52 <ToastProvider>
53 <AnchoredToastProvider>
54 <EventRouter />
55 <DesktopProjectBootstrap />
56 <Outlet />
57 </AnchoredToastProvider>
58 </ToastProvider>
59 );
61​
62function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
63 const message = errorMessage(error);
64 const details = errorDetails(error);
65​
66 return (
67 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
68 <div className="pointer-events-none absolute inset-0 opacity-80">
69 <div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />
70 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
71 </div>
72​
73 <section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
74 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
75 {APP_DISPLAY_NAME}
76 </p>
77 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
78 Something went wrong.
79 </h1>
80 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
81​
82 <div className="mt-5 flex flex-wrap gap-2">
83 <Button size="sm" onClick={() => reset()}>
84 Try again
85 </Button>
86 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
87 Reload app
88 </Button>
89 </div>
90​
91 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
92 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
93 <span className="group-open:hidden">Show error details</span>
94 <span className="hidden group-open:inline">Hide error details</span>
95 </summary>
96 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
97 {details}
98 </pre>
99 </details>
100 </section>
101 </div>
102 );
104​
105function errorMessage(error: unknown): string {
106 if (error instanceof Error && error.message.trim().length > 0) {
107 return error.message;
108 }
109​
110 if (typeof error === "string" && error.trim().length > 0) {
111 return error;
112 }
113​
114 return "An unexpected router error occurred.";
116​
117function errorDetails(error: unknown): string {
118 if (error instanceof Error) {
119 return error.stack ?? error.message;
120 }
121​
122 if (typeof error === "string") {
123 return error;
124 }
125​
126 try {
127 return JSON.stringify(error, null, 2);
128 } catch {
129 return "No additional error details are available.";
130 }
132​
133function EventRouter() {
134 const syncServerReadModel = useStore((store) => store.syncServerReadModel);
135 const setProjectExpanded = useStore((store) => store.setProjectExpanded);
136 const removeOrphanedTerminalStates = useTerminalStateStore(
137 (store) => store.removeOrphanedTerminalStates,
138 );
139 const queryClient = useQueryClient();
140 const navigate = useNavigate();
141 const pathname = useRouterState({ select: (state) => state.location.pathname });
142 const pathnameRef = useRef(pathname);
143 const handledBootstrapThreadIdRef = useRef<string | null>(null);
144​
145 pathnameRef.current = pathname;
146​
147 useEffect(() => {
148 const api = readNativeApi();
149 if (!api) return;
150 let disposed = false;
151 let latestSequence = 0;
152 let syncing = false;
153 let pending = false;
154 let needsProviderInvalidation = false;
155​
156 const flushSnapshotSync = async (): Promise<void> => {
157 const snapshot = await api.orchestration.getSnapshot();
158 if (disposed) return;
159 latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
160 syncServerReadModel(snapshot);
161 clearPromotedDraftThreads(new Set(snapshot.threads.map((t) => t.id)));
162 const draftThreadIds = Object.keys(
163 useComposerDraftStore.getState().draftThreadsByThreadId,
164 ) as ThreadId[];
165 const activeThreadIds = collectActiveTerminalThreadIds({
166 snapshotThreads: snapshot.threads,
167 draftThreadIds,
168 });
169 removeOrphanedTerminalStates(activeThreadIds);
170 if (pending) {
171 pending = false;
172 await flushSnapshotSync();
173 }
174 };
175​
176 const syncSnapshot = async () => {
177 if (syncing) {
178 pending = true;
179 return;
180 }
181 syncing = true;
182 pending = false;
183 try {
184 await flushSnapshotSync();
185 } catch {
186 // Keep prior state and wait for next domain event to trigger a resync.
187 }
188 syncing = false;
189 };
190​
191 const domainEventFlushThrottler = new Throttler(
192 () => {
193 if (needsProviderInvalidation) {
194 needsProviderInvalidation = false;
195 void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
196 // Invalidate workspace entry queries so the @-mention file picker
197 // reflects files created, deleted, or restored during this turn.
198 void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
199 }
200 void syncSnapshot();
201 },
202 {
203 wait: 100,
204 leading: false,
205 trailing: true,
206 },
207 );
208​
209 const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
210 if (event.sequence <= latestSequence) {
211 return;
212 }
213 latestSequence = event.sequence;
214 if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
215 needsProviderInvalidation = true;
216 }
217 domainEventFlushThrottler.maybeExecute();
218 });
219 const unsubTerminalEvent = api.terminal.onEvent((event) => {
220 const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
221 if (hasRunningSubprocess === null) {
222 return;
223 }
224 useTerminalStateStore
225 .getState()
226 .setTerminalActivity(
227 ThreadId.makeUnsafe(event.threadId),
228 event.terminalId,
229 hasRunningSubprocess,
230 );
231 });
232 const unsubWelcome = onServerWelcome((payload) => {
233 void (async () => {
234 await syncSnapshot();
235 if (disposed) {
236 return;
237 }
238​
239 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
240 return;
241 }
242 setProjectExpanded(payload.bootstrapProjectId, true);
243​
244 if (pathnameRef.current !== "/") {
245 return;
246 }
247 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
248 return;
249 }
250 await navigate({
251 to: "/$threadId",
252 params: { threadId: payload.bootstrapThreadId },
253 replace: true,
254 });
255 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
256 })().catch(() => undefined);
257 });
258 // onServerConfigUpdated replays the latest cached value synchronously
259 // during subscribe. Skip the toast for that replay so effect re-runs
260 // don't produce duplicate toasts.
261 let subscribed = false;
262 const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
263 void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
264 if (!subscribed) return;
265 const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
266 if (!issue) {
267 toastManager.add({
268 type: "success",
269 title: "Keybindings updated",
270 description: "Keybindings configuration reloaded successfully.",
271 });
272 return;
273 }
274​
275 toastManager.add({
276 type: "warning",
277 title: "Invalid keybindings configuration",
278 description: issue.message,
279 actionProps: {
280 children: "Open keybindings.json",
281 onClick: () => {
282 void queryClient
283 .ensureQueryData(serverConfigQueryOptions())
284 .then((config) => {
285 const editor = resolveAndPersistPreferredEditor(config.availableEditors);
286 if (!editor) {
287 throw new Error("No available editors found.");
288 }
289 return api.shell.openInEditor(config.keybindingsConfigPath, editor);
290 })
291 .catch((error) => {
292 toastManager.add({
293 type: "error",
294 title: "Unable to open keybindings file",
295 description:
296 error instanceof Error ? error.message : "Unknown error opening file.",
297 });
298 });
299 },
300 },
301 });
302 });
303 subscribed = true;
304 return () => {
305 disposed = true;
306 needsProviderInvalidation = false;
307 domainEventFlushThrottler.cancel();
308 unsubDomainEvent();
309 unsubTerminalEvent();
310 unsubWelcome();
311 unsubServerConfigUpdated();
312 };
313 }, [
314 navigate,
315 queryClient,
316 removeOrphanedTerminalStates,
317 setProjectExpanded,
318 syncServerReadModel,
319 ]);
320​
321 return null;
323​
324function DesktopProjectBootstrap() {
325 // Desktop hydration runs through EventRouter project + orchestration sync.
326 return null;