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

use-thread-selection.ts

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