Open History to see the last commit
1import { OrchestrationEvent, 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 { AppSidebarLayout } from "../components/AppSidebarLayout";
15import { Button } from "../components/ui/button";
16import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
17import { resolveAndPersistPreferredEditor } from "../editorPreferences";
18import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
19import { readNativeApi } from "../nativeApi";
20import {
21 clearPromotedDraftThread,
22 clearPromotedDraftThreads,
23 useComposerDraftStore,
24} from "../composerDraftStore";
25import { useStore } from "../store";
26import { useUiStateStore } from "../uiStateStore";
27import { useTerminalStateStore } from "../terminalStateStore";
28import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
29import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
30import { migrateLocalSettingsToServer } from "../hooks/useSettings";
31import { providerQueryKeys } from "../lib/providerReactQuery";
32import { projectQueryKeys } from "../lib/projectReactQuery";
33import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
34import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
35import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
36
37export const Route = createRootRouteWithContext<{
38 queryClient: QueryClient;
39}>()({
40 component: RootRouteView,
41 errorComponent: RootRouteErrorView,
42 head: () => ({
43 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
44 }),
45});
46
47function RootRouteView() {
48 if (!readNativeApi()) {
49 return (
50 <div className="flex h-screen flex-col bg-background text-foreground">
51 <div className="flex flex-1 items-center justify-center">
52 <p className="text-sm text-muted-foreground">
53 Connecting to {APP_DISPLAY_NAME} server...
54 </p>
55 </div>
56 </div>
57 );
58 }
59
60 return (
61 <ToastProvider>
62 <AnchoredToastProvider>
63 <EventRouter />
64 <DesktopProjectBootstrap />
65 <AppSidebarLayout>
66 <Outlet />
67 </AppSidebarLayout>
68 </AnchoredToastProvider>
69 </ToastProvider>
70 );
71}
72
73function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
74 const message = errorMessage(error);
75 const details = errorDetails(error);
76
77 return (
78 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
79 <div className="pointer-events-none absolute inset-0 opacity-80">
80 <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)]" />
81 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
82 </div>
83
84 <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">
85 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
86 {APP_DISPLAY_NAME}
87 </p>
88 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
89 Something went wrong.
90 </h1>
91 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
92
93 <div className="mt-5 flex flex-wrap gap-2">
94 <Button size="sm" onClick={() => reset()}>
95 Try again
96 </Button>
97 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
98 Reload app
99 </Button>
100 </div>
101
102 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
103 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
104 <span className="group-open:hidden">Show error details</span>
105 <span className="hidden group-open:inline">Hide error details</span>
106 </summary>
107 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
108 {details}
109 </pre>
110 </details>
111 </section>
112 </div>
113 );
114}
115
116function errorMessage(error: unknown): string {
117 if (error instanceof Error && error.message.trim().length > 0) {
118 return error.message;
119 }
120
121 if (typeof error === "string" && error.trim().length > 0) {
122 return error;
123 }
124
125 return "An unexpected router error occurred.";
126}
127
128function errorDetails(error: unknown): string {
129 if (error instanceof Error) {
130 return error.stack ?? error.message;
131 }
132
133 if (typeof error === "string") {
134 return error;
135 }
136
137 try {
138 return JSON.stringify(error, null, 2);
139 } catch {
140 return "No additional error details are available.";
141 }
142}
143
144function EventRouter() {
145 const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
146 const syncServerReadModel = useStore((store) => store.syncServerReadModel);
147 const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
148 const syncProjects = useUiStateStore((store) => store.syncProjects);
149 const syncThreads = useUiStateStore((store) => store.syncThreads);
150 const clearThreadUi = useUiStateStore((store) => store.clearThreadUi);
151 const removeTerminalState = useTerminalStateStore((store) => store.removeTerminalState);
152 const removeOrphanedTerminalStates = useTerminalStateStore(
153 (store) => store.removeOrphanedTerminalStates,
154 );
155 const queryClient = useQueryClient();
156 const navigate = useNavigate();
157 const pathname = useRouterState({ select: (state) => state.location.pathname });
158 const pathnameRef = useRef(pathname);
159 const handledBootstrapThreadIdRef = useRef<string | null>(null);
160
161 pathnameRef.current = pathname;
162
163 useEffect(() => {
164 const api = readNativeApi();
165 if (!api) return;
166 let disposed = false;
167 const recovery = createOrchestrationRecoveryCoordinator();
168 let needsProviderInvalidation = false;
169
170 const reconcileSnapshotDerivedState = () => {
171 const threads = useStore.getState().threads;
172 const projects = useStore.getState().projects;
173 syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
174 syncThreads(
175 threads.map((thread) => ({
176 id: thread.id,
177 seedVisitedAt: thread.updatedAt ?? thread.createdAt,
178 })),
179 );
180 clearPromotedDraftThreads(threads.map((thread) => thread.id));
181 const draftThreadIds = Object.keys(
182 useComposerDraftStore.getState().draftThreadsByThreadId,
183 ) as ThreadId[];
184 const activeThreadIds = collectActiveTerminalThreadIds({
185 snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })),
186 draftThreadIds,
187 });
188 removeOrphanedTerminalStates(activeThreadIds);
189 };
190
191 const queryInvalidationThrottler = new Throttler(
192 () => {
193 if (!needsProviderInvalidation) {
194 return;
195 }
196 needsProviderInvalidation = false;
197 void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
198 // Invalidate workspace entry queries so the @-mention file picker
199 // reflects files created, deleted, or restored during this turn.
200 void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
201 },
202 {
203 wait: 100,
204 leading: false,
205 trailing: true,
206 },
207 );
208
209 const applyEventBatch = (events: ReadonlyArray<OrchestrationEvent>) => {
210 const nextEvents = recovery.markEventBatchApplied(events);
211 if (nextEvents.length === 0) {
212 return;
213 }
214
215 const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
216 const needsProjectUiSync = nextEvents.some(
217 (event) =>
218 event.type === "project.created" ||
219 event.type === "project.meta-updated" ||
220 event.type === "project.deleted",
221 );
222
223 if (batchEffects.needsProviderInvalidation) {
224 needsProviderInvalidation = true;
225 void queryInvalidationThrottler.maybeExecute();
226 }
227
228 applyOrchestrationEvents(nextEvents);
229 if (needsProjectUiSync) {
230 const projects = useStore.getState().projects;
231 syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
232 }
233 const needsThreadUiSync = nextEvents.some(
234 (event) => event.type === "thread.created" || event.type === "thread.deleted",
235 );
236 if (needsThreadUiSync) {
237 const threads = useStore.getState().threads;
238 syncThreads(
239 threads.map((thread) => ({
240 id: thread.id,
241 seedVisitedAt: thread.updatedAt ?? thread.createdAt,
242 })),
243 );
244 }
245 const draftStore = useComposerDraftStore.getState();
246 for (const threadId of batchEffects.clearPromotedDraftThreadIds) {
247 clearPromotedDraftThread(threadId);
248 }
249 for (const threadId of batchEffects.clearDeletedThreadIds) {
250 draftStore.clearDraftThread(threadId);
251 clearThreadUi(threadId);
252 }
253 for (const threadId of batchEffects.removeTerminalStateThreadIds) {
254 removeTerminalState(threadId);
255 }
256 };
257
258 const recoverFromSequenceGap = async (): Promise<void> => {
259 if (!recovery.beginReplayRecovery("sequence-gap")) {
260 return;
261 }
262
263 try {
264 const events = await api.orchestration.replayEvents(recovery.getState().latestSequence);
265 if (!disposed) {
266 applyEventBatch(events);
267 }
268 } catch {
269 recovery.failReplayRecovery();
270 void fallbackToSnapshotRecovery();
271 return;
272 }
273
274 if (!disposed && recovery.completeReplayRecovery()) {
275 void recoverFromSequenceGap();
276 }
277 };
278
279 const runSnapshotRecovery = async (reason: "bootstrap" | "replay-failed"): Promise<void> => {
280 if (!recovery.beginSnapshotRecovery(reason)) {
281 return;
282 }
283
284 try {
285 const snapshot = await api.orchestration.getSnapshot();
286 if (!disposed) {
287 syncServerReadModel(snapshot);
288 reconcileSnapshotDerivedState();
289 if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
290 void recoverFromSequenceGap();
291 }
292 }
293 } catch {
294 // Keep prior state and wait for welcome or a later replay attempt.
295 recovery.failSnapshotRecovery();
296 }
297 };
298
299 const bootstrapFromSnapshot = async (): Promise<void> => {
300 await runSnapshotRecovery("bootstrap");
301 };
302
303 const fallbackToSnapshotRecovery = async (): Promise<void> => {
304 await runSnapshotRecovery("replay-failed");
305 };
306
307 const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
308 const action = recovery.classifyDomainEvent(event.sequence);
309 if (action === "apply") {
310 applyEventBatch([event]);
311 return;
312 }
313 if (action === "recover") {
314 void recoverFromSequenceGap();
315 }
316 });
317 const unsubTerminalEvent = api.terminal.onEvent((event) => {
318 const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
319 if (hasRunningSubprocess === null) {
320 return;
321 }
322 useTerminalStateStore
323 .getState()
324 .setTerminalActivity(
325 ThreadId.makeUnsafe(event.threadId),
326 event.terminalId,
327 hasRunningSubprocess,
328 );
329 });
330 const unsubWelcome = onServerWelcome((payload) => {
331 // Migrate old localStorage settings to server on first connect
332 migrateLocalSettingsToServer();
333 void (async () => {
334 await bootstrapFromSnapshot();
335 if (disposed) {
336 return;
337 }
338
339 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
340 return;
341 }
342 setProjectExpanded(payload.bootstrapProjectId, true);
343
344 if (pathnameRef.current !== "/") {
345 return;
346 }
347 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
348 return;
349 }
350 await navigate({
351 to: "/$threadId",
352 params: { threadId: payload.bootstrapThreadId },
353 replace: true,
354 });
355 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
356 })().catch(() => undefined);
357 });
358 // onServerConfigUpdated replays the latest cached value synchronously
359 // during subscribe. Skip the toast for that replay so effect re-runs
360 // don't produce duplicate toasts.
361 let subscribed = false;
362 const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
363 // Invalidate the config query so active observers refetch fresh data.
364 void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
365
366 if (!subscribed) return;
367
368 // Only show keybindings toasts for keybindings changes (no settings in payload)
369 if (payload.settings) return;
370
371 const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
372 if (!issue) {
373 toastManager.add({
374 type: "success",
375 title: "Keybindings updated",
376 description: "Keybindings configuration reloaded successfully.",
377 });
378 return;
379 }
380
381 toastManager.add({
382 type: "warning",
383 title: "Invalid keybindings configuration",
384 description: issue.message,
385 actionProps: {
386 children: "Open keybindings.json",
387 onClick: () => {
388 void queryClient
389 .ensureQueryData(serverConfigQueryOptions())
390 .then((config) => {
391 const editor = resolveAndPersistPreferredEditor(config.availableEditors);
392 if (!editor) {
393 throw new Error("No available editors found.");
394 }
395 return api.shell.openInEditor(config.keybindingsConfigPath, editor);
396 })
397 .catch((error) => {
398 toastManager.add({
399 type: "error",
400 title: "Unable to open keybindings file",
401 description:
402 error instanceof Error ? error.message : "Unknown error opening file.",
403 });
404 });
405 },
406 },
407 });
408 });
409 const unsubProvidersUpdated = onServerProvidersUpdated(() => {
410 void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
411 });
412 subscribed = true;
413 return () => {
414 disposed = true;
415 needsProviderInvalidation = false;
416 queryInvalidationThrottler.cancel();
417 unsubDomainEvent();
418 unsubTerminalEvent();
419 unsubWelcome();
420 unsubServerConfigUpdated();
421 unsubProvidersUpdated();
422 };
423 }, [
424 applyOrchestrationEvents,
425 navigate,
426 queryClient,
427 removeTerminalState,
428 removeOrphanedTerminalStates,
429 clearThreadUi,
430 setProjectExpanded,
431 syncProjects,
432 syncServerReadModel,
433 syncThreads,
434 ]);
435
436 return null;
437}
438
439function DesktopProjectBootstrap() {
440 // Desktop hydration runs through EventRouter project + orchestration sync.
441 return null;
442}