Open History to see the last commit
1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import { Navigate, useNavigate } from "@tanstack/react-router";
3import { useEffect, useState } from "react";
4
5import ChatView from "./ChatView";
6import { BackgroundThreadContext } from "./chat/backgroundThread";
7import { SidebarInset } from "./ui/sidebar";
8import { useComposerDraftStore } from "../composerDraftStore";
9import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
10import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities";
11import { useEnvironmentShellStatus } from "../state/shell";
12import { useEnvironmentThread } from "../state/threads";
13import {
14 buildThreadRouteParams,
15 isThreadRouteSnapshotAuthoritative,
16 resolveThreadRouteRenderState,
17 type ThreadRouteTarget,
18} from "../threadRoutes";
19
20/**
21 * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat`
22 * layout, since an element only survives a route swap when the same parent renders it. Draft
23 * promotion runs in the draft store; this only follows the redirect it leaves behind.
24 * `background` keeps the thread mounted, inert and in place under Settings or Usage.
25 */
26export function ThreadRouteView({
27 target,
28 background = false,
29}: {
30 target: ThreadRouteTarget;
31 background?: boolean;
32}) {
33 const navigate = useNavigate();
34 const draftId = target.kind === "draft" ? target.draftId : null;
35 const draftSession = useComposerDraftStore((store) =>
36 draftId === null ? null : store.getDraftSession(draftId),
37 );
38 const draftRedirect = useComposerDraftStore((store) =>
39 draftId === null ? null : store.getPromotedDraftRedirect(draftId),
40 );
41 const serverThreadRef = target.kind === "server" ? target.threadRef : null;
42 const serverThreadShell = useQuietThreadShell(serverThreadRef);
43 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
44 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
45 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
46 const draftThread = useComposerDraftStore((store) =>
47 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
48 );
49 // Reached from the sidebar before finalize, the thread still has its draft.
50 const serverThreadDraftId = useComposerDraftStore((store) =>
51 serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null,
52 );
53 // The ChatView that carried a draft keeps its key through the redirect to its thread, and only
54 // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView.
55 const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null);
56 const nextHandoffKey =
57 draftId !== null && draftSession === null && draftRedirect
58 ? handoffKey?.key === draftId
59 ? handoffKey
60 : { threadKey: scopedThreadKey(draftRedirect), key: draftId }
61 : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef)
62 ? handoffKey
63 : serverThreadRef && serverThreadDraftId
64 ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId }
65 : null;
66 if (nextHandoffKey !== handoffKey) {
67 setHandoffKey(nextHandoffKey);
68 }
69 const environmentHasDraftThreads = useComposerDraftStore((store) =>
70 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
71 );
72 // Until the shell lists the thread, its own load (HTTP, then the socket)
73 // decides whether it exists. Read only then: once listed, ChatView keeps
74 // this stream open and its updates need not re-render the route.
75 const unlistedThreadRef =
76 target.kind === "server" && serverThreadShell === null && draftThread === null
77 ? target.threadRef
78 : null;
79 const unlistedThreadDetail = useEnvironmentThread(
80 unlistedThreadRef?.environmentId ?? null,
81 unlistedThreadRef?.threadId ?? null,
82 );
83 const renderState = resolveThreadRouteRenderState({
84 bootstrapComplete,
85 serverThreadExists: serverThreadShell !== null,
86 serverThreadDeleted: serverThreadShell?.deletedAt != null,
87 unlistedThreadDetail,
88 draftThreadExists: draftThread !== null,
89 });
90 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
91
92 useEffect(() => {
93 if (target.kind !== "server" || !bootstrapComplete) {
94 return;
95 }
96 if (renderState === "missing") {
97 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
98 clearPendingFileDropsForThread(target.threadRef);
99 if (environmentHasAnyThreads && !background) {
100 void navigate({ to: "/", replace: true });
101 }
102 }
103 }, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
104
105 let view: React.ReactNode = null;
106 let redirect: React.ReactNode = null;
107 if (target.kind === "draft") {
108 if (draftSession) {
109 view = (
110 <ChatView
111 key={target.draftId}
112 draftId={target.draftId}
113 environmentId={draftSession.environmentId}
114 threadId={draftSession.threadId}
115 routeKind="draft"
116 forceExpandedMobileComposer
117 />
118 );
119 } else if (draftRedirect) {
120 // Same slot and key as the server route renders, so the swap keeps this instance.
121 view = (
122 <ChatView
123 key={target.draftId}
124 environmentId={draftRedirect.environmentId}
125 threadId={draftRedirect.threadId}
126 routeKind="server"
127 />
128 );
129 redirect = (
130 <Navigate
131 to="/$environmentId/$threadId"
132 params={buildThreadRouteParams(draftRedirect)}
133 replace
134 />
135 );
136 } else {
137 redirect = <Navigate to="/" replace />;
138 }
139 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
140 view = (
141 <ChatView
142 key={nextHandoffKey?.key}
143 environmentId={target.threadRef.environmentId}
144 threadId={target.threadRef.threadId}
145 routeKind="server"
146 />
147 );
148 }
149
150 return (
151 <SidebarInset
152 className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh"
153 inert={background}
154 >
155 <BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>
156 {background ? null : redirect}
157 </SidebarInset>
158 );
159}