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

use-thread-selection.ts

204 lines7.3 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 type OrchestrationThread,
7 ThreadId,
8 type ScopedProjectRef,
9 type ScopedThreadRef,
10} from "@t3tools/contracts";
11import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12import * as Option from "effect/Option";
13​
14import { scopedThreadKey } from "../lib/scopedEntities";
15import { useProject, useThreadShell } from "../state/entities";
16import { useEnvironmentThread } from "../state/threads";
17import {
18 resolvePendingThreadCreation,
19 pendingThreadCreationOutcomesAtom,
20 pendingThreadCreationShell,
21 type PendingThreadCreation,
22} from "./pending-thread-creation";
23import {
24 useRemoteEnvironmentRuntime,
25 useSavedRemoteConnection,
26} from "./use-remote-environment-registry";
27import { useThreadOutboxMessages } from "./use-thread-outbox";
28type ThreadSelectionRouteParams = {
29 readonly environmentId?: string | string[];
30 readonly threadId?: string | string[];
31};
32​
33function firstRouteParam(value: string | string[] | undefined): string | null {
34 if (Array.isArray(value)) {
35 return value[0] ?? null;
36 }
37​
38 return value ?? null;
40​
41function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["updatedAt"] | null {
42 for (let index = thread.messages.length - 1; index >= 0; index -= 1) {
43 const message = thread.messages[index];
44 if (message?.role === "user") {
45 return message.createdAt;
46 }
47 }
48​
49 return null;
51​
52function threadDetailToShell(
53 environmentId: EnvironmentId,
54 thread: OrchestrationThread,
55): EnvironmentThreadShell {
56 return {
57 environmentId,
58 id: thread.id,
59 projectId: thread.projectId,
60 title: thread.title,
61 modelSelection: thread.modelSelection,
62 runtimeMode: thread.runtimeMode,
63 interactionMode: thread.interactionMode,
64 branch: thread.branch,
65 worktreePath: thread.worktreePath,
66 linkedPullRequest: thread.linkedPullRequest ?? null,
67 pullRequests: thread.pullRequests,
68 branchPullRequest: thread.branchPullRequest ?? null,
69 latestTurn: thread.latestTurn,
70 createdAt: thread.createdAt,
71 updatedAt: thread.updatedAt,
72 archivedAt: thread.archivedAt,
73 settledOverride: thread.settledOverride,
74 settledAt: thread.settledAt,
75 unsettledAt: thread.unsettledAt,
76 activeOrderKey: thread.activeOrderKey,
77 autoSettleDisabledAt: thread.autoSettleDisabledAt,
78 pinnedAt: thread.pinnedAt,
79 pinOrderKey: thread.pinOrderKey,
80 snoozedUntil: thread.snoozedUntil ?? null,
81 snoozedAt: thread.snoozedAt ?? null,
82 session: thread.session,
83 latestUserMessageAt: latestUserMessageAt(thread),
84 hasPendingApprovals: false,
85 hasPendingUserInput: false,
86 hasActionableProposedPlan: false,
87 };
89​
90function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
91 const routeParams = params ?? {};
92 const routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
93 const environmentId = firstRouteParam(routeParams.environmentId);
94 const threadId = firstRouteParam(routeParams.threadId);
95 if (!environmentId || !threadId) {
96 return null;
97 }
98​
99 return {
100 environmentId: EnvironmentId.make(environmentId),
101 threadId: ThreadId.make(threadId),
102 };
103 }, [routeParams.environmentId, routeParams.threadId]);
104 const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
105 if (routeThreadRef !== null) {
106 lastRouteThreadRef.current = routeThreadRef;
107 }
108 const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
109 const selectedThreadShell = useThreadShell(selectedThreadRef);
110 const selectedThreadKey =
111 selectedThreadRef === null
112 ? null
113 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
114 const queuedMessagesByThreadKey = useThreadOutboxMessages();
115 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
116 // A creation the outbox still holds or just delivered: the thread screen
117 // opened before the server made the thread, so present a stand-in shell.
118 const pendingCreation = useMemo<PendingThreadCreation | null>(() => {
119 if (selectedThreadKey === null) {
120 return null;
121 }
122 const queued = queuedMessagesByThreadKey[selectedThreadKey]?.find(
123 (message) => message.creation !== undefined,
124 );
125 const outcome = creationOutcome[selectedThreadKey] ?? null;
126 const message = queued ?? outcome?.message ?? null;
127 return message === null ? null : { message, outcome };
128 }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]);
129 // Until the creation is delivered the server has no thread to subscribe
130 // to; subscribing anyway would retry "not found" for the whole setup.
131 const selectedThreadDetailRef =
132 selectedThreadShell !== null ||
133 pendingCreation === null ||
134 pendingCreation.outcome?.kind === "delivered"
135 ? selectedThreadRef
136 : null;
137 const selectedThreadDetailState = useEnvironmentThread(
138 selectedThreadDetailRef?.environmentId ?? null,
139 selectedThreadDetailRef?.threadId ?? null,
140 );
141 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
142 const selectedThread = useMemo(
143 () =>
144 selectedThreadShell ??
145 (selectedThreadRef !== null && selectedThreadDetail !== null
146 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
147 : pendingCreation !== null
148 ? pendingThreadCreationShell(pendingCreation.message)
149 : null),
150 [pendingCreation, selectedThreadDetail, selectedThreadRef, selectedThreadShell],
151 );
152 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
153 const selectedThreadCreation = resolvePendingThreadCreation({
154 threadKey: selectedThreadKey,
155 pending: pendingCreation,
156 previous: previousCreation,
157 detail: selectedThreadDetail,
158 });
159 if (previousCreation !== selectedThreadCreation) {
160 setPreviousCreation(selectedThreadCreation);
161 }
162 const selectedProjectRef = useMemo<ScopedProjectRef | null>(
163 () =>
164 selectedThread === null
165 ? null
166 : {
167 environmentId: selectedThread.environmentId,
168 projectId: selectedThread.projectId,
169 },
170 [selectedThread],
171 );
172 const selectedThreadProject = useProject(selectedProjectRef);
173 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
174 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
175 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
176​
177 return useMemo(
178 () => ({
179 selectedThreadRef,
180 selectedThread,
181 selectedThreadCreation,
182 selectedThreadDetailState,
183 selectedThreadProject,
184 selectedEnvironmentConnection,
185 selectedEnvironmentRuntime,
186 }),
187 [
188 selectedEnvironmentConnection,
189 selectedEnvironmentRuntime,
190 selectedThread,
191 selectedThreadCreation,
192 selectedThreadDetailState,
193 selectedThreadProject,
194 selectedThreadRef,
195 ],
196 );
198​
199type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
200​
201export function useThreadSelection(): ThreadSelectionState {
202 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
203 return useResolvedThreadSelection(route.params);