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 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 routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
117 const environmentId = firstRouteParam(routeParams.environmentId);
118 const threadId = firstRouteParam(routeParams.threadId);
119 if (!environmentId || !threadId) {
120 return null;
121 }
122
123 return {
124 environmentId: EnvironmentId.make(environmentId),
125 threadId: ThreadId.make(threadId),
126 };
127 }, [routeParams.environmentId, routeParams.threadId]);
128 const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
129 if (routeThreadRef !== null) {
130 lastRouteThreadRef.current = routeThreadRef;
131 }
132 const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
133 const selectedThreadShell = useThreadShell(selectedThreadRef);
134 const selectedThreadKey =
135 selectedThreadRef === null
136 ? null
137 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
138 const queuedMessagesByThreadKey = useThreadOutboxMessages();
139 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
140 const pendingCreation = useMemo<PendingThreadCreation | null>(() => {
141 if (selectedThreadKey === null) {
142 return null;
143 }
144 const queued = queuedMessagesByThreadKey[selectedThreadKey]?.find(
145 (message) => message.creation !== undefined,
146 );
147 const outcome = creationOutcome[selectedThreadKey] ?? null;
148 const message = queued ?? outcome?.message ?? null;
149 return message === null ? null : { message, outcome };
150 }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]);
151 // Until the creation is delivered the server has no thread to subscribe
152 // to. Every detail reader must use this ref, not the route id: an earlier
153 // read gets a definitive not-found, which the thread state keeps as deleted.
154 const selectedThreadDetailRef =
155 selectedThreadShell !== null ||
156 pendingCreation === null ||
157 pendingCreation.outcome?.kind === "delivered"
158 ? selectedThreadRef
159 : null;
160 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
161 const needsDetail =
162 selectedThreadShell === null || pendingCreation !== null || previousCreation !== null;
163 const selectedThreadDetailState = useEnvironmentThread(
164 needsDetail ? (selectedThreadDetailRef?.environmentId ?? null) : null,
165 needsDetail ? (selectedThreadDetailRef?.threadId ?? null) : null,
166 );
167 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
168 const selectedThread = useMemo(
169 () =>
170 selectedThreadShell ??
171 (selectedThreadRef !== null && selectedThreadDetail !== null
172 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
173 : pendingCreation !== null
174 ? pendingThreadCreationShell(pendingCreation.message)
175 : null),
176 [pendingCreation, selectedThreadDetail, selectedThreadRef, selectedThreadShell],
177 );
178 const selectedThreadCreation = resolvePendingThreadCreation({
179 threadKey: selectedThreadKey,
180 pending: pendingCreation,
181 previous: previousCreation,
182 detail: selectedThreadDetail,
183 });
184 if (previousCreation !== selectedThreadCreation) {
185 setPreviousCreation(selectedThreadCreation);
186 }
187 const selectedProjectRef = useMemo<ScopedProjectRef | null>(
188 () =>
189 selectedThread === null
190 ? null
191 : {
192 environmentId: selectedThread.environmentId,
193 projectId: selectedThread.projectId,
194 },
195 [selectedThread],
196 );
197 const selectedThreadProject = useProject(selectedProjectRef);
198 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
199 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
200 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
201
202 return useMemo(
203 () => ({
204 selectedThreadRef,
205 selectedThread,
206 selectedThreadCreation,
207 selectedThreadDetailRef,
208 selectedThreadProject,
209 selectedEnvironmentConnection,
210 selectedEnvironmentRuntime,
211 }),
212 [
213 selectedEnvironmentConnection,
214 selectedEnvironmentRuntime,
215 selectedThread,
216 selectedThreadCreation,
217 selectedThreadDetailRef,
218 selectedThreadProject,
219 selectedThreadRef,
220 ],
221 );
222}
223
224type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
225
226export function useThreadSelection(): ThreadSelectionState {
227 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
228 return useResolvedThreadSelection(route.params);
229}