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

use-selected-thread-requests.ts

453 lines15.4 KB

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, useRef, useState } from "react";
20​
21import {
22 type EnvironmentId,
23 type ProviderApprovalDecision,
24 type RuntimeRequestId,
25 type ThreadId,
26} from "@t3tools/contracts";
27import {
28 type PendingThreadRequests,
29 type ThreadUserInputQuestion,
30 onThreadRequestsResolved,
31 pruneResolvedUserInputDrafts,
32 resolvedQuestionDraftKeys,
33 seedUserInputDraftAnswers,
34 userInputDraftKey,
35} from "@t3tools/client-runtime/state/thread-requests";
36import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
37import { Atom } from "effect/reactivity";
38​
39import { environmentThreadDetails, threadEnvironment } from "../state/threads";
40import {
41 buildPendingUserInputAnswers,
42 setPendingUserInputCustomAnswer,
43 togglePendingUserInputOptionSelection,
44 type PendingUserInputDraftAnswer,
45} from "../lib/threadActivity";
46import { appAtomRegistry } from "./atom-registry";
47import { useSelectedThreadPendingRequests } from "./use-thread-detail";
48import { useThreadSelection } from "./use-thread-selection";
49import { useAtomCommand } from "./use-atom-command";
50import { readEnvironmentScope } from "./session";
51​
52const EMPTY_PENDING_REQUESTS: PendingThreadRequests = { approvals: [], userInputs: [] };
53​
54const userInputDraftsByRequestKeyAtom = Atom.make<
55 Record<string, Record<string, PendingUserInputDraftAnswer>>
56>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
57​
58// Writes start from the suggested answer the user was looking at.
59function seededDraft(
60 drafts: Record<string, PendingUserInputDraftAnswer> | undefined,
61 question: ThreadUserInputQuestion,
62): PendingUserInputDraftAnswer | undefined {
63 return seedUserInputDraftAnswers([question], drafts ?? {})[question.id];
65​
66function setUserInputDraftOption(
67 requestKey: string,
68 question: ThreadUserInputQuestion,
69 value: string,
70): void {
71 const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
72 appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
73 ...current,
74 [requestKey]: {
75 ...current[requestKey],
76 [question.id]: togglePendingUserInputOptionSelection(
77 question,
78 seededDraft(current[requestKey], question),
79 value,
80 ),
81 },
82 });
84​
85function setUserInputDraftCustomAnswer(
86 requestKey: string,
87 question: ThreadUserInputQuestion,
88 customAnswer: string,
89): void {
90 const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
91 appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
92 ...current,
93 [requestKey]: {
94 ...current[requestKey],
95 [question.id]: setPendingUserInputCustomAnswer(
96 question,
97 seededDraft(current[requestKey], question),
98 customAnswer,
99 ),
100 },
101 });
103​
104/** Drops a thread's answer and attachment drafts for every request outside `pendingRequestIds`. */
105function pruneResolvedRequestDrafts(
106 environmentId: EnvironmentId,
107 threadId: ThreadId,
108 pendingRequestIds: ReadonlyArray<RuntimeRequestId>,
109): void {
110 const drafts = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
111 const prunedDrafts = pruneResolvedUserInputDrafts(
112 drafts,
113 environmentId,
114 threadId,
115 pendingRequestIds,
116 );
117 if (prunedDrafts !== drafts) appAtomRegistry.set(userInputDraftsByRequestKeyAtom, prunedDrafts);
118​
119 const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
120 const attachmentDrafts = appAtomRegistry.get(questionAttachmentDraftsAtom(prefix));
121 const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };
122 let changed = false;
123 for (const key of resolvedQuestionDraftKeys(
124 new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)]),
125 prefix,
126 pendingRequestIds,
127 )) {
128 if (attachmentDrafts[key]) clearComposerDraft(key);
129 if (key in counts) {
130 delete counts[key];
131 changed = true;
132 }
133 }
134 if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);
136​
137// Resolution can come from anywhere: another device, an interrupt, the turn
138// ending, or a reload over drafts for requests that resolved meanwhile.
139onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) =>
140 pruneResolvedRequestDrafts(environmentId, threadId, pendingRequestIds),
141);
142​
143/**
144 * Drops `answeredRequestId`'s drafts as soon as the server accepts the
145 * response, before the projection push that resolves it lands.
146 */
147function collectAnsweredRequestDrafts(
148 environmentId: EnvironmentId,
149 threadId: ThreadId,
150 answeredRequestId: RuntimeRequestId,
151) {
152 const current = appAtomRegistry.get(
153 environmentThreadDetails.pendingRequestsAtom({ environmentId, threadId }),
154 );
155 // Missing detail is not resolution.
156 if (current === null) return;
157 pruneResolvedRequestDrafts(
158 environmentId,
159 threadId,
160 [...current.approvals, ...current.userInputs]
161 .map((request) => request.requestId)
162 .filter((requestId) => requestId !== answeredRequestId),
163 );
165​
166export function useSelectedThreadRequests() {
167 const respondToApproval = useAtomCommand(
168 threadEnvironment.respondToApproval,
169 "thread approval response",
170 );
171 const respondToUserInput = useAtomCommand(
172 threadEnvironment.respondToUserInput,
173 "thread user input response",
174 );
175 const dismissUserInput = useAtomCommand(
176 threadEnvironment.dismissUserInput,
177 "thread user input dismissal",
178 );
179 const { selectedThread: selectedThreadShell } = useThreadSelection();
180 const pendingRequests = useSelectedThreadPendingRequests();
181 const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
182 const userInputResponsesInFlight = useRef(new Set<string>());
183 const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
184 const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
185​
186 const activePendingApprovals = pendingRequests?.approvals ?? EMPTY_PENDING_REQUESTS.approvals;
187 const activePendingApproval = activePendingApprovals[0] ?? null;
188 const activePendingUserInputs = pendingRequests?.userInputs ?? EMPTY_PENDING_REQUESTS.userInputs;
189 const activePendingUserInput = activePendingUserInputs[0] ?? null;
190 const questionServerConfigs = useServerConfigs();
191 const attachmentDrafts = useAtomValue(
192 questionAttachmentDraftsAtom(
193 selectedThreadShell
194 ? questionAttachmentDraftPrefix(selectedThreadShell.environmentId, selectedThreadShell.id)
195 : "",
196 ),
197 );
198 const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);
199 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
200 // Suggested answers are shown until the user edits them; only edits are stored.
201 const activePendingUserInputAnswerDrafts =
202 activePendingUserInput && selectedThreadShell
203 ? seedUserInputDraftAnswers(
204 activePendingUserInput.questions,
205 userInputDraftsByRequestKey[
206 userInputDraftKey(
207 selectedThreadShell.environmentId,
208 selectedThreadShell.id,
209 activePendingUserInput.requestId,
210 )
211 ] ?? {},
212 )
213 : {};
214 const activePendingUserInputDrafts =
215 activePendingUserInput && selectedThreadShell
216 ? Object.fromEntries(
217 activePendingUserInput.questions.map((question) => {
218 const key = questionAttachmentDraftKey(
219 selectedThreadShell.environmentId,
220 selectedThreadShell.id,
221 activePendingUserInput.requestId,
222 question.id,
223 );
224 const attachments = attachmentDrafts[key]?.attachments ?? [];
225 const uploadInput = {
226 environmentId: selectedThreadShell.environmentId,
227 attachments,
228 serverConfig: questionServerConfigs.get(selectedThreadShell.environmentId) ?? null,
229 states: uploadStates,
230 };
231 return [
232 question.id,
233 {
234 ...activePendingUserInputAnswerDrafts[question.id],
235 attachmentCount: attachments.length,
236 attachmentsBlocked:
237 (attachments.length > 0 &&
238 questionServerConfigs.get(selectedThreadShell.environmentId)?.environment
239 .capabilities.questionAttachments !== true) ||
240 (preparationCounts[key] ?? 0) > 0 ||
241 composerAttachmentsStillUploading(uploadInput) ||
242 composerAttachmentUploadBlockReason({
243 ...uploadInput,
244 connected: true,
245 }) !== null,
246 },
247 ];
248 }),
249 )
250 : {};
251 const activePendingUserInputAnswers = activePendingUserInput
252 ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
253 : null;
254​
255 const onSelectUserInputOption = useCallback(
256 (requestId: RuntimeRequestId, question: ThreadUserInputQuestion, value: string) => {
257 if (!selectedThreadShell) {
258 return;
259 }
260​
261 const requestKey = userInputDraftKey(
262 selectedThreadShell.environmentId,
263 selectedThreadShell.id,
264 requestId,
265 );
266 setUserInputDraftOption(requestKey, question, value);
267 },
268 [selectedThreadShell],
269 );
270​
271 const onChangeUserInputCustomAnswer = useCallback(
272 (requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
273 const question = activePendingUserInputs
274 .find((request) => request.requestId === requestId)
275 ?.questions.find((entry) => entry.id === questionId);
276 if (!selectedThreadShell || !question) {
277 return;
278 }
279​
280 const requestKey = userInputDraftKey(
281 selectedThreadShell.environmentId,
282 selectedThreadShell.id,
283 requestId,
284 );
285 setUserInputDraftCustomAnswer(requestKey, question, customAnswer);
286 },
287 [activePendingUserInputs, selectedThreadShell],
288 );
289​
290 const onRespondToApproval = useCallback(
291 async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision, feedback?: string) => {
292 if (
293 !selectedThreadShell ||
294 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
295 ) {
296 return;
297 }
298 if (
299 activePendingApprovals.find((approval) => approval.requestId === requestId)
300 ?.responseCapability !== "live"
301 ) {
302 return;
303 }
304​
305 setRespondingApprovalId(requestId);
306 const result = await respondToApproval({
307 environmentId: selectedThreadShell.environmentId,
308 input: {
309 threadId: selectedThreadShell.id,
310 requestId,
311 decision,
312 ...(feedback === undefined ? {} : { feedback }),
313 },
314 });
315 setRespondingApprovalId((current) => (current === requestId ? null : current));
316 return result;
317 },
318 [activePendingApprovals, respondToApproval, selectedThreadShell],
319 );
320​
321 const onSubmitUserInput = useCallback(async () => {
322 if (
323 !selectedThreadShell ||
324 !activePendingUserInput ||
325 activePendingUserInput.responseCapability === "not_resumable" ||
326 !activePendingUserInputAnswers ||
327 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
328 ) {
329 return;
330 }
331​
332 const responseKey = questionAttachmentDraftKey(
333 selectedThreadShell.environmentId,
334 selectedThreadShell.id,
335 activePendingUserInput.requestId,
336 "",
337 );
338 if (userInputResponsesInFlight.current.has(responseKey)) return;
339 const attachmentsByQuestionId = new Map<
340 string,
341 import("@t3tools/contracts").UserInputAttachments[string]
342 >();
343 for (const question of activePendingUserInput.questions) {
344 const key = questionAttachmentDraftKey(
345 selectedThreadShell.environmentId,
346 selectedThreadShell.id,
347 activePendingUserInput.requestId,
348 question.id,
349 );
350 if ((appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0) return;
351 const attachments = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments ?? [];
352 if (attachments.length === 0) continue;
353 if (
354 attachments.some(
355 (attachment) =>
356 !attachment.uploadedAttachmentId ||
357 attachment.uploadEnvironmentId !== selectedThreadShell.environmentId,
358 )
359 ) {
360 Dialog.alert(
361 "Attachments are not ready",
362 "Wait for uploads to finish, or retry failed uploads.",
363 );
364 return;
365 }
366 attachmentsByQuestionId.set(
367 question.id,
368 attachments.map((attachment) => ({
369 type: attachment.type,
370 id: attachment.uploadedAttachmentId!,
371 name: attachment.name,
372 mimeType: attachment.mimeType,
373 sizeBytes: attachment.sizeBytes,
374 })),
375 );
376 }
377 userInputResponsesInFlight.current.add(responseKey);
378 setRespondingUserInputId(activePendingUserInput.requestId);
379 const result = await respondToUserInput({
380 environmentId: selectedThreadShell.environmentId,
381 input: {
382 threadId: selectedThreadShell.id,
383 requestId: activePendingUserInput.requestId,
384 answers: activePendingUserInputAnswers,
385 ...(attachmentsByQuestionId.size > 0
386 ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
387 : {}),
388 },
389 });
390 userInputResponsesInFlight.current.delete(responseKey);
391 setRespondingUserInputId((current) =>
392 current === activePendingUserInput.requestId ? null : current,
393 );
394 if (result._tag === "Success") {
395 collectAnsweredRequestDrafts(
396 selectedThreadShell.environmentId,
397 selectedThreadShell.id,
398 activePendingUserInput.requestId,
399 );
400 }
401 return result;
402 }, [
403 activePendingUserInput,
404 activePendingUserInputAnswers,
405 respondToUserInput,
406 selectedThreadShell,
407 ]);
408​
409 const onDismissUserInput = useCallback(async () => {
410 if (
411 !selectedThreadShell ||
412 !activePendingUserInput ||
413 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
414 ) {
415 return;
416 }
417​
418 setRespondingUserInputId(activePendingUserInput.requestId);
419 const result = await dismissUserInput({
420 environmentId: selectedThreadShell.environmentId,
421 input: {
422 threadId: selectedThreadShell.id,
423 requestId: activePendingUserInput.requestId,
424 },
425 });
426 setRespondingUserInputId((current) =>
427 current === activePendingUserInput.requestId ? null : current,
428 );
429 if (result._tag === "Success") {
430 collectAnsweredRequestDrafts(
431 selectedThreadShell.environmentId,
432 selectedThreadShell.id,
433 activePendingUserInput.requestId,
434 );
435 }
436 return result;
437 }, [activePendingUserInput, dismissUserInput, selectedThreadShell]);
438​
439 return {
440 activePendingApproval,
441 activePendingApprovals,
442 activePendingUserInput,
443 activePendingUserInputDrafts,
444 activePendingUserInputAnswers,
445 respondingApprovalId,
446 respondingUserInputId,
447 onRespondToApproval,
448 onSelectUserInputOption,
449 onChangeUserInputCustomAnswer,
450 onSubmitUserInput,
451 onDismissUserInput,
452 };