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 ThreadId,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2ThreadShell,
9 type ScopedProjectRef,
10 type ScopedThreadRef,
11} from "@t3tools/contracts";
12import {
13 presentThreadShell,
14 type EnvironmentThreadShell,
15} from "@t3tools/client-runtime/state/shell";
16import {
17 deriveLatestThreadRun,
18 deriveThreadRuntime,
19} from "@t3tools/client-runtime/state/thread-execution";
20import * as Option from "effect/Option";
21
22import { scopedThreadKey } from "../lib/scopedEntities";
23import { useProject, useThreadShell } from "../state/entities";
24import { useEnvironmentThread } from "../state/threads";
25import {
26 resolvePendingThreadCreation,
27 pendingThreadCreationOutcomesAtom,
28 pendingThreadCreationShell,
29 type PendingThreadCreation,
30} from "./pending-thread-creation";
31import {
32 useRemoteEnvironmentRuntime,
33 useSavedRemoteConnection,
34} from "./use-remote-environment-registry";
35import { useThreadOutboxMessages } from "./use-thread-outbox";
36type ThreadSelectionRouteParams = {
37 readonly environmentId?: string | string[];
38 readonly threadId?: string | string[];
39};
40
41function firstRouteParam(value: string | string[] | undefined): string | null {
42 if (Array.isArray(value)) {
43 return value[0] ?? null;
44 }
45
46 return value ?? null;
47}
48
49function latestUserMessageAt(
50 projection: OrchestrationV2ThreadProjection,
51): OrchestrationV2ThreadShell["latestUserMessageAt"] {
52 for (let index = projection.messages.length - 1; index >= 0; index -= 1) {
53 const message = projection.messages[index];
54 if (message?.role === "user") {
55 return message.createdAt;
56 }
57 }
58
59 return null;
60}
61
62/**
63 * Builds an optimistic thread shell from the detail projection for the window
64 * where the shell list has not materialized the thread yet (e.g. a thread that
65 * was just created from this device).
66 */
67function threadDetailToShell(
68 environmentId: EnvironmentId,
69 projection: OrchestrationV2ThreadProjection,
70): EnvironmentThreadShell {
71 const thread = projection.thread;
72 const latestRun = deriveLatestThreadRun(projection);
73 const runtime = deriveThreadRuntime(projection);
74 const pendingRequest =
75 projection.runtimeRequests.find((request) => request.status === "pending") ?? null;
76 return presentThreadShell(environmentId, {
77 id: thread.id,
78 projectId: thread.projectId,
79 title: thread.title,
80 providerInstanceId: thread.providerInstanceId,
81 modelSelection: thread.modelSelection,
82 runtimeMode: thread.runtimeMode,
83 interactionMode: thread.interactionMode,
84 branch: thread.branch,
85 worktreePath: thread.worktreePath,
86 linkedPullRequest: thread.linkedPullRequest ?? null,
87 pullRequests: thread.pullRequests,
88 branchPullRequest: thread.branchPullRequest ?? null,
89 activeProviderThreadId: thread.activeProviderThreadId,
90 lineage: thread.lineage,
91 forkedFrom: thread.forkedFrom,
92 createdBy: thread.createdBy,
93 creationSource: thread.creationSource,
94 latestRunId: latestRun?.runId ?? null,
95 activeRunId: runtime?.activeRunId ?? null,
96 status: runtime?.status ?? "idle",
97 pendingRuntimeRequest:
98 pendingRequest === null
99 ? null
100 : { id: pendingRequest.id, kind: pendingRequest.kind, createdAt: pendingRequest.createdAt },
101 latestVisibleMessage: null,
102 latestUserMessageAt: latestUserMessageAt(projection),
103 hasActionableProposedPlan: false,
104 itemCount: projection.turnItems.length,
105 visibleItemCount: projection.visibleTurnItems.length,
106 createdAt: thread.createdAt,
107 updatedAt: thread.updatedAt,
108 archivedAt: thread.archivedAt,
109 settledOverride: thread.settledOverride,
110 settledAt: thread.settledAt,
111 unsettledAt: thread.unsettledAt,
112 activeOrderKey: thread.activeOrderKey,
113 autoSettleDisabledAt: thread.autoSettleDisabledAt,
114 pinnedAt: thread.pinnedAt,
115 pinOrderKey: thread.pinOrderKey,
116 snoozedUntil: thread.snoozedUntil ?? null,
117 snoozedAt: thread.snoozedAt ?? null,
118 deletedAt: thread.deletedAt,
119 });
120}
121
122function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
123 const routeParams = params ?? {};
124 const routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
125 const environmentId = firstRouteParam(routeParams.environmentId);
126 const threadId = firstRouteParam(routeParams.threadId);
127 if (!environmentId || !threadId) {
128 return null;
129 }
130
131 return {
132 environmentId: EnvironmentId.make(environmentId),
133 threadId: ThreadId.make(threadId),
134 };
135 }, [routeParams.environmentId, routeParams.threadId]);
136 const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
137 if (routeThreadRef !== null) {
138 lastRouteThreadRef.current = routeThreadRef;
139 }
140 const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
141 const selectedThreadShell = useThreadShell(selectedThreadRef);
142 const selectedThreadKey =
143 selectedThreadRef === null
144 ? null
145 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
146 const queuedMessagesByThreadKey = useThreadOutboxMessages();
147 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
148 // A creation the outbox still holds or just delivered: the thread screen
149 // opened before the server made the thread, so present a stand-in shell.
150 const pendingCreation = useMemo<PendingThreadCreation | null>(() => {
151 if (selectedThreadKey === null) {
152 return null;
153 }
154 const queued = queuedMessagesByThreadKey[selectedThreadKey]?.find(
155 (message) => message.creation !== undefined,
156 );
157 const outcome = creationOutcome[selectedThreadKey] ?? null;
158 const message = queued ?? outcome?.message ?? null;
159 return message === null ? null : { message, outcome };
160 }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]);
161 // Until the creation is delivered the server has no thread to subscribe
162 // to; subscribing anyway would retry "not found" for the whole setup.
163 const selectedThreadDetailRef =
164 selectedThreadShell !== null ||
165 pendingCreation === null ||
166 pendingCreation.outcome?.kind === "delivered"
167 ? selectedThreadRef
168 : null;
169 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
170 // Normal selection is shell-only. Detail readers subscribe separately; only
171 // optimistic creation needs the projection here until its prompt arrives.
172 const needsDetail =
173 selectedThreadShell === null || pendingCreation !== null || previousCreation !== null;
174 const selectedThreadDetailState = useEnvironmentThread(
175 needsDetail ? (selectedThreadDetailRef?.environmentId ?? null) : null,
176 needsDetail ? (selectedThreadDetailRef?.threadId ?? null) : null,
177 );
178 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
179 const selectedThread = useMemo(
180 () =>
181 selectedThreadShell ??
182 (selectedThreadRef !== null && selectedThreadDetail !== null
183 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
184 : pendingCreation !== null
185 ? pendingThreadCreationShell(pendingCreation.message)
186 : null),
187 [pendingCreation, selectedThreadDetail, selectedThreadRef, selectedThreadShell],
188 );
189 const selectedThreadCreation = resolvePendingThreadCreation({
190 threadKey: selectedThreadKey,
191 pending: pendingCreation,
192 previous: previousCreation,
193 detail: selectedThreadDetail,
194 });
195 if (previousCreation !== selectedThreadCreation) {
196 setPreviousCreation(selectedThreadCreation);
197 }
198 const selectedProjectRef = useMemo<ScopedProjectRef | null>(
199 () =>
200 selectedThread === null
201 ? null
202 : {
203 environmentId: selectedThread.environmentId,
204 projectId: selectedThread.projectId,
205 },
206 [selectedThread],
207 );
208 const selectedThreadProject = useProject(selectedProjectRef);
209 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
210 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
211 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
212
213 return useMemo(
214 () => ({
215 selectedThreadRef,
216 selectedThread,
217 selectedThreadCreation,
218 selectedThreadDetailRef,
219 selectedThreadProject,
220 selectedEnvironmentConnection,
221 selectedEnvironmentRuntime,
222 }),
223 [
224 selectedEnvironmentConnection,
225 selectedEnvironmentRuntime,
226 selectedThread,
227 selectedThreadCreation,
228 selectedThreadDetailRef,
229 selectedThreadProject,
230 selectedThreadRef,
231 ],
232 );
233}
234
235type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
236
237export function useThreadSelection(): ThreadSelectionState {
238 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
239 return useResolvedThreadSelection(route.params);
240}