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

use-thread-selection.ts

226 lines8.7 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 // Retain the last complete thread ref while closing routes drop params.
119 const [lastRouteThreadRef, setLastRouteThreadRef] = useState<ScopedThreadRef | null>(null);
120 if (
121 routeEnvironmentId !== null &&
122 routeThreadId !== null &&
123 (lastRouteThreadRef?.environmentId !== routeEnvironmentId ||
124 lastRouteThreadRef.threadId !== routeThreadId)
125 ) {
126 setLastRouteThreadRef({
127 environmentId: EnvironmentId.make(routeEnvironmentId),
128 threadId: ThreadId.make(routeThreadId),
129 });
130 }
131 const selectedThreadRef =
132 routeEnvironmentId !== null && routeThreadId !== null
133 ? lastRouteThreadRef?.environmentId === routeEnvironmentId &&
134 lastRouteThreadRef.threadId === routeThreadId
135 ? lastRouteThreadRef
136 : {
137 environmentId: EnvironmentId.make(routeEnvironmentId),
138 threadId: ThreadId.make(routeThreadId),
139 }
140 : lastRouteThreadRef;
141 const selectedThreadShell = useQuietThreadShell(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 const pendingCreation = ((): PendingThreadCreation | null => {
149 if (selectedThreadKey === null) {
150 return null;
151 }
152 const queued = queuedMessagesByThreadKey[selectedThreadKey]?.find(
153 (message) => message.creation !== undefined,
154 );
155 const outcome = creationOutcome[selectedThreadKey] ?? null;
156 const message = queued ?? outcome?.message ?? null;
157 return message === null ? null : { message, outcome };
158 })();
159 // The shell can arrive before creation is acknowledged. Wait for delivery
160 // before subscribing: an early not-found is cached as a deleted thread.
161 // Every detail reader must use this ref, not the route id.
162 const selectedThreadDetailRef =
163 pendingCreation === null || pendingCreation.outcome?.kind === "delivered"
164 ? selectedThreadRef
165 : null;
166 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
167 const needsDetail =
168 selectedThreadShell === null || pendingCreation !== null || previousCreation !== null;
169 const selectedThreadDetailState = useEnvironmentThread(
170 needsDetail ? (selectedThreadDetailRef?.environmentId ?? null) : null,
171 needsDetail ? (selectedThreadDetailRef?.threadId ?? null) : null,
172 );
173 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
174 const selectedThread =
175 selectedThreadShell ??
176 (selectedThreadRef !== null && selectedThreadDetail !== null
177 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
178 : pendingCreation !== null
179 ? pendingThreadCreationShell(pendingCreation.message)
180 : null);
181 const resolvedCreation = resolvePendingThreadCreation({
182 threadKey: selectedThreadKey,
183 pending: pendingCreation,
184 previous: previousCreation,
185 detail: selectedThreadDetail,
186 });
187 // Compare pendingCreation contents; new render-time objects would otherwise continually set state.
188 const creationUnchanged =
189 resolvedCreation === previousCreation ||
190 (resolvedCreation !== null &&
191 previousCreation !== null &&
192 resolvedCreation.message === previousCreation.message &&
193 resolvedCreation.outcome === previousCreation.outcome);
194 if (!creationUnchanged) {
195 setPreviousCreation(resolvedCreation);
196 }
197 const selectedThreadCreation = creationUnchanged ? previousCreation : resolvedCreation;
198 const selectedProjectRef: ScopedProjectRef | null =
199 selectedThread === null
200 ? null
201 : {
202 environmentId: selectedThread.environmentId,
203 projectId: selectedThread.projectId,
204 };
205 const selectedThreadProject = useProject(selectedProjectRef);
206 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
207 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
208 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
209​
210 return {
211 selectedThreadRef,
212 selectedThread,
213 selectedThreadCreation,
214 selectedThreadDetailRef,
215 selectedThreadProject,
216 selectedEnvironmentConnection,
217 selectedEnvironmentRuntime,
218 };
220​
221type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
222​
223export function useThreadSelection(): ThreadSelectionState {
224 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
225 return useResolvedThreadSelection(route.params);