Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-thread-selection.ts

228 lines8.8 KB

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;
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;
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 });
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 // The shell can arrive before creation is acknowledged. Wait for delivery
161 // before subscribing: an early not-found is cached as a deleted thread.
162 // Every detail reader must use this ref, not the route id.
163 const selectedThreadDetailRef =
164 pendingCreation === null || pendingCreation.outcome?.kind === "delivered"
165 ? selectedThreadRef
166 : null;
167 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
168 const needsDetail =
169 selectedThreadShell === null || pendingCreation !== null || previousCreation !== null;
170 const selectedThreadDetailState = useEnvironmentThread(
171 needsDetail ? (selectedThreadDetailRef?.environmentId ?? null) : null,
172 needsDetail ? (selectedThreadDetailRef?.threadId ?? null) : null,
173 );
174 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
175 const selectedThread =
176 selectedThreadShell ??
177 (selectedThreadRef !== null && selectedThreadDetail !== null
178 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
179 : pendingCreation !== null
180 ? pendingThreadCreationShell(pendingCreation.message)
181 : null);
182 const resolvedCreation = resolvePendingThreadCreation({
183 threadKey: selectedThreadKey,
184 pending: pendingCreation,
185 previous: previousCreation,
186 detail: selectedThreadDetail,
187 });
188 // `pendingCreation` is rebuilt each render, so compare contents: an identity
189 // check would set state on every render.
190 const creationUnchanged =
191 resolvedCreation === previousCreation ||
192 (resolvedCreation !== null &&
193 previousCreation !== null &&
194 resolvedCreation.message === previousCreation.message &&
195 resolvedCreation.outcome === previousCreation.outcome);
196 if (!creationUnchanged) {
197 setPreviousCreation(resolvedCreation);
198 }
199 const selectedThreadCreation = creationUnchanged ? previousCreation : resolvedCreation;
200 const selectedProjectRef: ScopedProjectRef | null =
201 selectedThread === null
202 ? null
203 : {
204 environmentId: selectedThread.environmentId,
205 projectId: selectedThread.projectId,
206 };
207 const selectedThreadProject = useProject(selectedProjectRef);
208 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
209 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
210 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
211​
212 return {
213 selectedThreadRef,
214 selectedThread,
215 selectedThreadCreation,
216 selectedThreadDetailRef,
217 selectedThreadProject,
218 selectedEnvironmentConnection,
219 selectedEnvironmentRuntime,
220 };
222​
223type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
224​
225export function useThreadSelection(): ThreadSelectionState {
226 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
227 return useResolvedThreadSelection(route.params);