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

use-thread-selection.ts

203 lines7.2 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 pinnedAt: thread.pinnedAt,
78 pinOrderKey: thread.pinOrderKey,
79 snoozedUntil: thread.snoozedUntil ?? null,
80 snoozedAt: thread.snoozedAt ?? null,
81 session: thread.session,
82 latestUserMessageAt: latestUserMessageAt(thread),
83 hasPendingApprovals: false,
84 hasPendingUserInput: false,
85 hasActionableProposedPlan: false,
86 };
88​
89function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
90 const routeParams = params ?? {};
91 const routeThreadRef = useMemo<ScopedThreadRef | null>(() => {
92 const environmentId = firstRouteParam(routeParams.environmentId);
93 const threadId = firstRouteParam(routeParams.threadId);
94 if (!environmentId || !threadId) {
95 return null;
96 }
97​
98 return {
99 environmentId: EnvironmentId.make(environmentId),
100 threadId: ThreadId.make(threadId),
101 };
102 }, [routeParams.environmentId, routeParams.threadId]);
103 const lastRouteThreadRef = useRef<ScopedThreadRef | null>(null);
104 if (routeThreadRef !== null) {
105 lastRouteThreadRef.current = routeThreadRef;
106 }
107 const selectedThreadRef = routeThreadRef ?? lastRouteThreadRef.current;
108 const selectedThreadShell = useThreadShell(selectedThreadRef);
109 const selectedThreadKey =
110 selectedThreadRef === null
111 ? null
112 : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId);
113 const queuedMessagesByThreadKey = useThreadOutboxMessages();
114 const creationOutcome = useAtomValue(pendingThreadCreationOutcomesAtom);
115 // A creation the outbox still holds or just delivered: the thread screen
116 // opened before the server made the thread, so present a stand-in shell.
117 const pendingCreation = useMemo<PendingThreadCreation | null>(() => {
118 if (selectedThreadKey === null) {
119 return null;
120 }
121 const queued = queuedMessagesByThreadKey[selectedThreadKey]?.find(
122 (message) => message.creation !== undefined,
123 );
124 const outcome = creationOutcome[selectedThreadKey] ?? null;
125 const message = queued ?? outcome?.message ?? null;
126 return message === null ? null : { message, outcome };
127 }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]);
128 // Until the creation is delivered the server has no thread to subscribe
129 // to; subscribing anyway would retry "not found" for the whole setup.
130 const selectedThreadDetailRef =
131 selectedThreadShell !== null ||
132 pendingCreation === null ||
133 pendingCreation.outcome?.kind === "delivered"
134 ? selectedThreadRef
135 : null;
136 const selectedThreadDetailState = useEnvironmentThread(
137 selectedThreadDetailRef?.environmentId ?? null,
138 selectedThreadDetailRef?.threadId ?? null,
139 );
140 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
141 const selectedThread = useMemo(
142 () =>
143 selectedThreadShell ??
144 (selectedThreadRef !== null && selectedThreadDetail !== null
145 ? threadDetailToShell(selectedThreadRef.environmentId, selectedThreadDetail)
146 : pendingCreation !== null
147 ? pendingThreadCreationShell(pendingCreation.message)
148 : null),
149 [pendingCreation, selectedThreadDetail, selectedThreadRef, selectedThreadShell],
150 );
151 const [previousCreation, setPreviousCreation] = useState<PendingThreadCreation | null>(null);
152 const selectedThreadCreation = resolvePendingThreadCreation({
153 threadKey: selectedThreadKey,
154 pending: pendingCreation,
155 previous: previousCreation,
156 detail: selectedThreadDetail,
157 });
158 if (previousCreation !== selectedThreadCreation) {
159 setPreviousCreation(selectedThreadCreation);
160 }
161 const selectedProjectRef = useMemo<ScopedProjectRef | null>(
162 () =>
163 selectedThread === null
164 ? null
165 : {
166 environmentId: selectedThread.environmentId,
167 projectId: selectedThread.projectId,
168 },
169 [selectedThread],
170 );
171 const selectedThreadProject = useProject(selectedProjectRef);
172 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
173 const selectedEnvironmentConnection = useSavedRemoteConnection(selectedEnvironmentId);
174 const selectedEnvironmentRuntime = useRemoteEnvironmentRuntime(selectedEnvironmentId);
175​
176 return useMemo(
177 () => ({
178 selectedThreadRef,
179 selectedThread,
180 selectedThreadCreation,
181 selectedThreadDetailState,
182 selectedThreadProject,
183 selectedEnvironmentConnection,
184 selectedEnvironmentRuntime,
185 }),
186 [
187 selectedEnvironmentConnection,
188 selectedEnvironmentRuntime,
189 selectedThread,
190 selectedThreadCreation,
191 selectedThreadDetailState,
192 selectedThreadProject,
193 selectedThreadRef,
194 ],
195 );
197​
198type ThreadSelectionState = ReturnType<typeof useResolvedThreadSelection>;
199​
200export function useThreadSelection(): ThreadSelectionState {
201 const route = useRoute<RouteProp<Record<string, ThreadSelectionRouteParams | undefined>>>();
202 return useResolvedThreadSelection(route.params);