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

usePendingThreadRequests.ts

682 lines25.8 KB

1import { msg } from "gt-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m } from "~/i18n/messages";
4import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
5import {
6 AuthOrchestrationOperateScope,
7 type EnvironmentId,
8 type ProviderApprovalDecision,
9 type RuntimeRequestId,
10 type ScopedThreadRef,
11 type ThreadId,
12 type UserInputAttachments,
13} from "@t3tools/contracts";
14import {
15 derivePendingThreadRequests,
16 seedUserInputDraftAnswers,
17 userInputDraftKey,
18} from "@t3tools/client-runtime/state/thread-requests";
19import {
20 isAtomCommandInterrupted,
21 squashAtomCommandFailure,
22} from "@t3tools/client-runtime/state/runtime";
23import { useRef, useState, type RefObject, type SetStateAction } from "react";
24import { useShallow } from "zustand/react/shallow";
25import {
26 type ComposerThreadDraftState,
27 type DraftId,
28 useComposerDraftStore,
29} from "../../composerDraftStore";
30import { useStableCallback } from "../../hooks/useStableCallback";
31import {
32 getUploadedAttachments,
33 refreshExpiredAttachmentUploads,
34 useAttachmentUploadStore,
35} from "../../lib/attachmentUploadQueue";
36import { composerDraftContentChanged } from "./composerSend.logic";
37import {
38 buildPendingUserInputAnswers,
39 setPendingUserInputCustomAnswer,
40 togglePendingUserInputOptionSelection,
41 type PendingUserInputDraftAnswer,
42} from "@t3tools/client-runtime/state/pending-user-input";
43import {
44 carryDisplacedCustomAnswerIntoPrompt,
45 withdrawDisplacedCustomAnswerFromPrompt,
46 derivePendingUserInputProgress,
47 answerContextRecords,
48 projectPendingUserInputAnswer,
49 threadContextsReferencedByAnswer,
50} from "../../pendingUserInput";
51import {
52 questionAttachmentDraftId,
53 usePendingUserInputAnswers,
54 usePendingUserInputQuestionIndex,
55 useQuestionAttachmentPreparation,
56} from "../../questionAttachments";
57import {
58 derivePendingApprovals,
59 derivePendingUserInputs,
60 type PendingUserInput,
61} from "../../session-logic";
62import { readEnvironmentScope } from "../../state/session";
63import { threadEnvironment } from "../../state/threads";
64import { useAtomCommand } from "../../state/use-atom-command";
65import { useOrchestrationCommand } from "../../state/use-orchestration-command";
66import { toastManager } from "../ui/toast";
67​
68import type { ChatComposerHandle } from "./ChatComposer";
69​
70const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
71const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
72const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
73const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
74​
75interface PendingUserInputDraftScope {
76 readonly environmentId: EnvironmentId;
77 readonly activeThreadId: ThreadId | null;
78 readonly activePendingUserInput: PendingUserInput | null;
79 readonly supportsQuestionAttachments: boolean;
81​
82function pendingUserInputDraftKeys(scope: PendingUserInputDraftScope) {
83 const { environmentId, activeThreadId, activePendingUserInput } = scope;
84 return {
85 requestKey: userInputDraftKey(environmentId, activeThreadId, activePendingUserInput?.requestId),
86 questionKeys:
87 activeThreadId && activePendingUserInput
88 ? activePendingUserInput.questions.map((question) =>
89 questionAttachmentDraftId(
90 environmentId,
91 activeThreadId,
92 activePendingUserInput.requestId,
93 question.id,
94 ),
95 )
96 : [],
97 };
99​
100const selectQuestionComposerDrafts =
101 (keys: ReadonlyArray<string>) =>
102 (state: { readonly draftsByThreadKey: Record<string, ComposerThreadDraftState> }) =>
103 Object.fromEntries(keys.map((key) => [key, state.draftsByThreadKey[key]]));
104​
105const selectQuestionUploadsBlocked =
106 (
107 keys: ReadonlyArray<string>,
108 questionComposerDrafts: Record<string, ComposerThreadDraftState | undefined>,
109 environmentId: EnvironmentId,
110 ) =>
111 (state: ReturnType<typeof useAttachmentUploadStore.getState>) =>
112 Object.fromEntries(
113 keys.map((key) => {
114 const draft = questionComposerDrafts[key];
115 const attachments = draft ? [...draft.images, ...draft.files] : [];
116 return [
117 key,
118 attachments.some((attachment) => {
119 const upload = state.uploadsByImageId[attachment.id];
120 return upload?.status !== "ready" || upload.environmentId !== environmentId;
121 }),
122 ];
123 }),
124 );
125​
126const selectQuestionPreparations =
127 (keys: ReadonlyArray<string>) => (state: { readonly counts: Record<string, number> }) =>
128 Object.fromEntries(keys.map((key) => [key, state.counts[key] ?? 0]));
129​
130function deriveActivePendingDraft(
131 scope: PendingUserInputDraftScope,
132 storedPendingAnswerDrafts: Record<string, PendingUserInputDraftAnswer>,
133 activePendingQuestionIndex: number,
134 questionComposerDrafts: Record<string, ComposerThreadDraftState | undefined>,
135 questionUploadsBlocked: Record<string, boolean>,
136 questionPreparations: Record<string, number>,
137) {
138 const { environmentId, activeThreadId, activePendingUserInput, supportsQuestionAttachments } =
139 scope;
140 // Suggested answers are shown until the user edits them; only edits are stored.
141 const activePendingAnswerDrafts: Record<string, PendingUserInputDraftAnswer> =
142 activePendingUserInput
143 ? seedUserInputDraftAnswers(activePendingUserInput.questions, storedPendingAnswerDrafts)
144 : storedPendingAnswerDrafts;
145 const activePendingDraftAnswers =
146 !activePendingUserInput || !activeThreadId
147 ? EMPTY_PENDING_USER_INPUT_ANSWERS
148 : Object.fromEntries(
149 activePendingUserInput.questions.map((question) => {
150 const key = questionAttachmentDraftId(
151 environmentId,
152 activeThreadId,
153 activePendingUserInput.requestId,
154 question.id,
155 );
156 const draft = questionComposerDrafts[key];
157 const attachments = draft ? [...draft.images, ...draft.files] : [];
158 return [
159 question.id,
160 {
161 ...activePendingAnswerDrafts[question.id],
162 attachmentCount: attachments.length,
163 attachmentsBlocked:
164 (attachments.length > 0 && !supportsQuestionAttachments) ||
165 (questionPreparations[key] ?? 0) > 0 ||
166 questionUploadsBlocked[key] === true,
167 },
168 ];
169 }),
170 );
171 const activePendingProgress = activePendingUserInput
172 ? derivePendingUserInputProgress(
173 activePendingUserInput.questions,
174 activePendingDraftAnswers,
175 activePendingQuestionIndex,
176 )
177 : null;
178 const activePendingResolvedAnswers = activePendingUserInput
179 ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers)
180 : null;
181 return {
182 activePendingDraftAnswers,
183 activePendingQuestionIndex,
184 activePendingProgress,
185 activePendingResolvedAnswers,
186 };
188​
189/**
190 * The open question's answers, position and progress. These change on every keystroke, so
191 * the composer subscribes to them rather than the chat view.
192 */
193export function usePendingUserInputDraft(scope: PendingUserInputDraftScope) {
194 const { requestKey, questionKeys: keys } = pendingUserInputDraftKeys(scope);
195 const storedPendingAnswerDrafts = usePendingUserInputAnswers(
196 (state) => state[requestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS,
197 );
198 const activePendingQuestionIndex = usePendingUserInputQuestionIndex(
199 (state) => state[requestKey] ?? 0,
200 );
201 const questionComposerDrafts = useComposerDraftStore(
202 useShallow(selectQuestionComposerDrafts(keys)),
203 );
204 const questionUploadsBlocked = useAttachmentUploadStore(
205 useShallow(selectQuestionUploadsBlocked(keys, questionComposerDrafts, scope.environmentId)),
206 );
207 const questionPreparations = useQuestionAttachmentPreparation(
208 useShallow(selectQuestionPreparations(keys)),
209 );
210 return deriveActivePendingDraft(
211 scope,
212 storedPendingAnswerDrafts,
213 activePendingQuestionIndex,
214 questionComposerDrafts,
215 questionUploadsBlocked,
216 questionPreparations,
217 );
219​
220// Request callbacks read drafts when called, so the chat view never subscribes to them.
221function readPendingUserInputDraft(scope: PendingUserInputDraftScope) {
222 const { requestKey, questionKeys: keys } = pendingUserInputDraftKeys(scope);
223 const questionComposerDrafts = selectQuestionComposerDrafts(keys)(
224 useComposerDraftStore.getState(),
225 );
226 return deriveActivePendingDraft(
227 scope,
228 usePendingUserInputAnswers.getState()[requestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS,
229 usePendingUserInputQuestionIndex.getState()[requestKey] ?? 0,
230 questionComposerDrafts,
231 selectQuestionUploadsBlocked(
232 keys,
233 questionComposerDrafts,
234 scope.environmentId,
235 )(useAttachmentUploadStore.getState()),
236 selectQuestionPreparations(keys)(useQuestionAttachmentPreparation.getState()),
237 );
239​
240function makePendingCustomAnswerSetter(input: {
241 readonly activePendingUserInput: PendingUserInput | null;
242 readonly activePendingRequestKey: string;
243 readonly writePrompt: (prompt: string) => void;
244 readonly withdrawRestoredAnswer: (questionId: string, value: string) => void;
245 readonly setPendingUserInputAnswersByRequestId: (
246 update: SetStateAction<Record<string, Record<string, PendingUserInputDraftAnswer>>>,
247 ) => void;
248}) {
249 return (questionId: string, value: string) => {
250 const { activePendingUserInput, activePendingRequestKey } = input;
251 if (!activePendingUserInput) {
252 return;
253 }
254 const question = activePendingUserInput.questions.find((entry) => entry.id === questionId);
255 if (!question || question.allowCustomAnswer === false) {
256 return;
257 }
258 input.writePrompt(value);
259 input.withdrawRestoredAnswer(questionId, value);
260 input.setPendingUserInputAnswersByRequestId((existing) => ({
261 ...existing,
262 [activePendingRequestKey]: {
263 ...existing[activePendingRequestKey],
264 [questionId]: setPendingUserInputCustomAnswer(
265 question,
266 existing[activePendingRequestKey]?.[questionId],
267 value,
268 ),
269 },
270 }));
271 // Resetting selection before rendering can re-enter Lexical with stale skill-token offsets.
272 };
274​
275export function usePendingThreadRequests(input: {
276 readonly environmentId: EnvironmentId;
277 readonly activeThreadId: ThreadId | null;
278 readonly serverProjection: ThreadStructure | null;
279 readonly supportsQuestionAttachments: boolean;
280 readonly composerDraftTarget: ScopedThreadRef | DraftId;
281 readonly setComposerDraftPrompt: (target: ScopedThreadRef | DraftId, prompt: string) => void;
282 readonly promptRef: { current: string };
283 readonly composerRef: RefObject<ChatComposerHandle | null>;
284 readonly setThreadError: (threadId: ThreadId, error: string | null) => void;
285}) {
286 const {
287 environmentId,
288 activeThreadId,
289 serverProjection,
290 supportsQuestionAttachments,
291 composerDraftTarget,
292 setComposerDraftPrompt,
293 promptRef,
294 composerRef,
295 setThreadError,
296 } = input;
297 const respondToThreadApproval = useOrchestrationCommand(threadEnvironment.respondToApproval, {
298 reportFailure: false,
299 });
300 const respondToThreadUserInput = useOrchestrationCommand(threadEnvironment.respondToUserInput, {
301 reportFailure: false,
302 });
303 const dismissThreadUserInput = useAtomCommand(threadEnvironment.dismissUserInput, {
304 reportFailure: false,
305 });
306 const userInputResponsesInFlight = useRef(new Set<string>());
307 // In the order the text went into the thread draft, which is how a copy is found again.
308 const displacedAnswers = useRef<
309 Array<{ readonly draft: string; readonly key: string; readonly text: string }>
310 >([]);
311 // This hook outlives a thread switch, and each thread has its own draft.
312 const displacedDraftKey =
313 typeof composerDraftTarget === "string"
314 ? composerDraftTarget
315 : `${composerDraftTarget.environmentId}:${composerDraftTarget.threadId}`;
316 const [respondingRequestIds, setRespondingRequestIds] = useState<RuntimeRequestId[]>([]);
317 const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
318 RuntimeRequestId[]
319 >([]);
320 const setPendingUserInputAnswersByRequestId = usePendingUserInputAnswers.setState;
321 const setPendingUserInputQuestionIndexByRequestId = usePendingUserInputQuestionIndex.setState;
322 const pendingRequests =
323 serverProjection !== null && serverProjection.thread.id === activeThreadId
324 ? derivePendingThreadRequests(serverProjection)
325 : NO_PENDING_REQUESTS;
326 // The projection changes on every streamed event, so shared empties keep the
327 // composer and approval panel from re-rendering while nothing is pending.
328 const pendingApprovals =
329 pendingRequests.approvals.length === 0
330 ? NO_PENDING_APPROVALS
331 : derivePendingApprovals(pendingRequests.approvals);
332 const pendingUserInputs =
333 pendingRequests.userInputs.length === 0
334 ? NO_PENDING_USER_INPUTS
335 : derivePendingUserInputs(pendingRequests.userInputs);
336 const activePendingUserInput = pendingUserInputs[0] ?? null;
337 const activePendingRequestKey = userInputDraftKey(
338 environmentId,
339 activeThreadId,
340 activePendingUserInput?.requestId,
341 );
342 const draftScope = {
343 environmentId,
344 activeThreadId,
345 activePendingUserInput,
346 supportsQuestionAttachments,
347 };
348 const activePendingIsResponding = activePendingUserInput
349 ? activePendingUserInput.responseCapability === "not_resumable" ||
350 respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
351 : false;
352 const activePendingApproval = pendingApprovals[0] ?? null;
353​
354 const onRespondToApproval = async (
355 requestId: RuntimeRequestId,
356 decision: ProviderApprovalDecision,
357 feedback?: string,
358 ) => {
359 if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
360 return;
361 if (
362 pendingApprovals.find((approval) => approval.requestId === requestId)?.responseCapability !==
363 "live"
364 )
365 return;
366​
367 setRespondingRequestIds((existing) =>
368 existing.includes(requestId) ? existing : [...existing, requestId],
369 );
370 const result = await respondToThreadApproval({
371 environmentId,
372 input: {
373 threadId: activeThreadId,
374 requestId,
375 decision,
376 ...(feedback === undefined ? {} : { feedback }),
377 },
378 });
379 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
380 const error = squashAtomCommandFailure(result);
381 setThreadError(
382 activeThreadId,
383 thrownErrorMessage(error, m) ?? m(msg("Failed to submit approval decision.")),
384 );
385 }
386 setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
387 return result;
388 };
389 const onRespondToApprovalStable = useStableCallback(onRespondToApproval);
390​
391 const onRespondToUserInput = async (
392 requestId: RuntimeRequestId,
393 answers: Record<string, unknown>,
394 ) => {
395 if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
396 return;
397 const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId);
398 if (!pendingInput || pendingInput.responseCapability === "not_resumable") return;
399 const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
400 if (userInputResponsesInFlight.current.has(responseKey)) return;
401 userInputResponsesInFlight.current.add(responseKey);
402 const answerDraftKey = userInputDraftKey(environmentId, activeThreadId, requestId);
403 const answerDraftBeforePreparation = usePendingUserInputAnswers.getState()[answerDraftKey];
404 setRespondingUserInputRequestIds((existing) =>
405 existing.includes(requestId) ? existing : [...existing, requestId],
406 );
407 const prepareAndRespond = async () => {
408 const attachmentsByQuestionId = new Map<string, UserInputAttachments[string]>();
409 const providerAnswers = { ...answers };
410 const threadDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget);
411 const questionDrafts = pendingInput.questions.map((question) => {
412 const target = questionAttachmentDraftId(
413 environmentId,
414 activeThreadId,
415 requestId,
416 question.id,
417 );
418 const draft = useComposerDraftStore.getState().getComposerDraft(target);
419 return { question, target, draft };
420 });
421 for (const { question, target, draft } of questionDrafts) {
422 if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
423 // A skipped optional question has no entry and must not gain an undefined one.
424 if (Object.hasOwn(answers, question.id)) {
425 providerAnswers[question.id] = projectPendingUserInputAnswer(
426 answers[question.id],
427 answerContextRecords(draft, threadDraft),
428 );
429 }
430 const attachments = draft ? [...draft.images, ...draft.files] : [];
431 if (attachments.length === 0) continue;
432 await refreshExpiredAttachmentUploads({
433 environmentId,
434 images: attachments,
435 draftTarget: target,
436 });
437 if (
438 composerDraftContentChanged(
439 draft,
440 useComposerDraftStore.getState().getComposerDraft(target),
441 )
442 ) {
443 setThreadError(
444 activeThreadId,
445 m(msg("Answer changed while preparing attachments. Review it and send again.")),
446 );
447 return;
448 }
449 const uploaded = getUploadedAttachments({ environmentId, images: attachments });
450 if (!uploaded) {
451 setThreadError(
452 activeThreadId,
453 m(msg("Wait for attachments to finish uploading, or remove failed uploads.")),
454 );
455 return;
456 }
457 attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]);
458 }
459 if (
460 usePendingUserInputAnswers.getState()[answerDraftKey] !== answerDraftBeforePreparation ||
461 questionDrafts.some(
462 ({ target, draft }) =>
463 (useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0 ||
464 composerDraftContentChanged(
465 draft,
466 useComposerDraftStore.getState().getComposerDraft(target),
467 ),
468 )
469 ) {
470 setThreadError(
471 activeThreadId,
472 m(msg("Answer changed while preparing attachments. Review it and send again.")),
473 );
474 return;
475 }
476 const result = await respondToThreadUserInput({
477 environmentId,
478 input: {
479 threadId: activeThreadId,
480 requestId,
481 answers: providerAnswers,
482 ...(attachmentsByQuestionId.size > 0
483 ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
484 : {}),
485 },
486 });
487 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
488 const error = squashAtomCommandFailure(result);
489 setThreadError(
490 activeThreadId,
491 thrownErrorMessage(error, m) ?? m(msg("Failed to submit user input.")),
492 );
493 }
494 return result;
495 };
496 return prepareAndRespond().finally(() => {
497 userInputResponsesInFlight.current.delete(responseKey);
498 setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
499 });
500 };
501​
502 const onDismissUserInput = async (requestId: RuntimeRequestId) => {
503 if (!activeThreadId) return;
504​
505 setRespondingUserInputRequestIds((existing) =>
506 existing.includes(requestId) ? existing : [...existing, requestId],
507 );
508 const result = await dismissThreadUserInput({
509 environmentId,
510 input: { threadId: activeThreadId, requestId },
511 });
512 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
513 const error = squashAtomCommandFailure(result);
514 setThreadError(
515 activeThreadId,
516 thrownErrorMessage(error, m) ?? m(msg("Failed to dismiss the question.")),
517 );
518 }
519 setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
520 return result;
521 };
522 const onDismissUserInputStable = useStableCallback(onDismissUserInput);
523​
524 const setActivePendingUserInputQuestionIndex = (nextQuestionIndex: number) => {
525 if (!activePendingUserInput) {
526 return;
527 }
528 setPendingUserInputQuestionIndexByRequestId((existing) => ({
529 ...existing,
530 [activePendingRequestKey]: nextQuestionIndex,
531 }));
532 };
533​
534 const onSelectActivePendingUserInputOption = (questionId: string, optionValue: string) => {
535 if (!activePendingUserInput) {
536 return;
537 }
538 // The option replaces the custom answer. Anything typed there is the
539 // user's text, so it goes back to the thread draft instead of vanishing.
540 const displacedAnswer =
541 readPendingUserInputDraft(draftScope).activePendingDraftAnswers[questionId]?.customAnswer;
542 const currentPrompt =
543 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
544 const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer);
545 if (nextPrompt !== currentPrompt) {
546 setComposerDraftPrompt(composerDraftTarget, nextPrompt);
547 displacedAnswers.current.push({
548 draft: displacedDraftKey,
549 key: `${activePendingRequestKey}:${questionId}`,
550 text: displacedAnswer ?? "",
551 });
552 toastManager.add({
553 type: "info",
554 title: m(msg("Your typed text was set aside")),
555 description: m(msg("It will be back in the composer once the question is answered.")),
556 data: { threadRef: activeThreadId ? { environmentId, threadId: activeThreadId } : null },
557 });
558 if (activeThreadId) {
559 const store = useComposerDraftStore.getState();
560 const questionTarget = questionAttachmentDraftId(
561 environmentId,
562 activeThreadId,
563 activePendingUserInput.requestId,
564 questionId,
565 );
566 store.addThreadContexts(
567 composerDraftTarget,
568 threadContextsReferencedByAnswer(
569 displacedAnswer ?? "",
570 store.getComposerDraft(questionTarget)?.threadContexts ?? [],
571 ),
572 { appendReference: false },
573 );
574 }
575 }
576 setPendingUserInputAnswersByRequestId((existing) => {
577 const question = activePendingUserInput.questions.find((entry) => entry.id === questionId);
578 if (!question) {
579 return existing;
580 }
581​
582 return {
583 ...existing,
584 [activePendingRequestKey]: {
585 ...existing[activePendingRequestKey],
586 [questionId]: togglePendingUserInputOptionSelection(
587 question,
588 existing[activePendingRequestKey]?.[questionId],
589 optionValue,
590 ),
591 },
592 };
593 });
594 promptRef.current = "";
595 composerRef.current?.resetCursorState({ cursor: 0 });
596 };
597 const onSelectActivePendingUserInputOptionStable = useStableCallback(
598 onSelectActivePendingUserInputOption,
599 );
600​
601 const writePrompt = useStableCallback((prompt: string) => {
602 promptRef.current = prompt;
603 });
604 // Undo can put set-aside text back into the answer; left in the draft too, it is sent twice.
605 const withdrawRestoredAnswer = useStableCallback((questionId: string, value: string) => {
606 const key = `${activePendingRequestKey}:${questionId}`;
607 const entries = displacedAnswers.current;
608 const index = entries.findLastIndex(
609 (entry) =>
610 entry.draft === displacedDraftKey &&
611 entry.key === key &&
612 entry.text.trim() === value.trim(),
613 );
614 const displaced = entries[index];
615 if (displaced === undefined) return;
616 const later = entries
617 .slice(index + 1)
618 .filter((entry) => entry.draft === displaced.draft)
619 .map((entry) => entry.text);
620 displacedAnswers.current = entries.filter((entry) => entry !== displaced);
621 const currentPrompt =
622 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
623 const nextPrompt = withdrawDisplacedCustomAnswerFromPrompt(
624 currentPrompt,
625 displaced.text,
626 later,
627 );
628 if (nextPrompt !== currentPrompt) setComposerDraftPrompt(composerDraftTarget, nextPrompt);
629 });
630 const onChangeActivePendingUserInputCustomAnswer = makePendingCustomAnswerSetter({
631 activePendingUserInput,
632 activePendingRequestKey,
633 writePrompt,
634 withdrawRestoredAnswer,
635 setPendingUserInputAnswersByRequestId,
636 });
637​
638 const onAdvanceActivePendingUserInput = () => {
639 if (!activePendingUserInput || activePendingUserInput.responseCapability === "not_resumable") {
640 return;
641 }
642 const { activePendingProgress, activePendingResolvedAnswers } =
643 readPendingUserInputDraft(draftScope);
644 if (!activePendingProgress) return;
645 if (activePendingProgress.isLastQuestion) {
646 if (activePendingResolvedAnswers) {
647 void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers);
648 }
649 return;
650 }
651 if (!activePendingProgress.canAdvance) return;
652 setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1);
653 };
654 const onAdvanceActivePendingUserInputStable = useStableCallback(onAdvanceActivePendingUserInput);
655​
656 const onPreviousActivePendingUserInputQuestion = () => {
657 const { activePendingProgress } = readPendingUserInputDraft(draftScope);
658 if (!activePendingProgress) {
659 return;
660 }
661 setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0));
662 };
663 const onPreviousActivePendingUserInputQuestionStable = useStableCallback(
664 onPreviousActivePendingUserInputQuestion,
665 );
666​
667 return {
668 pendingApprovals,
669 pendingUserInputs,
670 activePendingApproval,
671 activePendingUserInput,
672 activePendingIsResponding,
673 respondingRequestIds,
674 onRespondToApproval: onRespondToApprovalStable,
675 onDismissUserInput: onDismissUserInputStable,
676 onSelectActivePendingUserInputOption: onSelectActivePendingUserInputOptionStable,
677 onChangeActivePendingUserInputCustomAnswer,
678 onAdvanceActivePendingUserInput,
679 onAdvanceActivePendingUserInputStable,
680 onPreviousActivePendingUserInputQuestion: onPreviousActivePendingUserInputQuestionStable,
681 };