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

use-selected-thread-requests.ts

483 lines16.3 KB

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