The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): move pending approvals and questions out of ChatView (#20161)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 17:39 UTC
043bc031e485debdba5dcd62e5894a8725ff396b
2 files changed
+597
-483
apps/web/src/components/ChatView.tsx
+46
-483
@@ -25,6 +25,7 @@ import {
25
import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";
26
import { useScratchProject } from "../hooks/useScratchProject";
27
import { useStableCallback } from "../hooks/useStableCallback";
28
+import { usePendingThreadRequests } from "./chat/usePendingThreadRequests";
29
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
30
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
31
import {
@@ -41,13 +42,6 @@ import { feedbackBannerItem } from "./chat/ComposerFeedback";
42
import { usageLimitsBannerItem } from "./chat/ComposerUsageLimits";
43
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
44
import * as Schema from "effect/Schema";
44
-import {
45
- questionAttachmentDraftId,
46
- questionAttachmentDraftPrefix,
47
- clearQuestionAttachmentDraft,
48
- useQuestionAttachmentPreparation,
49
-} from "../questionAttachments";
50
-import { useAttachmentUploadStore } from "../lib/attachmentUploadQueue";
45
import {
46
AuthOrchestrationOperateScope,
47
AuthSettingsWriteScope,
@@ -67,7 +61,6 @@ import {
61
type ModelSelection,
62
type ProjectScript,
63
type ProjectId,
70
- type ProviderApprovalDecision,
64
type PreviewAnnotationPayload,
65
ProviderInstanceId,
66
type ServerProvider,
@@ -120,7 +113,6 @@ import {
113
type CodexFeedbackSubmission,
114
} from "@t3tools/client-runtime/state/threads";
115
import { resolveThreadLastVisitedAt } from "./Sidebar.logic";
123
-import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
116
import {
117
parseScopedThreadKey,
118
scopedThreadKey,
@@ -192,8 +184,6 @@ import {
184
parseStandaloneComposerSlashCommand,
185
} from "../composer-logic";
186
import {
195
- derivePendingApprovals,
196
- derivePendingUserInputs,
187
derivePhase,
188
deriveTimelineEntriesFromVisibleTurnItemsWithState,
189
selectHandoffImageResources,
@@ -204,7 +194,6 @@ import {
194
findLatestProposedPlan,
195
hasActionableProposedPlan,
196
isLatestRunSettled,
207
- type PendingUserInput,
197
} from "../session-logic";
198
import { type LegendListRef } from "@legendapp/list/react";
199
import {
@@ -215,16 +204,6 @@ import {
204
type TimelineRunObservation,
205
type TimelineScrollMode,
206
} from "./chat/timelineScrollAnchoring";
218
-import {
219
- buildPendingUserInputAnswers,
220
- carryDisplacedCustomAnswerIntoPrompt,
221
- derivePendingUserInputProgress,
222
- projectPendingUserInputAnswer,
223
- setPendingUserInputCustomAnswer,
224
- togglePendingUserInputOptionSelection,
225
- type PendingUserInputDraftAnswer,
226
-} from "../pendingUserInput";
227
-import { seedUserInputDraftAnswers } from "@t3tools/client-runtime/state/thread-requests";
207
import { useUiStateStore } from "../uiStateStore";
208
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
209
import {
@@ -632,7 +611,6 @@ const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
611
// broadcast to all shell subscribers.
612
const VISIT_DISPATCH_THROTTLE_MS = 10_000;
613
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
635
-const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
614
function useDraftHeroLayoutTransition(
615
isDraftHeroState: boolean,
616
animationsActive: boolean,
@@ -1596,40 +1574,7 @@ function makeThreadErrorSetter(input: {
1574
};
1575
}
1576
1599
-function makePendingCustomAnswerSetter(input: {
1600
- readonly activePendingUserInput: PendingUserInput | null;
1601
- readonly activePendingRequestKey: string;
1602
- readonly promptRef: { current: string };
1603
- readonly setPendingUserInputAnswersByRequestId: (
1604
- update: SetStateAction<Record<string, Record<string, PendingUserInputDraftAnswer>>>,
1605
- ) => void;
1606
-}) {
1607
- return (questionId: string, value: string) => {
1608
- const { activePendingUserInput, activePendingRequestKey } = input;
1609
- if (!activePendingUserInput) {
1610
- return;
1611
- }
1612
- const question = activePendingUserInput.questions.find((entry) => entry.id === questionId);
1613
- if (!question || question.allowCustomAnswer === false) {
1614
- return;
1615
- }
1616
- input.promptRef.current = value;
1617
- input.setPendingUserInputAnswersByRequestId((existing) => ({
1618
- ...existing,
1619
- [activePendingRequestKey]: {
1620
- ...existing[activePendingRequestKey],
1621
- [questionId]: setPendingUserInputCustomAnswer(
1622
- existing[activePendingRequestKey]?.[questionId],
1623
- value,
1624
- question,
1625
- ),
1626
- },
1627
- }));
1628
- // The editor owns this selection. Resetting it before the answer renders
1629
- // can re-enter Lexical with offsets from the previous skill token.
1630
- };
1631
-}
1632
-
1577
+/** Draft id for editing a queued run of `threadRef`. */
1578
function makeQueuedEditDraftTarget(threadRef: ScopedThreadRef) {
1579
return (runId: RunId) => DraftId.make(`queued-edit:${scopedThreadKey(threadRef)}:${runId}`);
1580
}
@@ -1724,15 +1669,6 @@ export default function ChatView(props: ChatViewProps) {
1669
label: "load earlier thread history",
1670
reportFailure: false,
1671
});
1727
- const respondToThreadApproval = useOrchestrationCommand(threadEnvironment.respondToApproval, {
1728
- reportFailure: false,
1729
- });
1730
- const respondToThreadUserInput = useOrchestrationCommand(threadEnvironment.respondToUserInput, {
1731
- reportFailure: false,
1732
- });
1733
- const dismissThreadUserInput = useAtomCommand(threadEnvironment.dismissUserInput, {
1734
- reportFailure: false,
1735
- });
1672
const revertThreadCheckpoint = useOrchestrationCommand(threadEnvironment.revertCheckpoint, {
1673
reportFailure: false,
1674
});
@@ -1978,8 +1914,6 @@ export default function ChatView(props: ChatViewProps) {
1914
const isRevertingCheckpoint = useComposerDraftStore((store) =>
1915
store.rewindingThreadKeys.has(routeThreadKey),
1916
);
1981
- const userInputResponsesInFlight = useRef(new Set<string>());
1982
- const [respondingRequestIds, setRespondingRequestIds] = useState<RuntimeRequestId[]>([]);
1917
1918
useEffect(() => {
1919
setIsWorkspaceFileDragActive(false);
@@ -1991,14 +1925,6 @@ export default function ChatView(props: ChatViewProps) {
1925
window.addEventListener("dragend", clearWorkspaceFileDrag);
1926
return () => window.removeEventListener("dragend", clearWorkspaceFileDrag);
1927
}, [isWorkspaceFileDragActive]);
1994
- const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
1995
- RuntimeRequestId[]
1996
- >([]);
1997
- const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<
1998
- Record<string, Record<string, PendingUserInputDraftAnswer>>
1999
- >({});
2000
- const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
2001
- useState<Record<string, number>>({});
1928
const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
1929
const isMobileViewport = useMediaQuery("max-sm");
1930
const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState<HTMLDivElement | null>(null);
@@ -3280,172 +3206,50 @@ export default function ChatView(props: ChatViewProps) {
3206
conversationProviderStatus !== null &&
3207
conversationProviderStatus.supportsConversationRollback !== false;
3208
const phase = derivePhase(activeRuntime);
3283
- const pendingRequests = useMemo(
3284
- () =>
3285
- serverProjection === null
3286
- ? { approvals: [], userInputs: [] }
3287
- : derivePendingThreadRequests(serverProjection),
3288
- [serverProjection],
3289
- );
3290
- const pendingApprovals = useMemo(
3291
- () => derivePendingApprovals(pendingRequests.approvals),
3292
- [pendingRequests.approvals],
3293
- );
3294
- const pendingUserInputs = useMemo(
3295
- () => derivePendingUserInputs(pendingRequests.userInputs),
3296
- [pendingRequests.userInputs],
3297
- );
3298
- const activePendingUserInput = pendingUserInputs[0] ?? null;
3299
- const activePendingRequestKey = JSON.stringify([
3300
- environmentId,
3301
- activeThreadId,
3302
- activePendingUserInput?.requestId,
3303
- ]);
3304
- const activePendingAnswerDrafts =
3305
- pendingUserInputAnswersByRequestId[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;
3306
- if (
3307
- activePendingUserInput &&
3308
- seedUserInputDraftAnswers(activePendingUserInput.questions, activePendingAnswerDrafts) !==
3309
- activePendingAnswerDrafts
3310
- ) {
3311
- setPendingUserInputAnswersByRequestId((existing) => {
3312
- const drafts = existing[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;
3313
- const seeded = seedUserInputDraftAnswers(activePendingUserInput.questions, drafts);
3314
- return seeded === drafts ? existing : { ...existing, [activePendingRequestKey]: seeded };
3315
- });
3316
- }
3317
- const pendingQuestionDraftKeys = useMemo(
3209
+ const setThreadError = useMemo(
3210
() =>
3319
- activeThreadId
3320
- ? pendingUserInputs.flatMap((request) =>
3321
- request.questions.map((question) =>
3322
- questionAttachmentDraftId(
3323
- environmentId,
3324
- activeThreadId,
3325
- request.requestId,
3326
- question.id,
3327
- ),
3328
- ),
3329
- )
3330
- : [],
3331
- [activeThreadId, environmentId, pendingUserInputs],
3332
- );
3333
- const questionComposerDrafts = useComposerDraftStore(
3334
- useShallow((state) =>
3335
- Object.fromEntries(
3336
- pendingQuestionDraftKeys.map((key) => [key, state.draftsByThreadKey[key]]),
3337
- ),
3338
- ),
3339
- );
3340
- const questionUploadsBlocked = useAttachmentUploadStore(
3341
- useShallow((state) =>
3342
- Object.fromEntries(
3343
- pendingQuestionDraftKeys.map((key) => {
3344
- const draft = questionComposerDrafts[key];
3345
- const attachments = draft ? [...draft.images, ...draft.files] : [];
3346
- return [
3347
- key,
3348
- attachments.some((attachment) => {
3349
- const upload = state.uploadsByImageId[attachment.id];
3350
- return upload?.status !== "ready" || upload.environmentId !== environmentId;
3351
- }),
3352
- ];
3353
- }),
3354
- ),
3355
- ),
3356
- );
3357
- const questionPreparations = useQuestionAttachmentPreparation(
3358
- useShallow((state) =>
3359
- Object.fromEntries(pendingQuestionDraftKeys.map((key) => [key, state.counts[key] ?? 0])),
3360
- ),
3361
- );
3362
- useEffect(() => {
3363
- if (!activeThread) return;
3364
- const questionThread = activeThread;
3365
- const currentRequests = pendingUserInputs;
3366
- const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);
3367
- const retained = new Set(
3368
- currentRequests.flatMap((request) =>
3369
- request.questions.map((question) =>
3370
- questionAttachmentDraftId(
3371
- environmentId,
3372
- questionThread.id,
3373
- request.requestId,
3374
- question.id,
3375
- ),
3376
- ),
3377
- ),
3378
- );
3379
- const keys = new Set([
3380
- ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
3381
- ...Object.keys(useQuestionAttachmentPreparation.getState().counts),
3382
- ]);
3383
- for (const key of keys) {
3384
- if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))
3385
- clearQuestionAttachmentDraft(DraftId.make(key));
3386
- }
3387
- }, [environmentId, activeThread, pendingUserInputs]);
3388
- const activePendingDraftAnswers = useMemo(() => {
3389
- if (!activePendingUserInput || !activeThreadId) return EMPTY_PENDING_USER_INPUT_ANSWERS;
3390
- return Object.fromEntries(
3391
- activePendingUserInput.questions.map((question) => {
3392
- const key = questionAttachmentDraftId(
3393
- environmentId,
3394
- activeThreadId,
3395
- activePendingUserInput.requestId,
3396
- question.id,
3397
- );
3398
- const draft = questionComposerDrafts[key];
3399
- const attachments = draft ? [...draft.images, ...draft.files] : [];
3400
- return [
3401
- question.id,
3402
- {
3403
- ...pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[question.id],
3404
- attachmentCount: attachments.length,
3405
- attachmentsBlocked:
3406
- (attachments.length > 0 && !supportsQuestionAttachments) ||
3407
- (questionPreparations[key] ?? 0) > 0 ||
3408
- questionUploadsBlocked[key] === true,
3409
- },
3410
- ];
3211
+ makeThreadErrorSetter({
3212
+ routeThreadRef,
3213
+ routeThreadKey,
3214
+ draftId,
3215
+ serverThreadRef: serverThread
3216
+ ? { threadId: serverThread.id, environmentId: serverThread.environmentId }
3217
+ : null,
3218
+ setLocalServerErrorsByThreadKey,
3219
+ setLocalDraftErrorsByDraftId,
3220
}),
3412
- );
3413
- }, [
3221
+ [draftId, routeThreadKey, routeThreadRef, serverThread?.id, serverThread?.environmentId],
3222
+ );
3223
+ const {
3224
+ pendingApprovals,
3225
+ pendingUserInputs,
3226
+ activePendingApproval,
3227
activePendingUserInput,
3415
- activeThreadId,
3228
+ activePendingDraftAnswers,
3229
+ activePendingQuestionIndex,
3230
+ activePendingProgress,
3231
+ activePendingResolvedAnswers,
3232
+ activePendingIsResponding,
3233
+ respondingRequestIds,
3234
+ onRespondToApproval: onRespondToApprovalStable,
3235
+ onDismissUserInput: onDismissUserInputStable,
3236
+ onSelectActivePendingUserInputOption: onSelectActivePendingUserInputOptionStable,
3237
+ onChangeActivePendingUserInputCustomAnswer,
3238
+ onAdvanceActivePendingUserInput,
3239
+ onAdvanceActivePendingUserInputStable,
3240
+ onPreviousActivePendingUserInputQuestion: onPreviousActivePendingUserInputQuestionStable,
3241
+ } = usePendingThreadRequests({
3242
environmentId,
3417
- questionComposerDrafts,
3418
- questionUploadsBlocked,
3243
+ activeThreadId,
3244
+ activeThread,
3245
+ serverProjection,
3246
supportsQuestionAttachments,
3420
- questionPreparations,
3421
- pendingUserInputAnswersByRequestId,
3422
- activePendingRequestKey,
3423
- ]);
3424
- const activePendingQuestionIndex = activePendingUserInput
3425
- ? (pendingUserInputQuestionIndexByRequestId[activePendingRequestKey] ?? 0)
3426
- : 0;
3427
- const activePendingProgress = useMemo(
3428
- () =>
3429
- activePendingUserInput
3430
- ? derivePendingUserInputProgress(
3431
- activePendingUserInput.questions,
3432
- activePendingDraftAnswers,
3433
- activePendingQuestionIndex,
3434
- )
3435
- : null,
3436
- [activePendingDraftAnswers, activePendingQuestionIndex, activePendingUserInput],
3437
- );
3438
- const activePendingResolvedAnswers = useMemo(
3439
- () =>
3440
- activePendingUserInput
3441
- ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers)
3442
- : null,
3443
- [activePendingDraftAnswers, activePendingUserInput],
3444
- );
3445
- const activePendingIsResponding = activePendingUserInput
3446
- ? activePendingUserInput.responseCapability === "not_resumable" ||
3447
- respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
3448
- : false;
3247
+ composerDraftTarget,
3248
+ setComposerDraftPrompt,
3249
+ promptRef,
3250
+ composerRef,
3251
+ setThreadError,
3252
+ });
3253
const activeProposedPlan = useMemo(() => {
3254
if (!latestRunSettled) {
3255
return null;
@@ -3459,7 +3263,11 @@ export default function ChatView(props: ChatViewProps) {
3263
hasActionableProposedPlan: hasActionableProposedPlan(activeProposedPlan),
3264
hasComposerAttachments: composerHasAttachments,
3265
});
3462
- const activePendingApproval = pendingApprovals[0] ?? null;
3266
+ // The open /usage-limits panel for this thread, model and turn. Only the open
3267
+ // moment is stored: the rows read live provider data, so a redeemed reset
3268
+ // credit or refreshed probe shows through. Anything that spends quota closes
3269
+ // it: a new turn from any source, or the agent resuming after an approval or
3270
+ // answered question.
3271
const [usageLimitsPanel, setUsageLimitsPanel] = useState<{
3272
readonly key: string;
3273
readonly threadKey: string;
@@ -4467,20 +4275,6 @@ export default function ChatView(props: ChatViewProps) {
4275
null;
4276
const hasReachedSplitLimit =
4277
(activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP;
4470
- const setThreadError = useMemo(
4471
- () =>
4472
- makeThreadErrorSetter({
4473
- routeThreadRef,
4474
- routeThreadKey,
4475
- draftId,
4476
- serverThreadRef: serverThread
4477
- ? { threadId: serverThread.id, environmentId: serverThread.environmentId }
4478
- : null,
4479
- setLocalServerErrorsByThreadKey,
4480
- setLocalDraftErrorsByDraftId,
4481
- }),
4482
- [draftId, routeThreadKey, routeThreadRef, serverThread?.id, serverThread?.environmentId],
4483
- );
4278
4279
const focusComposer = () => {
4280
composerRef.current?.focusAtEnd();
@@ -9716,237 +9510,6 @@ export default function ChatView(props: ChatViewProps) {
9510
}
9511
};
9512
9719
- const onRespondToApproval = async (
9720
- requestId: RuntimeRequestId,
9721
- decision: ProviderApprovalDecision,
9722
- ) => {
9723
- if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
9724
- return;
9725
- if (
9726
- pendingApprovals.find((approval) => approval.requestId === requestId)?.responseCapability !==
9727
- "live"
9728
- )
9729
- return;
9730
-
9731
- setRespondingRequestIds((existing) =>
9732
- existing.includes(requestId) ? existing : [...existing, requestId],
9733
- );
9734
- const result = await respondToThreadApproval({
9735
- environmentId,
9736
- input: {
9737
- threadId: activeThreadId,
9738
- requestId,
9739
- decision,
9740
- },
9741
- });
9742
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
9743
- const error = squashAtomCommandFailure(result);
9744
- setThreadError(
9745
- activeThreadId,
9746
- error instanceof Error ? error.message : "Failed to submit approval decision.",
9747
- );
9748
- }
9749
- setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
9750
- return result;
9751
- };
9752
- const onRespondToApprovalStable = useStableCallback(onRespondToApproval);
9753
-
9754
- const onRespondToUserInput = async (
9755
- requestId: RuntimeRequestId,
9756
- answers: Record<string, unknown>,
9757
- ) => {
9758
- if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
9759
- return;
9760
- const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId);
9761
- if (!pendingInput || pendingInput.responseCapability === "not_resumable") return;
9762
- const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
9763
- if (userInputResponsesInFlight.current.has(responseKey)) return;
9764
- const attachmentsByQuestionId = new Map<
9765
- string,
9766
- import("@t3tools/contracts").UserInputAttachments[string]
9767
- >();
9768
- const providerAnswers = { ...answers };
9769
- for (const question of pendingInput.questions) {
9770
- const target = questionAttachmentDraftId(
9771
- environmentId,
9772
- activeThreadId,
9773
- requestId,
9774
- question.id,
9775
- );
9776
- if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
9777
- const draft = useComposerDraftStore.getState().getComposerDraft(target);
9778
- providerAnswers[question.id] = projectPendingUserInputAnswer(
9779
- answers[question.id],
9780
- draft?.threadContexts ?? [],
9781
- );
9782
- const attachments = draft ? [...draft.images, ...draft.files] : [];
9783
- if (attachments.length === 0) continue;
9784
- const uploaded = getUploadedAttachments({ environmentId, images: attachments });
9785
- if (!uploaded) {
9786
- setThreadError(
9787
- activeThreadId,
9788
- "Wait for attachments to finish uploading, or remove failed uploads.",
9789
- );
9790
- return;
9791
- }
9792
- attachmentsByQuestionId.set(
9793
- question.id,
9794
- uploaded as import("@t3tools/contracts").UserInputAttachments[string],
9795
- );
9796
- }
9797
- userInputResponsesInFlight.current.add(responseKey);
9798
-
9799
- setRespondingUserInputRequestIds((existing) =>
9800
- existing.includes(requestId) ? existing : [...existing, requestId],
9801
- );
9802
- const result = await respondToThreadUserInput({
9803
- environmentId,
9804
- input: {
9805
- threadId: activeThreadId,
9806
- requestId,
9807
- answers: providerAnswers,
9808
- ...(attachmentsByQuestionId.size > 0
9809
- ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
9810
- : {}),
9811
- },
9812
- });
9813
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
9814
- const error = squashAtomCommandFailure(result);
9815
- setThreadError(
9816
- activeThreadId,
9817
- error instanceof Error ? error.message : "Failed to submit user input.",
9818
- );
9819
- }
9820
- userInputResponsesInFlight.current.delete(responseKey);
9821
- setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
9822
- return result;
9823
- };
9824
-
9825
- const onDismissUserInput = async (requestId: RuntimeRequestId) => {
9826
- if (!activeThreadId) return;
9827
-
9828
- setRespondingUserInputRequestIds((existing) =>
9829
- existing.includes(requestId) ? existing : [...existing, requestId],
9830
- );
9831
- const result = await dismissThreadUserInput({
9832
- environmentId,
9833
- input: { threadId: activeThreadId, requestId },
9834
- });
9835
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
9836
- const error = squashAtomCommandFailure(result);
9837
- setThreadError(
9838
- activeThreadId,
9839
- error instanceof Error ? error.message : "Failed to dismiss the question.",
9840
- );
9841
- }
9842
- setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
9843
- return result;
9844
- };
9845
- const onDismissUserInputStable = useStableCallback(onDismissUserInput);
9846
-
9847
- const setActivePendingUserInputQuestionIndex = (nextQuestionIndex: number) => {
9848
- if (!activePendingUserInput) {
9849
- return;
9850
- }
9851
- setPendingUserInputQuestionIndexByRequestId((existing) => ({
9852
- ...existing,
9853
- [activePendingRequestKey]: nextQuestionIndex,
9854
- }));
9855
- };
9856
-
9857
- const onSelectActivePendingUserInputOption = (questionId: string, optionValue: string) => {
9858
- if (!activePendingUserInput) {
9859
- return;
9860
- }
9861
- const displacedAnswer =
9862
- pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[questionId]?.customAnswer;
9863
- const currentPrompt =
9864
- useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
9865
- const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer);
9866
- if (nextPrompt !== currentPrompt) {
9867
- setComposerDraftPrompt(composerDraftTarget, nextPrompt);
9868
- if (activeThreadId) {
9869
- const store = useComposerDraftStore.getState();
9870
- const questionTarget = questionAttachmentDraftId(
9871
- environmentId,
9872
- activeThreadId,
9873
- activePendingUserInput.requestId,
9874
- questionId,
9875
- );
9876
- store.addThreadContexts(
9877
- composerDraftTarget,
9878
- store.getComposerDraft(questionTarget)?.threadContexts ?? [],
9879
- { appendReference: false },
9880
- );
9881
- }
9882
- }
9883
- setPendingUserInputAnswersByRequestId((existing) => {
9884
- const question =
9885
- (activePendingProgress?.activeQuestion?.id === questionId
9886
- ? activePendingProgress.activeQuestion
9887
- : undefined) ?? activePendingUserInput.questions.find((entry) => entry.id === questionId);
9888
- if (!question) {
9889
- return existing;
9890
- }
9891
-
9892
- return {
9893
- ...existing,
9894
- [activePendingRequestKey]: {
9895
- ...existing[activePendingRequestKey],
9896
- [questionId]: togglePendingUserInputOptionSelection(
9897
- question,
9898
- existing[activePendingRequestKey]?.[questionId],
9899
- optionValue,
9900
- ),
9901
- },
9902
- };
9903
- });
9904
- promptRef.current = "";
9905
- composerRef.current?.resetCursorState({ cursor: 0 });
9906
- };
9907
- const onSelectActivePendingUserInputOptionStable = useStableCallback(
9908
- onSelectActivePendingUserInputOption,
9909
- );
9910
-
9911
- const onChangeActivePendingUserInputCustomAnswer = useMemo(
9912
- () =>
9913
- makePendingCustomAnswerSetter({
9914
- activePendingUserInput,
9915
- activePendingRequestKey,
9916
- promptRef,
9917
- setPendingUserInputAnswersByRequestId,
9918
- }),
9919
- [activePendingUserInput, activePendingRequestKey],
9920
- );
9921
-
9922
- const onAdvanceActivePendingUserInput = () => {
9923
- if (
9924
- !activePendingUserInput ||
9925
- activePendingUserInput.responseCapability === "not_resumable" ||
9926
- !activePendingProgress
9927
- ) {
9928
- return;
9929
- }
9930
- if (activePendingProgress.isLastQuestion) {
9931
- if (activePendingResolvedAnswers) {
9932
- void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers);
9933
- }
9934
- return;
9935
- }
9936
- setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1);
9937
- };
9938
- const onAdvanceActivePendingUserInputStable = useStableCallback(onAdvanceActivePendingUserInput);
9939
-
9940
- const onPreviousActivePendingUserInputQuestion = () => {
9941
- if (!activePendingProgress) {
9942
- return;
9943
- }
9944
- setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0));
9945
- };
9946
- const onPreviousActivePendingUserInputQuestionStable = useStableCallback(
9947
- onPreviousActivePendingUserInputQuestion,
9948
- );
9949
-
9513
async function onSubmitPlanFollowUp({
9514
text,
9515
context,
apps/web/src/components/chat/usePendingThreadRequests.ts
new
+551
@@ -0,0 +1,551 @@
1
+import {
2
+ AuthOrchestrationOperateScope,
3
+ type EnvironmentId,
4
+ type OrchestrationV2ThreadProjection,
5
+ type ProviderApprovalDecision,
6
+ type RuntimeRequestId,
7
+ type ScopedThreadRef,
8
+ type ThreadId,
9
+ type UserInputAttachments,
10
+} from "@t3tools/contracts";
11
+import {
12
+ derivePendingThreadRequests,
13
+ seedUserInputDraftAnswers,
14
+} from "@t3tools/client-runtime/state/thread-requests";
15
+import {
16
+ isAtomCommandInterrupted,
17
+ squashAtomCommandFailure,
18
+} from "@t3tools/client-runtime/state/runtime";
19
+import { useEffect, useMemo, useRef, useState, type RefObject, type SetStateAction } from "react";
20
+import { useShallow } from "zustand/react/shallow";
21
+import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
22
+import { useStableCallback } from "../../hooks/useStableCallback";
23
+import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
24
+import {
25
+ buildPendingUserInputAnswers,
26
+ carryDisplacedCustomAnswerIntoPrompt,
27
+ derivePendingUserInputProgress,
28
+ projectPendingUserInputAnswer,
29
+ setPendingUserInputCustomAnswer,
30
+ togglePendingUserInputOptionSelection,
31
+ type PendingUserInputDraftAnswer,
32
+} from "../../pendingUserInput";
33
+import {
34
+ clearQuestionAttachmentDraft,
35
+ questionAttachmentDraftId,
36
+ questionAttachmentDraftPrefix,
37
+ useQuestionAttachmentPreparation,
38
+} from "../../questionAttachments";
39
+import {
40
+ derivePendingApprovals,
41
+ derivePendingUserInputs,
42
+ type PendingUserInput,
43
+} from "../../session-logic";
44
+import { readEnvironmentScope } from "../../state/session";
45
+import { threadEnvironment } from "../../state/threads";
46
+import { useAtomCommand } from "../../state/use-atom-command";
47
+import { useOrchestrationCommand } from "../../state/use-orchestration-command";
48
+import type { ChatComposerHandle } from "./ChatComposer";
49
+
50
+const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
51
+
52
+/** Writes the custom answer for a question of the pending user input the making render saw. */
53
+function makePendingCustomAnswerSetter(input: {
54
+ readonly activePendingUserInput: PendingUserInput | null;
55
+ readonly activePendingRequestKey: string;
56
+ readonly promptRef: { current: string };
57
+ readonly setPendingUserInputAnswersByRequestId: (
58
+ update: SetStateAction<Record<string, Record<string, PendingUserInputDraftAnswer>>>,
59
+ ) => void;
60
+}) {
61
+ return (questionId: string, value: string) => {
62
+ const { activePendingUserInput, activePendingRequestKey } = input;
63
+ if (!activePendingUserInput) {
64
+ return;
65
+ }
66
+ const question = activePendingUserInput.questions.find((entry) => entry.id === questionId);
67
+ if (!question || question.allowCustomAnswer === false) {
68
+ return;
69
+ }
70
+ input.promptRef.current = value;
71
+ input.setPendingUserInputAnswersByRequestId((existing) => ({
72
+ ...existing,
73
+ [activePendingRequestKey]: {
74
+ ...existing[activePendingRequestKey],
75
+ [questionId]: setPendingUserInputCustomAnswer(
76
+ existing[activePendingRequestKey]?.[questionId],
77
+ value,
78
+ question,
79
+ ),
80
+ },
81
+ }));
82
+ // The editor owns this selection. Resetting it before the answer renders
83
+ // can re-enter Lexical with offsets from the previous skill token.
84
+ };
85
+}
86
+
87
+/**
88
+ * Pending approvals and user-input questions for the active thread: what is
89
+ * waiting, the user's in-progress answers, and the commands that respond.
90
+ */
91
+export function usePendingThreadRequests(input: {
92
+ readonly environmentId: EnvironmentId;
93
+ readonly activeThreadId: ThreadId | null;
94
+ // The effect that prunes stale question drafts re-runs when this object changes.
95
+ readonly activeThread: { readonly id: ThreadId } | undefined;
96
+ readonly serverProjection: OrchestrationV2ThreadProjection | null;
97
+ readonly supportsQuestionAttachments: boolean;
98
+ readonly composerDraftTarget: ScopedThreadRef | DraftId;
99
+ readonly setComposerDraftPrompt: (target: ScopedThreadRef | DraftId, prompt: string) => void;
100
+ readonly promptRef: { current: string };
101
+ readonly composerRef: RefObject<ChatComposerHandle | null>;
102
+ readonly setThreadError: (threadId: ThreadId, error: string | null) => void;
103
+}) {
104
+ const {
105
+ environmentId,
106
+ activeThreadId,
107
+ activeThread,
108
+ serverProjection,
109
+ supportsQuestionAttachments,
110
+ composerDraftTarget,
111
+ setComposerDraftPrompt,
112
+ promptRef,
113
+ composerRef,
114
+ setThreadError,
115
+ } = input;
116
+ const respondToThreadApproval = useOrchestrationCommand(threadEnvironment.respondToApproval, {
117
+ reportFailure: false,
118
+ });
119
+ const respondToThreadUserInput = useOrchestrationCommand(threadEnvironment.respondToUserInput, {
120
+ reportFailure: false,
121
+ });
122
+ const dismissThreadUserInput = useAtomCommand(threadEnvironment.dismissUserInput, {
123
+ reportFailure: false,
124
+ });
125
+ const userInputResponsesInFlight = useRef(new Set<string>());
126
+ const [respondingRequestIds, setRespondingRequestIds] = useState<RuntimeRequestId[]>([]);
127
+ const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
128
+ RuntimeRequestId[]
129
+ >([]);
130
+ const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<
131
+ Record<string, Record<string, PendingUserInputDraftAnswer>>
132
+ >({});
133
+ const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
134
+ useState<Record<string, number>>({});
135
+ const pendingRequests = useMemo(
136
+ () =>
137
+ serverProjection === null
138
+ ? { approvals: [], userInputs: [] }
139
+ : derivePendingThreadRequests(serverProjection),
140
+ [serverProjection],
141
+ );
142
+ const pendingApprovals = useMemo(
143
+ () => derivePendingApprovals(pendingRequests.approvals),
144
+ [pendingRequests.approvals],
145
+ );
146
+ const pendingUserInputs = useMemo(
147
+ () => derivePendingUserInputs(pendingRequests.userInputs),
148
+ [pendingRequests.userInputs],
149
+ );
150
+ const activePendingUserInput = pendingUserInputs[0] ?? null;
151
+ const activePendingRequestKey = JSON.stringify([
152
+ environmentId,
153
+ activeThreadId,
154
+ activePendingUserInput?.requestId,
155
+ ]);
156
+ const activePendingAnswerDrafts =
157
+ pendingUserInputAnswersByRequestId[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;
158
+ if (
159
+ activePendingUserInput &&
160
+ seedUserInputDraftAnswers(activePendingUserInput.questions, activePendingAnswerDrafts) !==
161
+ activePendingAnswerDrafts
162
+ ) {
163
+ setPendingUserInputAnswersByRequestId((existing) => {
164
+ const drafts = existing[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;
165
+ const seeded = seedUserInputDraftAnswers(activePendingUserInput.questions, drafts);
166
+ return seeded === drafts ? existing : { ...existing, [activePendingRequestKey]: seeded };
167
+ });
168
+ }
169
+ const pendingQuestionDraftKeys = useMemo(
170
+ () =>
171
+ activeThreadId
172
+ ? pendingUserInputs.flatMap((request) =>
173
+ request.questions.map((question) =>
174
+ questionAttachmentDraftId(
175
+ environmentId,
176
+ activeThreadId,
177
+ request.requestId,
178
+ question.id,
179
+ ),
180
+ ),
181
+ )
182
+ : [],
183
+ [activeThreadId, environmentId, pendingUserInputs],
184
+ );
185
+ const questionComposerDrafts = useComposerDraftStore(
186
+ useShallow((state) =>
187
+ Object.fromEntries(
188
+ pendingQuestionDraftKeys.map((key) => [key, state.draftsByThreadKey[key]]),
189
+ ),
190
+ ),
191
+ );
192
+ const questionUploadsBlocked = useAttachmentUploadStore(
193
+ useShallow((state) =>
194
+ Object.fromEntries(
195
+ pendingQuestionDraftKeys.map((key) => {
196
+ const draft = questionComposerDrafts[key];
197
+ const attachments = draft ? [...draft.images, ...draft.files] : [];
198
+ return [
199
+ key,
200
+ attachments.some((attachment) => {
201
+ const upload = state.uploadsByImageId[attachment.id];
202
+ return upload?.status !== "ready" || upload.environmentId !== environmentId;
203
+ }),
204
+ ];
205
+ }),
206
+ ),
207
+ ),
208
+ );
209
+ const questionPreparations = useQuestionAttachmentPreparation(
210
+ useShallow((state) =>
211
+ Object.fromEntries(pendingQuestionDraftKeys.map((key) => [key, state.counts[key] ?? 0])),
212
+ ),
213
+ );
214
+ useEffect(() => {
215
+ if (!activeThread) return;
216
+ const questionThread = activeThread;
217
+ const currentRequests = pendingUserInputs;
218
+ const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);
219
+ const retained = new Set(
220
+ currentRequests.flatMap((request) =>
221
+ request.questions.map((question) =>
222
+ questionAttachmentDraftId(
223
+ environmentId,
224
+ questionThread.id,
225
+ request.requestId,
226
+ question.id,
227
+ ),
228
+ ),
229
+ ),
230
+ );
231
+ const keys = new Set([
232
+ ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
233
+ ...Object.keys(useQuestionAttachmentPreparation.getState().counts),
234
+ ]);
235
+ for (const key of keys) {
236
+ if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))
237
+ clearQuestionAttachmentDraft(DraftId.make(key));
238
+ }
239
+ }, [environmentId, activeThread, pendingUserInputs]);
240
+ const activePendingDraftAnswers = useMemo(() => {
241
+ if (!activePendingUserInput || !activeThreadId) return EMPTY_PENDING_USER_INPUT_ANSWERS;
242
+ return Object.fromEntries(
243
+ activePendingUserInput.questions.map((question) => {
244
+ const key = questionAttachmentDraftId(
245
+ environmentId,
246
+ activeThreadId,
247
+ activePendingUserInput.requestId,
248
+ question.id,
249
+ );
250
+ const draft = questionComposerDrafts[key];
251
+ const attachments = draft ? [...draft.images, ...draft.files] : [];
252
+ return [
253
+ question.id,
254
+ {
255
+ ...pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[question.id],
256
+ attachmentCount: attachments.length,
257
+ attachmentsBlocked:
258
+ (attachments.length > 0 && !supportsQuestionAttachments) ||
259
+ (questionPreparations[key] ?? 0) > 0 ||
260
+ questionUploadsBlocked[key] === true,
261
+ },
262
+ ];
263
+ }),
264
+ );
265
+ }, [
266
+ activePendingUserInput,
267
+ activeThreadId,
268
+ environmentId,
269
+ questionComposerDrafts,
270
+ questionUploadsBlocked,
271
+ supportsQuestionAttachments,
272
+ questionPreparations,
273
+ pendingUserInputAnswersByRequestId,
274
+ activePendingRequestKey,
275
+ ]);
276
+ const activePendingQuestionIndex = activePendingUserInput
277
+ ? (pendingUserInputQuestionIndexByRequestId[activePendingRequestKey] ?? 0)
278
+ : 0;
279
+ const activePendingProgress = useMemo(
280
+ () =>
281
+ activePendingUserInput
282
+ ? derivePendingUserInputProgress(
283
+ activePendingUserInput.questions,
284
+ activePendingDraftAnswers,
285
+ activePendingQuestionIndex,
286
+ )
287
+ : null,
288
+ [activePendingDraftAnswers, activePendingQuestionIndex, activePendingUserInput],
289
+ );
290
+ const activePendingResolvedAnswers = useMemo(
291
+ () =>
292
+ activePendingUserInput
293
+ ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers)
294
+ : null,
295
+ [activePendingDraftAnswers, activePendingUserInput],
296
+ );
297
+ const activePendingIsResponding = activePendingUserInput
298
+ ? activePendingUserInput.responseCapability === "not_resumable" ||
299
+ respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
300
+ : false;
301
+ const activePendingApproval = pendingApprovals[0] ?? null;
302
+
303
+ const onRespondToApproval = async (
304
+ requestId: RuntimeRequestId,
305
+ decision: ProviderApprovalDecision,
306
+ ) => {
307
+ if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
308
+ return;
309
+ if (
310
+ pendingApprovals.find((approval) => approval.requestId === requestId)?.responseCapability !==
311
+ "live"
312
+ )
313
+ return;
314
+
315
+ setRespondingRequestIds((existing) =>
316
+ existing.includes(requestId) ? existing : [...existing, requestId],
317
+ );
318
+ const result = await respondToThreadApproval({
319
+ environmentId,
320
+ input: {
321
+ threadId: activeThreadId,
322
+ requestId,
323
+ decision,
324
+ },
325
+ });
326
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
327
+ const error = squashAtomCommandFailure(result);
328
+ setThreadError(
329
+ activeThreadId,
330
+ error instanceof Error ? error.message : "Failed to submit approval decision.",
331
+ );
332
+ }
333
+ setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
334
+ return result;
335
+ };
336
+ const onRespondToApprovalStable = useStableCallback(onRespondToApproval);
337
+
338
+ const onRespondToUserInput = async (
339
+ requestId: RuntimeRequestId,
340
+ answers: Record<string, unknown>,
341
+ ) => {
342
+ if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
343
+ return;
344
+ const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId);
345
+ if (!pendingInput || pendingInput.responseCapability === "not_resumable") return;
346
+ const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
347
+ if (userInputResponsesInFlight.current.has(responseKey)) return;
348
+ const attachmentsByQuestionId = new Map<string, UserInputAttachments[string]>();
349
+ const providerAnswers = { ...answers };
350
+ for (const question of pendingInput.questions) {
351
+ const target = questionAttachmentDraftId(
352
+ environmentId,
353
+ activeThreadId,
354
+ requestId,
355
+ question.id,
356
+ );
357
+ if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
358
+ const draft = useComposerDraftStore.getState().getComposerDraft(target);
359
+ providerAnswers[question.id] = projectPendingUserInputAnswer(
360
+ answers[question.id],
361
+ draft?.threadContexts ?? [],
362
+ );
363
+ const attachments = draft ? [...draft.images, ...draft.files] : [];
364
+ if (attachments.length === 0) continue;
365
+ const uploaded = getUploadedAttachments({ environmentId, images: attachments });
366
+ if (!uploaded) {
367
+ setThreadError(
368
+ activeThreadId,
369
+ "Wait for attachments to finish uploading, or remove failed uploads.",
370
+ );
371
+ return;
372
+ }
373
+ attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]);
374
+ }
375
+ userInputResponsesInFlight.current.add(responseKey);
376
+
377
+ setRespondingUserInputRequestIds((existing) =>
378
+ existing.includes(requestId) ? existing : [...existing, requestId],
379
+ );
380
+ const result = await respondToThreadUserInput({
381
+ environmentId,
382
+ input: {
383
+ threadId: activeThreadId,
384
+ requestId,
385
+ answers: providerAnswers,
386
+ ...(attachmentsByQuestionId.size > 0
387
+ ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
388
+ : {}),
389
+ },
390
+ });
391
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
392
+ const error = squashAtomCommandFailure(result);
393
+ setThreadError(
394
+ activeThreadId,
395
+ error instanceof Error ? error.message : "Failed to submit user input.",
396
+ );
397
+ }
398
+ userInputResponsesInFlight.current.delete(responseKey);
399
+ setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
400
+ return result;
401
+ };
402
+
403
+ // Closes an async question without messaging the agent. The server records
404
+ // the dismissal so every client releases the composer.
405
+ const onDismissUserInput = async (requestId: RuntimeRequestId) => {
406
+ if (!activeThreadId) return;
407
+
408
+ setRespondingUserInputRequestIds((existing) =>
409
+ existing.includes(requestId) ? existing : [...existing, requestId],
410
+ );
411
+ const result = await dismissThreadUserInput({
412
+ environmentId,
413
+ input: { threadId: activeThreadId, requestId },
414
+ });
415
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
416
+ const error = squashAtomCommandFailure(result);
417
+ setThreadError(
418
+ activeThreadId,
419
+ error instanceof Error ? error.message : "Failed to dismiss the question.",
420
+ );
421
+ }
422
+ setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
423
+ return result;
424
+ };
425
+ const onDismissUserInputStable = useStableCallback(onDismissUserInput);
426
+
427
+ const setActivePendingUserInputQuestionIndex = (nextQuestionIndex: number) => {
428
+ if (!activePendingUserInput) {
429
+ return;
430
+ }
431
+ setPendingUserInputQuestionIndexByRequestId((existing) => ({
432
+ ...existing,
433
+ [activePendingRequestKey]: nextQuestionIndex,
434
+ }));
435
+ };
436
+
437
+ const onSelectActivePendingUserInputOption = (questionId: string, optionValue: string) => {
438
+ if (!activePendingUserInput) {
439
+ return;
440
+ }
441
+ // The option replaces the custom answer. Anything typed there is the
442
+ // user's text, so it goes back to the thread draft instead of vanishing.
443
+ const displacedAnswer =
444
+ pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[questionId]?.customAnswer;
445
+ const currentPrompt =
446
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
447
+ const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer);
448
+ if (nextPrompt !== currentPrompt) {
449
+ setComposerDraftPrompt(composerDraftTarget, nextPrompt);
450
+ if (activeThreadId) {
451
+ const store = useComposerDraftStore.getState();
452
+ const questionTarget = questionAttachmentDraftId(
453
+ environmentId,
454
+ activeThreadId,
455
+ activePendingUserInput.requestId,
456
+ questionId,
457
+ );
458
+ store.addThreadContexts(
459
+ composerDraftTarget,
460
+ store.getComposerDraft(questionTarget)?.threadContexts ?? [],
461
+ { appendReference: false },
462
+ );
463
+ }
464
+ }
465
+ setPendingUserInputAnswersByRequestId((existing) => {
466
+ const question =
467
+ (activePendingProgress?.activeQuestion?.id === questionId
468
+ ? activePendingProgress.activeQuestion
469
+ : undefined) ?? activePendingUserInput.questions.find((entry) => entry.id === questionId);
470
+ if (!question) {
471
+ return existing;
472
+ }
473
+
474
+ return {
475
+ ...existing,
476
+ [activePendingRequestKey]: {
477
+ ...existing[activePendingRequestKey],
478
+ [questionId]: togglePendingUserInputOptionSelection(
479
+ question,
480
+ existing[activePendingRequestKey]?.[questionId],
481
+ optionValue,
482
+ ),
483
+ },
484
+ };
485
+ });
486
+ promptRef.current = "";
487
+ composerRef.current?.resetCursorState({ cursor: 0 });
488
+ };
489
+ const onSelectActivePendingUserInputOptionStable = useStableCallback(
490
+ onSelectActivePendingUserInputOption,
491
+ );
492
+
493
+ const onChangeActivePendingUserInputCustomAnswer = useMemo(
494
+ () =>
495
+ makePendingCustomAnswerSetter({
496
+ activePendingUserInput,
497
+ activePendingRequestKey,
498
+ promptRef,
499
+ setPendingUserInputAnswersByRequestId,
500
+ }),
501
+ [activePendingUserInput, activePendingRequestKey, promptRef],
502
+ );
503
+
504
+ const onAdvanceActivePendingUserInput = () => {
505
+ if (
506
+ !activePendingUserInput ||
507
+ activePendingUserInput.responseCapability === "not_resumable" ||
508
+ !activePendingProgress
509
+ ) {
510
+ return;
511
+ }
512
+ if (activePendingProgress.isLastQuestion) {
513
+ if (activePendingResolvedAnswers) {
514
+ void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers);
515
+ }
516
+ return;
517
+ }
518
+ setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1);
519
+ };
520
+ const onAdvanceActivePendingUserInputStable = useStableCallback(onAdvanceActivePendingUserInput);
521
+
522
+ const onPreviousActivePendingUserInputQuestion = () => {
523
+ if (!activePendingProgress) {
524
+ return;
525
+ }
526
+ setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0));
527
+ };
528
+ const onPreviousActivePendingUserInputQuestionStable = useStableCallback(
529
+ onPreviousActivePendingUserInputQuestion,
530
+ );
531
+
532
+ return {
533
+ pendingApprovals,
534
+ pendingUserInputs,
535
+ activePendingApproval,
536
+ activePendingUserInput,
537
+ activePendingDraftAnswers,
538
+ activePendingQuestionIndex,
539
+ activePendingProgress,
540
+ activePendingResolvedAnswers,
541
+ activePendingIsResponding,
542
+ respondingRequestIds,
543
+ onRespondToApproval: onRespondToApprovalStable,
544
+ onDismissUserInput: onDismissUserInputStable,
545
+ onSelectActivePendingUserInputOption: onSelectActivePendingUserInputOptionStable,
546
+ onChangeActivePendingUserInputCustomAnswer,
547
+ onAdvanceActivePendingUserInput,
548
+ onAdvanceActivePendingUserInputStable,
549
+ onPreviousActivePendingUserInputQuestion: onPreviousActivePendingUserInputQuestionStable,
550
+ };
551
+}