Open History to see the last commit
1import { createFileRoute, useNavigate } from "@tanstack/react-router";
2import { useEffect } from "react";
3import ChatView from "../components/ChatView";
4import { threadHasStarted } from "../components/ChatView.logic";
5import {
6 DraftId,
7 markPromotedDraftThreadByRef,
8 useComposerDraftStore,
9} from "../composerDraftStore";
10import { SidebarInset } from "../components/ui/sidebar";
11import { buildThreadRouteParams } from "../threadRoutes";
12import { useThreadRefs, useThreadShell } from "../state/entities";
13
14function DraftChatThreadRouteView() {
15 const navigate = useNavigate();
16 const { draftId: rawDraftId } = Route.useParams();
17 const draftId = DraftId.make(rawDraftId);
18 const draftSession = useComposerDraftStore((store) => store.getDraftSession(draftId));
19 const threadRefs = useThreadRefs();
20 const inferredThreadRef = draftSession
21 ? (threadRefs.find(
22 (ref) =>
23 ref.environmentId === draftSession.environmentId &&
24 ref.threadId === draftSession.threadId,
25 ) ?? null)
26 : null;
27 const serverThreadRef = draftSession?.promotedTo ?? inferredThreadRef;
28 const serverThread = useThreadShell(serverThreadRef);
29 const serverThreadStarted = threadHasStarted(serverThread);
30 const canonicalThreadRef = serverThreadStarted ? serverThreadRef : null;
31
32 useEffect(() => {
33 if (!inferredThreadRef || draftSession?.promotedTo) {
34 return;
35 }
36 markPromotedDraftThreadByRef(inferredThreadRef);
37 }, [draftSession?.promotedTo, inferredThreadRef]);
38
39 useEffect(() => {
40 if (!canonicalThreadRef) {
41 return;
42 }
43 void navigate({
44 to: "/$environmentId/$threadId",
45 params: buildThreadRouteParams(canonicalThreadRef),
46 replace: true,
47 });
48 }, [canonicalThreadRef, navigate]);
49
50 useEffect(() => {
51 if (draftSession || canonicalThreadRef) {
52 return;
53 }
54 void navigate({ to: "/", replace: true });
55 }, [canonicalThreadRef, draftSession, navigate]);
56
57 if (canonicalThreadRef) {
58 return (
59 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">
60 <ChatView
61 environmentId={canonicalThreadRef.environmentId}
62 threadId={canonicalThreadRef.threadId}
63 routeKind="server"
64 />
65 </SidebarInset>
66 );
67 }
68
69 if (!draftSession) {
70 return null;
71 }
72
73 return (
74 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">
75 <ChatView
76 draftId={draftId}
77 environmentId={draftSession.environmentId}
78 threadId={draftSession.threadId}
79 routeKind="draft"
80 />
81 </SidebarInset>
82 );
83}
84
85export const Route = createFileRoute("/_chat/draft/$draftId")({
86 component: DraftChatThreadRouteView,
87});