Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useRoute, type RouteProp } from "@react-navigation/native";
3import { useMemo, useRef, useState } from "react";
4import {
5 EnvironmentId,
6 type OrchestrationThread,
7 ThreadId,
8 type ScopedProjectRef,
9 type ScopedThreadRef,
10} from "@t3tools/contracts";
11import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12import { pendingProviderTurnSummary } from "@t3tools/shared/pendingProviderTurn";
13import * as Option from "effect/Option";
14
15import { scopedThreadKey } from "../lib/scopedEntities";
16import { useProject, useThreadShell } from "../state/entities";
17import { useEnvironmentThread } from "../state/threads";
18import {
19 resolvePendingThreadCreation,
20 pendingThreadCreationOutcomesAtom,
21 pendingThreadCreationShell,
22 type PendingThreadCreation,
23} from "./pending-thread-creation";
24import {
25 useRemoteEnvironmentRuntime,
26 useSavedRemoteConnection,
27} from "./use-remote-environment-registry";
28import { useThreadOutboxMessages } from "./use-thread-outbox";
29type ThreadSelectionRouteParams = {
30 readonly environmentId?: string | string[];
31 readonly threadId?: string | string[];
32};
33
34function firstRouteParam(value: string | string[] | undefined): string | null {
35 if (Array.isArray(value)) {
36 return value[0] ?? null;
37 }
38
39 return value ?? null;
40}
41
42function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["updatedAt"] | null {
43 for (let index = thread.messages.length - 1; index >= 0; index -= 1) {
44 const message = thread.messages[index];
45 if (message?.role === "user") {
46 return message.createdAt;
47 }
48 }
49
50 return null;
51}
52
53function threadDetailToShell(
54 environmentId: EnvironmentId,
55 thread: OrchestrationThread,
56): EnvironmentThreadShell {
57 return {
58 environmentId,
59 id: thread.id,
60 projectId: thread.projectId,
61 title: thread.title,
62 modelSelection: thread.modelSelection,
63 runtimeMode: thread.runtimeMode,
64 interactionMode: thread.interactionMode,
65 branch: thread.branch,
66 worktreePath: thread.worktreePath,
67 linkedPullRequest: thread.linkedPullRequest ?? null,
68 pullRequests: thread.pullRequests,
69 branchPullRequest: thread.branchPullRequest ?? null,
70 latestTurn: thread.latestTurn,
71 createdAt: thread.createdAt,
72 updatedAt: thread.updatedAt,
73 archivedAt: thread.archivedAt,
74 settledOverride: thread.settledOverride,
75 settledAt: thread.settledAt,
76 unsettledAt: thread.unsettledAt,
77 activeOrderKey: thread.activeOrderKey,
78 pinnedAt: thread.pinnedAt,
79 pinOrderKey: thread.pinOrderKey,
80 snoozedUntil: thread.snoozedUntil ?? null,
81 snoozedAt: thread.snoozedAt ?? null,
82 session: thread.session,
83 pendingProviderTurn: pendingProviderTurnSummary(thread.pendingProviderTurn),
84 latestUserMessageAt: latestUserMessageAt(thread),
85 hasPendingApprovals: false,
86 hasPendingUserInput: false,
87 hasActionableProposedPlan: false,
88 };
89}
90
91function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
92 const routeParams = params ?? {};
93 const routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
94 const environmentId = firstRouteParam(routeParams.environmentId);
95 const threadId = firstRouteParam(routeParams.threadId);
96 if (!environmentId || !threadId) {
97 return null;
98 }
99
100 return {
101 environmentId: EnvironmentId.make(environmentId),
102 threadId: ThreadId.make(threadId),
103 };
104 }, [routeParams.environmentId, routeParams.threadId]);
105 const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
106 if (routeThreadRef !== null) {
107 lastRouteThreadRef.current = routeThreadRef;
108 }
109 const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
110 const selectedThreadShell = useThreadShell(selectedThreadRef);
111 const selectedThreadKey =
112 selectedThreadRef === null
113 ? null
114 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
115 const queuedMessagesByThreadKey = useThreadOutboxMessages();
116 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
117 // A creation the outbox still holds or just delivered: the thread screen
118 // opened before the server made the thread, so present a stand-in shell.
119 const pendingCreation = useMemo<PendingThreadCreation | null>(() => {
120 if (selectedThreadKey === null) {
121 return null;
122 }
123 const queued = queuedMessagesByThreadKey[selectedThreadKey]?.find(
124 (message) => message.creation !== undefined,
125 );
126 const outcome = creationOutcome[selectedThreadKey] ?? null;
127 const message = queued ?? outcome?.message ?? null;
128 return message === null ? null : { message, outcome };
129 }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]);
130 // Until the creation is delivered the server has no thread to subscribe
131 // to; subscribing anyway would retry "not found" for the whole setup.
132 const selectedThreadDetailRef =
133 selectedThreadShell !== null ||
134 pendingCreation === null ||
135 pendingCreation.outcome?.kind === "delivered"
136 ? selectedThreadRef
137 : null;
138 const selectedThreadDetailState = useEnvironmentThread(
139 selectedThreadDetailRef?.environmentId ?? null,
140 selectedThreadDetailRef?.threadId ?? null,
141 );
142 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
143 const selectedThread = useMemo(
144 () =>
145 selectedThreadShell ??
146 (selectedThreadRef !== null && selectedThreadDetail !== null
147 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
148 : pendingCreation !== null
149 ? pendingThreadCreationShell(pendingCreation.message)
150 : null),
151 [pendingCreation, selectedThreadDetail, selectedThreadRef, selectedThreadShell],
152 );
153 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
154 const selectedThreadCreation = resolvePendingThreadCreation({
155 threadKey: selectedThreadKey,
156 pending: pendingCreation,
157 previous: previousCreation,
158 detail: selectedThreadDetail,
159 });
160 if (previousCreation !== selectedThreadCreation) {
161 setPreviousCreation(selectedThreadCreation);
162 }
163 const selectedProjectRef = useMemo<ScopedProjectRef | null>(
164 () =>
165 selectedThread === null
166 ? null
167 : {
168 environmentId: selectedThread.environmentId,
169 projectId: selectedThread.projectId,
170 },
171 [selectedThread],
172 );
173 const selectedThreadProject = useProject(selectedProjectRef);
174 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
175 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
176 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
177
178 return useMemo(
179 () => ({
180 selectedThreadRef,
181 selectedThread,
182 selectedThreadCreation,
183 selectedThreadDetailState,
184 selectedThreadProject,
185 selectedEnvironmentConnection,
186 selectedEnvironmentRuntime,
187 }),
188 [
189 selectedEnvironmentConnection,
190 selectedEnvironmentRuntime,
191 selectedThread,
192 selectedThreadCreation,
193 selectedThreadDetailState,
194 selectedThreadProject,
195 selectedThreadRef,
196 ],
197 );
198}
199
200type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
201
202export function useThreadSelection(): ThreadSelectionState {
203 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
204 return useResolvedThreadSelection(route.params);
205}