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

use-thread-selection.ts

217 lines8.2 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useRoute, type RouteProp } from "@react-navigation/native";
3import { useState } from "react";
4import { useMessages } from "gt-react-native";
5import {
6 EnvironmentId,
7 ThreadId,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2ThreadShell,
10 type ScopedProjectRef,
11 type ScopedThreadRef,
12} from "@t3tools/contracts";
13import {
14 presentThreadShell,
15 type EnvironmentThreadShell,
16} from "@t3tools/client-runtime/state/shell";
17import {
18 deriveLatestThreadRun,
19 deriveThreadRuntime,
20} from "@t3tools/client-runtime/state/thread-execution";
21import * as Option from "effect/Option";
22​
23import { scopedThreadKey } from "../lib/scopedEntities";
24import { useProject, useQuietThreadShell } from "./entities";
25import { useEnvironmentThread } from "./threads";
26import {
27 resolvePendingThreadCreation,
28 pendingThreadCreationOutcomesAtom,
29 pendingThreadCreationShell,
30 selectThreadCreationDetail,
31 type PendingThreadCreation,
32} from "./pending-thread-creation";
33import {
34 useRemoteEnvironmentRuntime,
35 useSavedRemoteConnection,
36} from "./use-remote-environment-registry";
37import { useThreadOutboxMessages } from "./use-thread-outbox";
38type ThreadSelectionRouteParams = {
39 readonly environmentId?: string | string[];
40 readonly threadId?: string | string[];
41};
42​
43function firstRouteParam(value: string | string[] | undefined): string | null {
44 const first = Array.isArray(value) ? value[0] : value;
45 return first === undefined || first.trim().length === 0 ? null : first;
47​
48function latestUserMessageAt(
49 projection: OrchestrationV2ThreadProjection,
50): OrchestrationV2ThreadShell["latestUserMessageAt"] {
51 for (let index = projection.messages.length - 1; index >= 0; index -= 1) {
52 const message = projection.messages[index];
53 if (message?.role === "user") {
54 return message.createdAt;
55 }
56 }
57​
58 return null;
60​
61function threadDetailToShell(
62 environmentId: EnvironmentId,
63 projection: OrchestrationV2ThreadProjection,
64): EnvironmentThreadShell {
65 const thread = projection.thread;
66 const latestRun = deriveLatestThreadRun(projection);
67 const runtime = deriveThreadRuntime(projection);
68 const pendingRequest =
69 projection.runtimeRequests.find((request) => request.status === "pending") ?? null;
70 return presentThreadShell(environmentId, {
71 id: thread.id,
72 projectId: thread.projectId,
73 title: thread.title,
74 providerInstanceId: thread.providerInstanceId,
75 modelSelection: thread.modelSelection,
76 runtimeMode: thread.runtimeMode,
77 interactionMode: thread.interactionMode,
78 branch: thread.branch,
79 worktreePath: thread.worktreePath,
80 linkedPullRequest: thread.linkedPullRequest ?? null,
81 pullRequests: thread.pullRequests,
82 branchPullRequest: thread.branchPullRequest ?? null,
83 activeProviderThreadId: thread.activeProviderThreadId,
84 lineage: thread.lineage,
85 forkedFrom: thread.forkedFrom,
86 createdBy: thread.createdBy,
87 creationSource: thread.creationSource,
88 latestRunId: latestRun?.runId ?? null,
89 activeRunId: runtime?.activeRunId ?? null,
90 status: runtime?.status ?? "idle",
91 pendingRuntimeRequest:
92 pendingRequest === null
93 ? null
94 : { id: pendingRequest.id, kind: pendingRequest.kind, createdAt: pendingRequest.createdAt },
95 latestVisibleMessage: null,
96 latestUserMessageAt: latestUserMessageAt(projection),
97 hasActionableProposedPlan: false,
98 itemCount: projection.turnItems.length,
99 visibleItemCount: projection.visibleTurnItems.length,
100 createdAt: thread.createdAt,
101 updatedAt: thread.updatedAt,
102 archivedAt: thread.archivedAt,
103 settledOverride: thread.settledOverride,
104 settledAt: thread.settledAt,
105 unsettledAt: thread.unsettledAt,
106 activeOrderKey: thread.activeOrderKey,
107 autoSettleDisabledAt: thread.autoSettleDisabledAt,
108 pinnedAt: thread.pinnedAt,
109 pinOrderKey: thread.pinOrderKey,
110 snoozedUntil: thread.snoozedUntil ?? null,
111 snoozedAt: thread.snoozedAt ?? null,
112 deletedAt: thread.deletedAt,
113 });
115​
116function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
117 const resolve = useMessages();
118 const routeParams = params ?? {};
119 const routeEnvironmentId = firstRouteParam(routeParams.environmentId);
120 const routeThreadId = firstRouteParam(routeParams.threadId);
121 // Retain the last complete thread ref while closing routes drop params.
122 const [lastRouteThreadRef, setLastRouteThreadRef] = useState<ScopedThreadRef | null>(null);
123 if (
124 routeEnvironmentId !== null &&
125 routeThreadId !== null &&
126 (lastRouteThreadRef?.environmentId !== routeEnvironmentId ||
127 lastRouteThreadRef.threadId !== routeThreadId)
128 ) {
129 setLastRouteThreadRef({
130 environmentId: EnvironmentId.make(routeEnvironmentId),
131 threadId: ThreadId.make(routeThreadId),
132 });
133 }
134 const selectedThreadRef =
135 routeEnvironmentId !== null && routeThreadId !== null
136 ? lastRouteThreadRef?.environmentId === routeEnvironmentId &&
137 lastRouteThreadRef.threadId === routeThreadId
138 ? lastRouteThreadRef
139 : {
140 environmentId: EnvironmentId.make(routeEnvironmentId),
141 threadId: ThreadId.make(routeThreadId),
142 }
143 : lastRouteThreadRef;
144 const selectedThreadShell = useQuietThreadShell(selectedThreadRef);
145 const selectedThreadKey =
146 selectedThreadRef === null
147 ? null
148 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
149 const queuedMessagesByThreadKey = useThreadOutboxMessages();
150 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
151 const { pendingCreation, detailRef: selectedThreadDetailRef } = selectThreadCreationDetail({
152 threadRef: selectedThreadRef,
153 threadKey: selectedThreadKey,
154 queuedMessagesByThreadKey,
155 outcomes: creationOutcome,
156 });
157 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
158 const needsDetail =
159 selectedThreadShell === null || pendingCreation !== null || previousCreation !== null;
160 const selectedThreadDetailState = useEnvironmentThread(
161 needsDetail ? (selectedThreadDetailRef?.environmentId ?? null) : null,
162 needsDetail ? (selectedThreadDetailRef?.threadId ?? null) : null,
163 );
164 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
165 const selectedThread =
166 selectedThreadShell ??
167 (selectedThreadRef !== null && selectedThreadDetail !== null
168 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
169 : pendingCreation !== null
170 ? pendingThreadCreationShell(pendingCreation.message, resolve)
171 : null);
172 const resolvedCreation = resolvePendingThreadCreation({
173 threadKey: selectedThreadKey,
174 pending: pendingCreation,
175 previous: previousCreation,
176 detail: selectedThreadDetail,
177 });
178 // Compare pendingCreation contents; new render-time objects would otherwise continually set state.
179 const creationUnchanged =
180 resolvedCreation === previousCreation ||
181 (resolvedCreation !== null &&
182 previousCreation !== null &&
183 resolvedCreation.message === previousCreation.message &&
184 resolvedCreation.outcome === previousCreation.outcome);
185 if (!creationUnchanged) {
186 setPreviousCreation(resolvedCreation);
187 }
188 const selectedThreadCreation = creationUnchanged ? previousCreation : resolvedCreation;
189 const selectedProjectRef: ScopedProjectRef | null =
190 selectedThread === null
191 ? null
192 : {
193 environmentId: selectedThread.environmentId,
194 projectId: selectedThread.projectId,
195 };
196 const selectedThreadProject = useProject(selectedProjectRef);
197 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
198 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
199 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
200​
201 return {
202 selectedThreadRef,
203 selectedThread,
204 selectedThreadCreation,
205 selectedThreadDetailRef,
206 selectedThreadProject,
207 selectedEnvironmentConnection,
208 selectedEnvironmentRuntime,
209 };
211​
212type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
213​
214export function useThreadSelection(): ThreadSelectionState {
215 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
216 return useResolvedThreadSelection(route.params);