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

use-thread-selection.ts

235 lines8.5 KB

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;
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;
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 pinnedAt: thread.pinnedAt,
114 pinOrderKey: thread.pinOrderKey,
115 snoozedUntil: thread.snoozedUntil ?? null,
116 snoozedAt: thread.snoozedAt ?? null,
117 deletedAt: thread.deletedAt,
118 });
120​
121function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
122 const routeParams = params ?? {};
123 const routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
124 const environmentId = firstRouteParam(routeParams.environmentId);
125 const threadId = firstRouteParam(routeParams.threadId);
126 if (!environmentId || !threadId) {
127 return null;
128 }
129​
130 return {
131 environmentId: EnvironmentId.make(environmentId),
132 threadId: ThreadId.make(threadId),
133 };
134 }, [routeParams.environmentId, routeParams.threadId]);
135 const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
136 if (routeThreadRef !== null) {
137 lastRouteThreadRef.current = routeThreadRef;
138 }
139 const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
140 const selectedThreadShell = useThreadShell(selectedThreadRef);
141 const selectedThreadKey =
142 selectedThreadRef === null
143 ? null
144 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
145 const queuedMessagesByThreadKey = useThreadOutboxMessages();
146 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
147 // A creation the outbox still holds or just delivered: the thread screen
148 // opened before the server made the thread, so present a stand-in shell.
149 const pendingCreation = useMemo<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 }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]);
160 // Until the creation is delivered the server has no thread to subscribe
161 // to; subscribing anyway would retry "not found" for the whole setup.
162 const selectedThreadDetailRef =
163 selectedThreadShell !== null ||
164 pendingCreation === null ||
165 pendingCreation.outcome?.kind === "delivered"
166 ? selectedThreadRef
167 : null;
168 const selectedThreadDetailState = useEnvironmentThread(
169 selectedThreadDetailRef?.environmentId ?? null,
170 selectedThreadDetailRef?.threadId ?? null,
171 );
172 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
173 const selectedThread = useMemo(
174 () =>
175 selectedThreadShell ??
176 (selectedThreadRef !== null && selectedThreadDetail !== null
177 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
178 : pendingCreation !== null
179 ? pendingThreadCreationShell(pendingCreation.message)
180 : null),
181 [pendingCreation, selectedThreadDetail, selectedThreadRef, selectedThreadShell],
182 );
183 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
184 const selectedThreadCreation = resolvePendingThreadCreation({
185 threadKey: selectedThreadKey,
186 pending: pendingCreation,
187 previous: previousCreation,
188 detail: selectedThreadDetail,
189 });
190 if (previousCreation !== selectedThreadCreation) {
191 setPreviousCreation(selectedThreadCreation);
192 }
193 const selectedProjectRef = useMemo<ScopedProjectRef | null>(
194 () =>
195 selectedThread === null
196 ? null
197 : {
198 environmentId: selectedThread.environmentId,
199 projectId: selectedThread.projectId,
200 },
201 [selectedThread],
202 );
203 const selectedThreadProject = useProject(selectedProjectRef);
204 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
205 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
206 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
207​
208 return useMemo(
209 () => ({
210 selectedThreadRef,
211 selectedThread,
212 selectedThreadCreation,
213 selectedThreadDetailState,
214 selectedThreadProject,
215 selectedEnvironmentConnection,
216 selectedEnvironmentRuntime,
217 }),
218 [
219 selectedEnvironmentConnection,
220 selectedEnvironmentRuntime,
221 selectedThread,
222 selectedThreadCreation,
223 selectedThreadDetailState,
224 selectedThreadProject,
225 selectedThreadRef,
226 ],
227 );
229​
230type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
231​
232export function useThreadSelection(): ThreadSelectionState {
233 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
234 return useResolvedThreadSelection(route.params);