Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useRoute, type RouteProp } from "@react-navigation/native";
3import { 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, useQuietThreadShell } 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 const first = Array.isArray(value) ? value[0] : value;
43 return first === undefined || first.trim().length === 0 ? null : first;
44}
45
46function latestUserMessageAt(
47 projection: OrchestrationV2ThreadProjection,
48): OrchestrationV2ThreadShell["latestUserMessageAt"] {
49 for (let index = projection.messages.length - 1; index >= 0; index -= 1) {
50 const message = projection.messages[index];
51 if (message?.role === "user") {
52 return message.createdAt;
53 }
54 }
55
56 return null;
57}
58
59function threadDetailToShell(
60 environmentId: EnvironmentId,
61 projection: OrchestrationV2ThreadProjection,
62): EnvironmentThreadShell {
63 const thread = projection.thread;
64 const latestRun = deriveLatestThreadRun(projection);
65 const runtime = deriveThreadRuntime(projection);
66 const pendingRequest =
67 projection.runtimeRequests.find((request) => request.status === "pending") ?? null;
68 return presentThreadShell(environmentId, {
69 id: thread.id,
70 projectId: thread.projectId,
71 title: thread.title,
72 providerInstanceId: thread.providerInstanceId,
73 modelSelection: thread.modelSelection,
74 runtimeMode: thread.runtimeMode,
75 interactionMode: thread.interactionMode,
76 branch: thread.branch,
77 worktreePath: thread.worktreePath,
78 linkedPullRequest: thread.linkedPullRequest ?? null,
79 pullRequests: thread.pullRequests,
80 branchPullRequest: thread.branchPullRequest ?? null,
81 activeProviderThreadId: thread.activeProviderThreadId,
82 lineage: thread.lineage,
83 forkedFrom: thread.forkedFrom,
84 createdBy: thread.createdBy,
85 creationSource: thread.creationSource,
86 latestRunId: latestRun?.runId ?? null,
87 activeRunId: runtime?.activeRunId ?? null,
88 status: runtime?.status ?? "idle",
89 pendingRuntimeRequest:
90 pendingRequest === null
91 ? null
92 : { id: pendingRequest.id, kind: pendingRequest.kind, createdAt: pendingRequest.createdAt },
93 latestVisibleMessage: null,
94 latestUserMessageAt: latestUserMessageAt(projection),
95 hasActionableProposedPlan: false,
96 itemCount: projection.turnItems.length,
97 visibleItemCount: projection.visibleTurnItems.length,
98 createdAt: thread.createdAt,
99 updatedAt: thread.updatedAt,
100 archivedAt: thread.archivedAt,
101 settledOverride: thread.settledOverride,
102 settledAt: thread.settledAt,
103 unsettledAt: thread.unsettledAt,
104 activeOrderKey: thread.activeOrderKey,
105 autoSettleDisabledAt: thread.autoSettleDisabledAt,
106 pinnedAt: thread.pinnedAt,
107 pinOrderKey: thread.pinOrderKey,
108 snoozedUntil: thread.snoozedUntil ?? null,
109 snoozedAt: thread.snoozedAt ?? null,
110 deletedAt: thread.deletedAt,
111 });
112}
113
114function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
115 const routeParams = params ?? {};
116 const routeEnvironmentId = firstRouteParam(routeParams.environmentId);
117 const routeThreadId = firstRouteParam(routeParams.threadId);
118 // A route that drops its params (a closing sheet, for example) keeps showing
119 // the last thread, so the last complete pair is kept as state.
120 const [lastRouteThreadRef, setLastRouteThreadRef] = useState<ScopedThreadRef | null>(null);
121 if (
122 routeEnvironmentId !== null &&
123 routeThreadId !== null &&
124 (lastRouteThreadRef?.environmentId !== routeEnvironmentId ||
125 lastRouteThreadRef.threadId !== routeThreadId)
126 ) {
127 setLastRouteThreadRef({
128 environmentId: EnvironmentId.make(routeEnvironmentId),
129 threadId: ThreadId.make(routeThreadId),
130 });
131 }
132 const selectedThreadRef =
133 routeEnvironmentId !== null && routeThreadId !== null
134 ? lastRouteThreadRef?.environmentId === routeEnvironmentId &&
135 lastRouteThreadRef.threadId === routeThreadId
136 ? lastRouteThreadRef
137 : {
138 environmentId: EnvironmentId.make(routeEnvironmentId),
139 threadId: ThreadId.make(routeThreadId),
140 }
141 : lastRouteThreadRef;
142 const selectedThreadShell = useQuietThreadShell(selectedThreadRef);
143 const selectedThreadKey =
144 selectedThreadRef === null
145 ? null
146 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
147 const queuedMessagesByThreadKey = useThreadOutboxMessages();
148 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
149 const pendingCreation = ((): PendingThreadCreation | null => {
150 if (selectedThreadKey === null) {
151 return null;
152 }
153 const queued = queuedMessagesByThreadKey[selectedThreadKey]?.find(
154 (message) => message.creation !== undefined,
155 );
156 const outcome = creationOutcome[selectedThreadKey] ?? null;
157 const message = queued ?? outcome?.message ?? null;
158 return message === null ? null : { message, outcome };
159 })();
160 // Until the creation is delivered the server has no thread to subscribe
161 // to. Every detail reader must use this ref, not the route id: an earlier
162 // read gets a definitive not-found, which the thread state keeps as deleted.
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 const needsDetail =
171 selectedThreadShell === null || pendingCreation !== null || previousCreation !== null;
172 const selectedThreadDetailState = useEnvironmentThread(
173 needsDetail ? (selectedThreadDetailRef?.environmentId ?? null) : null,
174 needsDetail ? (selectedThreadDetailRef?.threadId ?? null) : null,
175 );
176 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
177 const selectedThread =
178 selectedThreadShell ??
179 (selectedThreadRef !== null && selectedThreadDetail !== null
180 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
181 : pendingCreation !== null
182 ? pendingThreadCreationShell(pendingCreation.message)
183 : null);
184 const resolvedCreation = resolvePendingThreadCreation({
185 threadKey: selectedThreadKey,
186 pending: pendingCreation,
187 previous: previousCreation,
188 detail: selectedThreadDetail,
189 });
190 // `pendingCreation` is rebuilt each render, so compare contents: an identity
191 // check would set state on every render.
192 const creationUnchanged =
193 resolvedCreation === previousCreation ||
194 (resolvedCreation !== null &&
195 previousCreation !== null &&
196 resolvedCreation.message === previousCreation.message &&
197 resolvedCreation.outcome === previousCreation.outcome);
198 if (!creationUnchanged) {
199 setPreviousCreation(resolvedCreation);
200 }
201 const selectedThreadCreation = creationUnchanged ? previousCreation : resolvedCreation;
202 const selectedProjectRef: ScopedProjectRef | null =
203 selectedThread === null
204 ? null
205 : {
206 environmentId: selectedThread.environmentId,
207 projectId: selectedThread.projectId,
208 };
209 const selectedThreadProject = useProject(selectedProjectRef);
210 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
211 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
212 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
213
214 return {
215 selectedThreadRef,
216 selectedThread,
217 selectedThreadCreation,
218 selectedThreadDetailRef,
219 selectedThreadProject,
220 selectedEnvironmentConnection,
221 selectedEnvironmentRuntime,
222 };
223}
224
225type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
226
227export function useThreadSelection(): ThreadSelectionState {
228 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
229 return useResolvedThreadSelection(route.params);
230}