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

use-selected-thread-requests.ts

344 lines12.0 KB

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