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