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