Open History to see the last commit
1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3import { useNavigate } from "@tanstack/react-router";
4import { useEffect, useState } from "react";
5
6import ChatView from "./ChatView";
7import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";
8import { waitForDraftHeroTransition } from "./chat/draftHeroTransition";
9import { SidebarInset } from "./ui/sidebar";
10import {
11 finalizePromotedDraftThreadByRef,
12 markPromotedDraftThreadByRef,
13 useBackgroundDraftSubmissionPending,
14 useComposerDraftStore,
15} from "../composerDraftStore";
16import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
17import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
18import { useEnvironmentShellStatus } from "../state/shell";
19import {
20 buildThreadRouteParams,
21 isThreadRouteSnapshotAuthoritative,
22 resolveThreadRouteRenderState,
23 type ThreadRouteTarget,
24} from "../threadRoutes";
25
26/**
27 * Plain server threads are unkeyed, so navigating between them reuses one instance as ChatView
28 * expects. Rendered by the `_chat` layout rather than by the two leaf routes, since an element
29 * only survives a route swap when the same parent renders it.
30 */
31export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
32 const navigate = useNavigate();
33 const draftId = target.kind === "draft" ? target.draftId : null;
34 const draftSession = useComposerDraftStore((store) =>
35 draftId === null ? null : store.getDraftSession(draftId),
36 );
37 const threadRefs = useThreadRefs();
38 const inferredThreadRef = draftSession
39 ? (threadRefs.find(
40 (ref) =>
41 ref.environmentId === draftSession.environmentId &&
42 ref.threadId === draftSession.threadId,
43 ) ?? null)
44 : null;
45 const serverThreadRef: ScopedThreadRef | null =
46 target.kind === "server" ? target.threadRef : (draftSession?.promotedTo ?? inferredThreadRef);
47 const serverThread = useQuietThreadShell(serverThreadRef);
48 const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
49 target.kind === "draft" ? serverThreadRef : null,
50 );
51 const canonicalThreadRef =
52 target.kind === "draft"
53 ? resolveDraftPromotionNavigationTarget({
54 serverThreadRef,
55 serverThread,
56 backgroundSubmissionPending,
57 })
58 : null;
59
60 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
61 const serverThreadShell = serverThread;
62 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
63 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
64 const draftThread = useComposerDraftStore((store) =>
65 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
66 );
67 const promotedDraftId = useComposerDraftStore((store) =>
68 target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
69 );
70 // The draft record is removed once the promoted thread has started, which
71 // is after the route swap. Latch the key so the element that carried the
72 // draft keeps its identity for as long as this thread stays on screen.
73 const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);
74 const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;
75 const nextChatViewKey =
76 serverThreadKey === null
77 ? null
78 : chatViewKey?.threadKey === serverThreadKey
79 ? chatViewKey
80 : promotedDraftId
81 ? { threadKey: serverThreadKey, key: promotedDraftId }
82 : null;
83 if (nextChatViewKey !== chatViewKey) {
84 setChatViewKey(nextChatViewKey);
85 }
86 const environmentHasDraftThreads = useComposerDraftStore((store) =>
87 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
88 );
89 const renderState = resolveThreadRouteRenderState({
90 bootstrapComplete,
91 serverThreadExists: serverThreadShell !== null,
92 serverThreadDeleted: serverThreadShell?.deletedAt != null,
93 draftThreadExists: draftThread !== null,
94 });
95 const serverThreadStarted = threadHasStarted(serverThreadShell);
96 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
97
98 useEffect(() => {
99 if (!inferredThreadRef || draftSession?.promotedTo) {
100 return;
101 }
102 markPromotedDraftThreadByRef(inferredThreadRef);
103 }, [draftSession?.promotedTo, inferredThreadRef]);
104
105 useEffect(() => {
106 if (!canonicalThreadRef) {
107 return;
108 }
109 let cancelled = false;
110 void waitForDraftHeroTransition().then(() => {
111 if (cancelled) {
112 return;
113 }
114 void navigate({
115 to: "/$environmentId/$threadId",
116 params: buildThreadRouteParams(canonicalThreadRef),
117 replace: true,
118 });
119 });
120 return () => {
121 cancelled = true;
122 };
123 }, [canonicalThreadRef, navigate]);
124
125 useEffect(() => {
126 if (target.kind !== "draft" || draftSession || canonicalThreadRef) {
127 return;
128 }
129 void navigate({ to: "/", replace: true });
130 }, [canonicalThreadRef, draftSession, navigate, target.kind]);
131
132 useEffect(() => {
133 if (target.kind !== "server" || !bootstrapComplete) {
134 return;
135 }
136 if (renderState === "missing") {
137 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
138 clearPendingFileDropsForThread(target.threadRef);
139 if (environmentHasAnyThreads) {
140 void navigate({ to: "/", replace: true });
141 }
142 }
143 }, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
144
145 useEffect(() => {
146 if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
147 return;
148 }
149 finalizePromotedDraftThreadByRef(target.threadRef);
150 }, [draftThread, serverThreadStarted, target]);
151
152 let view: React.ReactNode = null;
153 if (target.kind === "draft") {
154 if (draftSession) {
155 view = (
156 <ChatView
157 key={target.draftId}
158 draftId={target.draftId}
159 environmentId={draftSession.environmentId}
160 threadId={draftSession.threadId}
161 routeKind="draft"
162 forceExpandedMobileComposer
163 />
164 );
165 }
166 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
167 view = (
168 <ChatView
169 key={nextChatViewKey?.key}
170 environmentId={target.threadRef.environmentId}
171 threadId={target.threadRef.threadId}
172 routeKind="server"
173 />
174 );
175 }
176
177 return (
178 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh">
179 {view}
180 </SidebarInset>
181 );
182}