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