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

use-selected-thread-requests.ts

357 lines12.4 KB

1import { useServerConfigs } from "./entities";
2import { Alert } from "react-native";
3import {
4 questionAttachmentDraftKey,
5 questionAttachmentDraftPrefix,
6 questionAttachmentPreparationAtom,
7} from "./question-attachments";
8import { composerDraftsAtom, clearComposerDraft } from "./use-composer-drafts";
9import {
10 composerAttachmentUploadsAtom,
11 composerAttachmentUploadBlockReason,
12 composerAttachmentsStillUploading,
13} from "./composer-attachment-uploads";
14import { useAtomValue } from "@effect/atom-react";
15import { useCallback, useEffect, useMemo, useRef, useState } from "react";
16​
17import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
18import {
19 derivePendingThreadRequests,
20 type ThreadUserInputQuestion,
21} from "@t3tools/client-runtime/state/thread-requests";
22import { Atom } from "effect/unstable/reactivity";
23​
24import { threadEnvironment } from "../state/threads";
25import { scopedRequestKey } from "../lib/scopedEntities";
26import {
27 buildPendingUserInputAnswers,
28 setPendingUserInputCustomAnswer,
29 togglePendingUserInputOptionSelection,
30 type PendingUserInputDraftAnswer,
31} from "../lib/threadActivity";
32import { appAtomRegistry } from "./atom-registry";
33import { useSelectedThreadProjection } from "./use-thread-detail";
34import { useThreadSelection } from "./use-thread-selection";
35import { useAtomCommand } from "./use-atom-command";
36​
37const userInputDraftsByRequestKeyAtom = Atom.make<
38 Record<string, Record<string, PendingUserInputDraftAnswer>>
39>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
40​
41function setUserInputDraftOption(
42 requestKey: string,
43 question: ThreadUserInputQuestion,
44 value: string,
45): void {
46 const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
47 appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
48 ...current,
49 [requestKey]: {
50 ...current[requestKey],
51 [question.id]: togglePendingUserInputOptionSelection(
52 question,
53 current[requestKey]?.[question.id],
54 value,
55 ),
56 },
57 });
59​
60function setUserInputDraftCustomAnswer(
61 requestKey: string,
62 question: ThreadUserInputQuestion,
63 customAnswer: string,
64): void {
65 const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
66 appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
67 ...current,
68 [requestKey]: {
69 ...current[requestKey],
70 [question.id]: setPendingUserInputCustomAnswer(
71 question,
72 current[requestKey]?.[question.id],
73 customAnswer,
74 ),
75 },
76 });
78​
79export function useSelectedThreadRequests() {
80 const respondToApproval = useAtomCommand(
81 threadEnvironment.respondToApproval,
82 "thread approval response",
83 );
84 const respondToUserInput = useAtomCommand(
85 threadEnvironment.respondToUserInput,
86 "thread user input response",
87 );
88 const dismissUserInput = useAtomCommand(
89 threadEnvironment.dismissUserInput,
90 "thread user input dismissal",
91 );
92 const { selectedThread: selectedThreadShell } = useThreadSelection();
93 const selectedThread = useSelectedThreadProjection();
94 const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
95 const userInputResponsesInFlight = useRef(new Set<string>());
96 const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
97 const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
98​
99 const pendingRequests = useMemo(
100 () =>
101 selectedThread === null
102 ? { approvals: [], userInputs: [] }
103 : derivePendingThreadRequests(selectedThread.projection),
104 [selectedThread],
105 );
106 const activePendingApprovals = pendingRequests.approvals;
107 const activePendingApproval = activePendingApprovals[0] ?? null;
108 const activePendingUserInputs = pendingRequests.userInputs;
109 const activePendingUserInput = activePendingUserInputs[0] ?? null;
110 const questionServerConfigs = useServerConfigs();
111 const attachmentDrafts = useAtomValue(composerDraftsAtom);
112 const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);
113 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
114 useEffect(() => {
115 if (!selectedThreadShell || !selectedThread) return;
116 const prefix = questionAttachmentDraftPrefix(
117 selectedThreadShell.environmentId,
118 selectedThreadShell.id,
119 );
120 const retained = new Set(
121 activePendingUserInputs.flatMap((request) =>
122 request.questions.map((question) =>
123 questionAttachmentDraftKey(
124 selectedThreadShell.environmentId,
125 selectedThreadShell.id,
126 request.requestId,
127 question.id,
128 ),
129 ),
130 ),
131 );
132 const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };
133 let changed = false;
134 for (const key of new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)])) {
135 if (!key.startsWith(prefix) || retained.has(key)) continue;
136 if (attachmentDrafts[key]) clearComposerDraft(key);
137 if (key in counts) {
138 delete counts[key];
139 changed = true;
140 }
141 }
142 if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);
143 }, [activePendingUserInputs, attachmentDrafts, selectedThread, selectedThreadShell]);
144 const activePendingUserInputDrafts =
145 activePendingUserInput && selectedThreadShell
146 ? Object.fromEntries(
147 activePendingUserInput.questions.map((question) => {
148 const key = questionAttachmentDraftKey(
149 selectedThreadShell.environmentId,
150 selectedThreadShell.id,
151 activePendingUserInput.requestId,
152 question.id,
153 );
154 const attachments = attachmentDrafts[key]?.attachments ?? [];
155 const uploadInput = {
156 environmentId: selectedThreadShell.environmentId,
157 attachments,
158 serverConfig: questionServerConfigs.get(selectedThreadShell.environmentId) ?? null,
159 states: uploadStates,
160 };
161 return [
162 question.id,
163 {
164 ...userInputDraftsByRequestKey[
165 scopedRequestKey(
166 selectedThreadShell.environmentId,
167 activePendingUserInput.requestId,
168 )
169 ]?.[question.id],
170 attachmentCount: attachments.length,
171 attachmentsBlocked:
172 (attachments.length > 0 &&
173 questionServerConfigs.get(selectedThreadShell.environmentId)?.environment
174 .capabilities.questionAttachments !== true) ||
175 (preparationCounts[key] ?? 0) > 0 ||
176 composerAttachmentsStillUploading(uploadInput) ||
177 composerAttachmentUploadBlockReason({
178 ...uploadInput,
179 connected: true,
180 }) !== null,
181 },
182 ];
183 }),
184 )
185 : {};
186 const activePendingUserInputAnswers = activePendingUserInput
187 ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
188 : null;
189​
190 const onSelectUserInputOption = useCallback(
191 (requestId: RuntimeRequestId, question: ThreadUserInputQuestion, value: string) => {
192 if (!selectedThreadShell) {
193 return;
194 }
195​
196 const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
197 setUserInputDraftOption(requestKey, question, value);
198 },
199 [selectedThreadShell],
200 );
201​
202 const onChangeUserInputCustomAnswer = useCallback(
203 (requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
204 const question = activePendingUserInputs
205 .find((request) => request.requestId === requestId)
206 ?.questions.find((entry) => entry.id === questionId);
207 if (!selectedThreadShell || !question) {
208 return;
209 }
210​
211 const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
212 setUserInputDraftCustomAnswer(requestKey, question, customAnswer);
213 },
214 [activePendingUserInputs, selectedThreadShell],
215 );
216​
217 const onRespondToApproval = useCallback(
218 async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
219 if (!selectedThreadShell) {
220 return;
221 }
222 if (
223 activePendingApprovals.find((approval) => approval.requestId === requestId)
224 ?.responseCapability !== "live"
225 ) {
226 return;
227 }
228​
229 setRespondingApprovalId(requestId);
230 const result = await respondToApproval({
231 environmentId: selectedThreadShell.environmentId,
232 input: {
233 threadId: selectedThreadShell.id,
234 requestId,
235 decision,
236 },
237 });
238 setRespondingApprovalId((current) => (current === requestId ? null : current));
239 return result;
240 },
241 [activePendingApprovals, respondToApproval, selectedThreadShell],
242 );
243​
244 const onSubmitUserInput = useCallback(async () => {
245 if (
246 !selectedThreadShell ||
247 !activePendingUserInput ||
248 activePendingUserInput.responseCapability === "not_resumable" ||
249 !activePendingUserInputAnswers
250 ) {
251 return;
252 }
253​
254 const responseKey = questionAttachmentDraftKey(
255 selectedThreadShell.environmentId,
256 selectedThreadShell.id,
257 activePendingUserInput.requestId,
258 "",
259 );
260 if (userInputResponsesInFlight.current.has(responseKey)) return;
261 const attachmentsByQuestionId = new Map<
262 string,
263 import("@t3tools/contracts").UserInputAttachments[string]
264 >();
265 for (const question of activePendingUserInput.questions) {
266 const key = questionAttachmentDraftKey(
267 selectedThreadShell.environmentId,
268 selectedThreadShell.id,
269 activePendingUserInput.requestId,
270 question.id,
271 );
272 if ((appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0) return;
273 const attachments = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments ?? [];
274 if (attachments.length === 0) continue;
275 if (
276 attachments.some(
277 (attachment) =>
278 !attachment.uploadedAttachmentId ||
279 attachment.uploadEnvironmentId !== selectedThreadShell.environmentId,
280 )
281 ) {
282 Alert.alert(
283 "Attachments are not ready",
284 "Wait for uploads to finish, or retry failed uploads.",
285 );
286 return;
287 }
288 attachmentsByQuestionId.set(
289 question.id,
290 attachments.map((attachment) => ({
291 type: attachment.type,
292 id: attachment.uploadedAttachmentId!,
293 name: attachment.name,
294 mimeType: attachment.mimeType,
295 sizeBytes: attachment.sizeBytes,
296 })),
297 );
298 }
299 userInputResponsesInFlight.current.add(responseKey);
300 setRespondingUserInputId(activePendingUserInput.requestId);
301 const result = await respondToUserInput({
302 environmentId: selectedThreadShell.environmentId,
303 input: {
304 threadId: selectedThreadShell.id,
305 requestId: activePendingUserInput.requestId,
306 answers: activePendingUserInputAnswers,
307 ...(attachmentsByQuestionId.size > 0
308 ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
309 : {}),
310 },
311 });
312 userInputResponsesInFlight.current.delete(responseKey);
313 setRespondingUserInputId((current) =>
314 current === activePendingUserInput.requestId ? null : current,
315 );
316 return result;
317 }, [
318 activePendingUserInput,
319 activePendingUserInputAnswers,
320 respondToUserInput,
321 selectedThreadShell,
322 ]);
323​
324 // Closes an async question without messaging the agent.
325 const onDismissUserInput = useCallback(async () => {
326 if (!selectedThreadShell || !activePendingUserInput) {
327 return;
328 }
329​
330 setRespondingUserInputId(activePendingUserInput.requestId);
331 const result = await dismissUserInput({
332 environmentId: selectedThreadShell.environmentId,
333 input: {
334 threadId: selectedThreadShell.id,
335 requestId: activePendingUserInput.requestId,
336 },
337 });
338 setRespondingUserInputId((current) =>
339 current === activePendingUserInput.requestId ? null : current,
340 );
341 return result;
342 }, [activePendingUserInput, dismissUserInput, selectedThreadShell]);
343​
344 return {
345 activePendingApproval,
346 activePendingUserInput,
347 activePendingUserInputDrafts,
348 activePendingUserInputAnswers,
349 respondingApprovalId,
350 respondingUserInputId,
351 onRespondToApproval,
352 onSelectUserInputOption,
353 onChangeUserInputCustomAnswer,
354 onSubmitUserInput,
355 onDismissUserInput,
356 };