Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
4import { visibilityParentKey } from "@t3tools/client-runtime/state/threads";
5import type { ScopedThreadRef } from "@t3tools/contracts";
6import * as Option from "effect/Option";
7import { Navigate, useNavigate } from "@tanstack/react-router";
8import { useEffect, useState } from "react";
9
10import ChatView from "./ChatView";
11import { BackgroundThreadContext } from "./chat/backgroundThread";
12import { SidebarInset } from "./ui/sidebar";
13import { useComposerDraftStore } from "../composerDraftStore";
14import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
15import {
16 useEnvironmentThreadRefs,
17 useAnyEnvironmentHiding,
18 useQuietThreadShell,
19} from "../state/entities";
20import { appAtomRegistry } from "../rpc/atomRegistry";
21import { useEnvironmentShellStatus } from "../state/shell";
22import { environmentThreadShells, threadFamilies, useEnvironmentThread } from "../state/threads";
23import {
24 buildThreadRouteParams,
25 isThreadRouteSnapshotAuthoritative,
26 resolveThreadRouteRenderState,
27 type ThreadRouteTarget,
28} from "../threadRoutes";
29
30/**
31 * Keeps the family of an open thread the shell leaves out (an older settled thread) in the shell
32 * rows until the route leaves it, so every reader of its shell row finds it.
33 */
34function useOpenThreadFamily(threadRef: ScopedThreadRef | null, missing: boolean) {
35 const key = threadRef === null ? null : scopedThreadKey(threadRef);
36 // Sticks to the route thread, so the row the family brings in does not release it.
37 const [mountedKey, setMountedKey] = useState<string | null>(null);
38 const nextKey = missing || mountedKey === key ? key : null;
39 if (nextKey !== mountedKey) setMountedKey(nextKey);
40 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- holds the open thread's family in the thread family registry until the route leaves it
41 useEffect(() => {
42 const ref = mountedKey === null ? null : parseScopedThreadKey(mountedKey);
43 if (ref === null) return;
44 return threadFamilies.mount(appAtomRegistry, ref.environmentId, ref.threadId);
45 }, [mountedKey]);
46}
47
48/**
49 * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat`
50 * layout, since an element only survives a route swap when the same parent renders it. Draft
51 * promotion runs in the draft store; this only follows the redirect it leaves behind.
52 * `background` keeps the thread mounted, inert and in place under Settings or Usage.
53 */
54export function ThreadRouteView({
55 target,
56 background = false,
57}: {
58 target: ThreadRouteTarget;
59 background?: boolean;
60}) {
61 const navigate = useNavigate();
62 const draftId = target.kind === "draft" ? target.draftId : null;
63 const draftSession = useComposerDraftStore((store) =>
64 draftId === null ? null : store.getDraftSession(draftId),
65 );
66 const draftRedirect = useComposerDraftStore((store) =>
67 draftId === null ? null : store.getPromotedDraftRedirect(draftId),
68 );
69 const serverThreadRef = target.kind === "server" ? target.threadRef : null;
70 const serverThreadShell = useQuietThreadShell(serverThreadRef);
71 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
72 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
73 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
74 const draftThread = useComposerDraftStore((store) =>
75 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
76 );
77 // Reached from the sidebar before finalize, the thread still has its draft.
78 const serverThreadDraftId = useComposerDraftStore((store) =>
79 serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null,
80 );
81 // The ChatView that carried a draft keeps its key through the redirect to its thread, and only
82 // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView.
83 const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null);
84 const nextHandoffKey =
85 draftId !== null && draftSession === null && draftRedirect
86 ? handoffKey?.key === draftId
87 ? handoffKey
88 : { threadKey: scopedThreadKey(draftRedirect), key: draftId }
89 : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef)
90 ? handoffKey
91 : serverThreadRef && serverThreadDraftId
92 ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId }
93 : null;
94 if (nextHandoffKey !== handoffKey) {
95 setHandoffKey(nextHandoffKey);
96 }
97 const environmentHasDraftThreads = useComposerDraftStore((store) =>
98 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
99 );
100 // Until the shell lists the thread, its own load (HTTP, then the socket)
101 // decides whether it exists. Read only then: once listed, ChatView keeps
102 // this stream open and its updates need not re-render the route.
103 const unlistedThreadRef =
104 target.kind === "server" && serverThreadShell === null && draftThread === null
105 ? target.threadRef
106 : null;
107 const unlistedThreadDetail = useEnvironmentThread(
108 unlistedThreadRef?.environmentId ?? null,
109 unlistedThreadRef?.threadId ?? null,
110 );
111 useOpenThreadFamily(serverThreadRef, bootstrapComplete && unlistedThreadRef !== null);
112 const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
113 const unlistedThread = Option.getOrNull(Option.map(unlistedThreadDetail.data, (p) => p.thread));
114 const unlistedParentKey =
115 unlistedThreadRef === null || unlistedThread === null
116 ? null
117 : visibilityParentKey(unlistedThreadRef.environmentId, unlistedThread);
118 const unlistedParentShell = useQuietThreadShell(
119 unlistedParentKey === null ? null : parseThreadKey(unlistedParentKey),
120 );
121 const hidingAnywhere = useAnyEnvironmentHiding();
122 const draftRedirectShell = useQuietThreadShell(draftRedirect ?? null);
123 const hiddenByTagFilter = serverThreadRef !== null && hiddenKeys.has(threadKey(serverThreadRef));
124 // Cached detail can predate a tag or an archive, so while hiding an off-shell thread opens only
125 // as the child of a loaded, visible parent (lineage never changes); anything else stays closed.
126 const offShellBlocked =
127 hidingAnywhere &&
128 unlistedThreadRef !== null &&
129 !(
130 unlistedParentKey !== null &&
131 unlistedParentShell !== null &&
132 !hiddenKeys.has(unlistedParentKey)
133 );
134 const renderState = resolveThreadRouteRenderState({
135 bootstrapComplete,
136 serverThreadExists: serverThreadShell !== null,
137 serverThreadDeleted: serverThreadShell?.deletedAt != null,
138 unlistedThreadDetail,
139 draftThreadExists: draftThread !== null,
140 });
141 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
142
143 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears pending file drops and navigates the router home once a server thread is confirmed missing
144 useEffect(() => {
145 if (target.kind !== "server" || !bootstrapComplete) {
146 return;
147 }
148 if (renderState === "missing") {
149 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
150 clearPendingFileDropsForThread(target.threadRef);
151 if (environmentHasAnyThreads && !background) {
152 void navigate({ to: "/", replace: true });
153 }
154 }
155 }, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
156
157 let view: React.ReactNode = null;
158 let redirect: React.ReactNode = null;
159 if (target.kind === "draft") {
160 if (
161 draftSession &&
162 hiddenKeys.has(
163 threadKey({ environmentId: draftSession.environmentId, threadId: draftSession.threadId }),
164 )
165 ) {
166 // A draft whose thread is already live and hidden (mid-promotion): never mount it.
167 redirect = <Navigate to="/" replace />;
168 } else if (draftSession) {
169 view = (
170 <ChatView
171 key={target.draftId}
172 draftId={target.draftId}
173 environmentId={draftSession.environmentId}
174 threadId={draftSession.threadId}
175 routeKind="draft"
176 forceExpandedMobileComposer
177 />
178 );
179 } else if (draftRedirect && hiddenKeys.has(threadKey(draftRedirect))) {
180 // Back to a promoted draft whose thread is now hidden: never mount it.
181 redirect = <Navigate to="/" replace />;
182 } else if (draftRedirect && hidingAnywhere && draftRedirectShell === null) {
183 // While hiding, a thread outside the live list is judged by the server route, unmounted here.
184 redirect = (
185 <Navigate
186 to="/$environmentId/$threadId"
187 params={buildThreadRouteParams(draftRedirect)}
188 replace
189 />
190 );
191 } else if (draftRedirect) {
192 // Same slot and key as the server route renders, so the swap keeps this instance.
193 view = (
194 <ChatView
195 key={target.draftId}
196 environmentId={draftRedirect.environmentId}
197 threadId={draftRedirect.threadId}
198 routeKind="server"
199 />
200 );
201 redirect = (
202 <Navigate
203 to="/$environmentId/$threadId"
204 params={buildThreadRouteParams(draftRedirect)}
205 replace
206 />
207 );
208 } else {
209 redirect = <Navigate to="/" replace />;
210 }
211 } else if (hiddenByTagFilter) {
212 redirect = <Navigate to="/" replace />;
213 } else if (offShellBlocked) {
214 // Before the shell bootstraps, a listed visible thread can still look off-shell.
215 if (bootstrapComplete && unlistedThread !== null) redirect = <Navigate to="/" replace />;
216 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
217 view = (
218 <ChatView
219 key={nextHandoffKey?.key}
220 environmentId={target.threadRef.environmentId}
221 threadId={target.threadRef.threadId}
222 routeKind="server"
223 />
224 );
225 }
226
227 return (
228 <SidebarInset
229 className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh"
230 inert={background}
231 >
232 <BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>
233 {background ? null : redirect}
234 </SidebarInset>
235 );
236}