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