Open History to see the last commit
1import {
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";
11import {
12 derivePendingThreadRequests,
13 seedUserInputDraftAnswers,
14} from "@t3tools/client-runtime/state/thread-requests";
15import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18} from "@t3tools/client-runtime/state/runtime";
19import { useEffect, useRef, useState, type RefObject, type SetStateAction } from "react";
20import { useShallow } from "zustand/react/shallow";
21import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
22import { useStableCallback } from "../../hooks/useStableCallback";
23import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
24import {
25 buildPendingUserInputAnswers,
26 carryDisplacedCustomAnswerIntoPrompt,
27 derivePendingUserInputProgress,
28 projectPendingUserInputAnswer,
29 setPendingUserInputCustomAnswer,
30 togglePendingUserInputOptionSelection,
31 type PendingUserInputDraftAnswer,
32} from "../../pendingUserInput";
33import {
34 clearQuestionAttachmentDraft,
35 questionAttachmentDraftId,
36 questionAttachmentDraftPrefix,
37 useQuestionAttachmentPreparation,
38} from "../../questionAttachments";
39import {
40 derivePendingApprovals,
41 derivePendingUserInputs,
42 type PendingUserInput,
43} from "../../session-logic";
44import { readEnvironmentScope } from "../../state/session";
45import { threadEnvironment } from "../../state/threads";
46import { useAtomCommand } from "../../state/use-atom-command";
47import { useOrchestrationCommand } from "../../state/use-orchestration-command";
48import type { ChatComposerHandle } from "./ChatComposer";
49
50const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
51const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
52const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
53const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
54
55/** Writes the custom answer for a question of the pending user input the making render saw. */
56function makePendingCustomAnswerSetter(input: {
57 readonly activePendingUserInput: PendingUserInput | null;
58 readonly activePendingRequestKey: string;
59 readonly writePrompt: (prompt: string) => void;
60 readonly setPendingUserInputAnswersByRequestId: (
61 update: SetStateAction<Record<string, Record<string, PendingUserInputDraftAnswer>>>,
62 ) => void;
63}) {
64 return (questionId: string, value: string) => {
65 const { activePendingUserInput, activePendingRequestKey } = input;
66 if (!activePendingUserInput) {
67 return;
68 }
69 const question = activePendingUserInput.questions.find((entry) => entry.id === questionId);
70 if (!question || question.allowCustomAnswer === false) {
71 return;
72 }
73 input.writePrompt(value);
74 input.setPendingUserInputAnswersByRequestId((existing) => ({
75 ...existing,
76 [activePendingRequestKey]: {
77 ...existing[activePendingRequestKey],
78 [questionId]: setPendingUserInputCustomAnswer(
79 existing[activePendingRequestKey]?.[questionId],
80 value,
81 question,
82 ),
83 },
84 }));
85 // The editor owns this selection. Resetting it before the answer renders
86 // can re-enter Lexical with offsets from the previous skill token.
87 };
88}
89
90/**
91 * Pending approvals and user-input questions for the active thread: what is
92 * waiting, the user's in-progress answers, and the commands that respond.
93 */
94export function usePendingThreadRequests(input: {
95 readonly environmentId: EnvironmentId;
96 readonly activeThreadId: ThreadId | null;
97 // The effect that prunes stale question drafts re-runs when this object changes.
98 readonly activeThread: { readonly id: ThreadId } | undefined;
99 readonly serverProjection: OrchestrationV2ThreadProjection | null;
100 readonly supportsQuestionAttachments: boolean;
101 readonly composerDraftTarget: ScopedThreadRef | DraftId;
102 readonly setComposerDraftPrompt: (target: ScopedThreadRef | DraftId, prompt: string) => void;
103 readonly promptRef: { current: string };
104 readonly composerRef: RefObject<ChatComposerHandle | null>;
105 readonly setThreadError: (threadId: ThreadId, error: string | null) => void;
106}) {
107 const {
108 environmentId,
109 activeThreadId,
110 activeThread,
111 serverProjection,
112 supportsQuestionAttachments,
113 composerDraftTarget,
114 setComposerDraftPrompt,
115 promptRef,
116 composerRef,
117 setThreadError,
118 } = input;
119 const respondToThreadApproval = useOrchestrationCommand(threadEnvironment.respondToApproval, {
120 reportFailure: false,
121 });
122 const respondToThreadUserInput = useOrchestrationCommand(threadEnvironment.respondToUserInput, {
123 reportFailure: false,
124 });
125 const dismissThreadUserInput = useAtomCommand(threadEnvironment.dismissUserInput, {
126 reportFailure: false,
127 });
128 const userInputResponsesInFlight = useRef(new Set<string>());
129 const [respondingRequestIds, setRespondingRequestIds] = useState<RuntimeRequestId[]>([]);
130 const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
131 RuntimeRequestId[]
132 >([]);
133 const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<
134 Record<string, Record<string, PendingUserInputDraftAnswer>>
135 >({});
136 const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
137 useState<Record<string, number>>({});
138 const pendingRequests =
139 serverProjection === null ? NO_PENDING_REQUESTS : derivePendingThreadRequests(serverProjection);
140 // The projection changes on every streamed event, so shared empties keep the
141 // composer and approval panel from re-rendering while nothing is pending.
142 const pendingApprovals =
143 pendingRequests.approvals.length === 0
144 ? NO_PENDING_APPROVALS
145 : derivePendingApprovals(pendingRequests.approvals);
146 const pendingUserInputs =
147 pendingRequests.userInputs.length === 0
148 ? NO_PENDING_USER_INPUTS
149 : derivePendingUserInputs(pendingRequests.userInputs);
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 = activeThreadId
170 ? pendingUserInputs.flatMap((request) =>
171 request.questions.map((question) =>
172 questionAttachmentDraftId(environmentId, activeThreadId, request.requestId, question.id),
173 ),
174 )
175 : [];
176 const questionComposerDrafts = useComposerDraftStore(
177 useShallow((state) =>
178 Object.fromEntries(
179 pendingQuestionDraftKeys.map((key) => [key, state.draftsByThreadKey[key]]),
180 ),
181 ),
182 );
183 const questionUploadsBlocked = useAttachmentUploadStore(
184 useShallow((state) =>
185 Object.fromEntries(
186 pendingQuestionDraftKeys.map((key) => {
187 const draft = questionComposerDrafts[key];
188 const attachments = draft ? [...draft.images, ...draft.files] : [];
189 return [
190 key,
191 attachments.some((attachment) => {
192 const upload = state.uploadsByImageId[attachment.id];
193 return upload?.status !== "ready" || upload.environmentId !== environmentId;
194 }),
195 ];
196 }),
197 ),
198 ),
199 );
200 const questionPreparations = useQuestionAttachmentPreparation(
201 useShallow((state) =>
202 Object.fromEntries(pendingQuestionDraftKeys.map((key) => [key, state.counts[key] ?? 0])),
203 ),
204 );
205 useEffect(() => {
206 if (!activeThread) return;
207 const questionThread = activeThread;
208 const currentRequests = pendingUserInputs;
209 const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);
210 const retained = new Set(
211 currentRequests.flatMap((request) =>
212 request.questions.map((question) =>
213 questionAttachmentDraftId(
214 environmentId,
215 questionThread.id,
216 request.requestId,
217 question.id,
218 ),
219 ),
220 ),
221 );
222 const keys = new Set([
223 ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
224 ...Object.keys(useQuestionAttachmentPreparation.getState().counts),
225 ]);
226 for (const key of keys) {
227 if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))
228 clearQuestionAttachmentDraft(DraftId.make(key));
229 }
230 }, [environmentId, activeThread, pendingUserInputs]);
231 const activePendingDraftAnswers =
232 !activePendingUserInput || !activeThreadId
233 ? EMPTY_PENDING_USER_INPUT_ANSWERS
234 : Object.fromEntries(
235 activePendingUserInput.questions.map((question) => {
236 const key = questionAttachmentDraftId(
237 environmentId,
238 activeThreadId,
239 activePendingUserInput.requestId,
240 question.id,
241 );
242 const draft = questionComposerDrafts[key];
243 const attachments = draft ? [...draft.images, ...draft.files] : [];
244 return [
245 question.id,
246 {
247 ...pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[question.id],
248 attachmentCount: attachments.length,
249 attachmentsBlocked:
250 (attachments.length > 0 && !supportsQuestionAttachments) ||
251 (questionPreparations[key] ?? 0) > 0 ||
252 questionUploadsBlocked[key] === true,
253 },
254 ];
255 }),
256 );
257 const activePendingQuestionIndex = activePendingUserInput
258 ? (pendingUserInputQuestionIndexByRequestId[activePendingRequestKey] ?? 0)
259 : 0;
260 const activePendingProgress = activePendingUserInput
261 ? derivePendingUserInputProgress(
262 activePendingUserInput.questions,
263 activePendingDraftAnswers,
264 activePendingQuestionIndex,
265 )
266 : null;
267 const activePendingResolvedAnswers = activePendingUserInput
268 ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers)
269 : null;
270 const activePendingIsResponding = activePendingUserInput
271 ? activePendingUserInput.responseCapability === "not_resumable" ||
272 respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
273 : false;
274 const activePendingApproval = pendingApprovals[0] ?? null;
275
276 const onRespondToApproval = async (
277 requestId: RuntimeRequestId,
278 decision: ProviderApprovalDecision,
279 ) => {
280 if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
281 return;
282 if (
283 pendingApprovals.find((approval) => approval.requestId === requestId)?.responseCapability !==
284 "live"
285 )
286 return;
287
288 setRespondingRequestIds((existing) =>
289 existing.includes(requestId) ? existing : [...existing, requestId],
290 );
291 const result = await respondToThreadApproval({
292 environmentId,
293 input: {
294 threadId: activeThreadId,
295 requestId,
296 decision,
297 },
298 });
299 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
300 const error = squashAtomCommandFailure(result);
301 setThreadError(
302 activeThreadId,
303 error instanceof Error ? error.message : "Failed to submit approval decision.",
304 );
305 }
306 setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
307 return result;
308 };
309 const onRespondToApprovalStable = useStableCallback(onRespondToApproval);
310
311 const onRespondToUserInput = async (
312 requestId: RuntimeRequestId,
313 answers: Record<string, unknown>,
314 ) => {
315 if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
316 return;
317 const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId);
318 if (!pendingInput || pendingInput.responseCapability === "not_resumable") return;
319 const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
320 if (userInputResponsesInFlight.current.has(responseKey)) return;
321 const attachmentsByQuestionId = new Map<string, UserInputAttachments[string]>();
322 const providerAnswers = { ...answers };
323 for (const question of pendingInput.questions) {
324 const target = questionAttachmentDraftId(
325 environmentId,
326 activeThreadId,
327 requestId,
328 question.id,
329 );
330 if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
331 const draft = useComposerDraftStore.getState().getComposerDraft(target);
332 providerAnswers[question.id] = projectPendingUserInputAnswer(
333 answers[question.id],
334 draft?.threadContexts ?? [],
335 );
336 const attachments = draft ? [...draft.images, ...draft.files] : [];
337 if (attachments.length === 0) continue;
338 const uploaded = getUploadedAttachments({ environmentId, images: attachments });
339 if (!uploaded) {
340 setThreadError(
341 activeThreadId,
342 "Wait for attachments to finish uploading, or remove failed uploads.",
343 );
344 return;
345 }
346 attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]);
347 }
348 userInputResponsesInFlight.current.add(responseKey);
349
350 setRespondingUserInputRequestIds((existing) =>
351 existing.includes(requestId) ? existing : [...existing, requestId],
352 );
353 const result = await respondToThreadUserInput({
354 environmentId,
355 input: {
356 threadId: activeThreadId,
357 requestId,
358 answers: providerAnswers,
359 ...(attachmentsByQuestionId.size > 0
360 ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
361 : {}),
362 },
363 });
364 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
365 const error = squashAtomCommandFailure(result);
366 setThreadError(
367 activeThreadId,
368 error instanceof Error ? error.message : "Failed to submit user input.",
369 );
370 }
371 userInputResponsesInFlight.current.delete(responseKey);
372 setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
373 return result;
374 };
375
376 // Closes an async question without messaging the agent. The server records
377 // the dismissal so every client releases the composer.
378 const onDismissUserInput = async (requestId: RuntimeRequestId) => {
379 if (!activeThreadId) return;
380
381 setRespondingUserInputRequestIds((existing) =>
382 existing.includes(requestId) ? existing : [...existing, requestId],
383 );
384 const result = await dismissThreadUserInput({
385 environmentId,
386 input: { threadId: activeThreadId, requestId },
387 });
388 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
389 const error = squashAtomCommandFailure(result);
390 setThreadError(
391 activeThreadId,
392 error instanceof Error ? error.message : "Failed to dismiss the question.",
393 );
394 }
395 setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
396 return result;
397 };
398 const onDismissUserInputStable = useStableCallback(onDismissUserInput);
399
400 const setActivePendingUserInputQuestionIndex = (nextQuestionIndex: number) => {
401 if (!activePendingUserInput) {
402 return;
403 }
404 setPendingUserInputQuestionIndexByRequestId((existing) => ({
405 ...existing,
406 [activePendingRequestKey]: nextQuestionIndex,
407 }));
408 };
409
410 const onSelectActivePendingUserInputOption = (questionId: string, optionValue: string) => {
411 if (!activePendingUserInput) {
412 return;
413 }
414 // The option replaces the custom answer. Anything typed there is the
415 // user's text, so it goes back to the thread draft instead of vanishing.
416 const displacedAnswer =
417 pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[questionId]?.customAnswer;
418 const currentPrompt =
419 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
420 const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer);
421 if (nextPrompt !== currentPrompt) {
422 setComposerDraftPrompt(composerDraftTarget, nextPrompt);
423 if (activeThreadId) {
424 const store = useComposerDraftStore.getState();
425 const questionTarget = questionAttachmentDraftId(
426 environmentId,
427 activeThreadId,
428 activePendingUserInput.requestId,
429 questionId,
430 );
431 store.addThreadContexts(
432 composerDraftTarget,
433 store.getComposerDraft(questionTarget)?.threadContexts ?? [],
434 { appendReference: false },
435 );
436 }
437 }
438 setPendingUserInputAnswersByRequestId((existing) => {
439 const question =
440 (activePendingProgress?.activeQuestion?.id === questionId
441 ? activePendingProgress.activeQuestion
442 : undefined) ?? activePendingUserInput.questions.find((entry) => entry.id === questionId);
443 if (!question) {
444 return existing;
445 }
446
447 return {
448 ...existing,
449 [activePendingRequestKey]: {
450 ...existing[activePendingRequestKey],
451 [questionId]: togglePendingUserInputOptionSelection(
452 question,
453 existing[activePendingRequestKey]?.[questionId],
454 optionValue,
455 ),
456 },
457 };
458 });
459 promptRef.current = "";
460 composerRef.current?.resetCursorState({ cursor: 0 });
461 };
462 const onSelectActivePendingUserInputOptionStable = useStableCallback(
463 onSelectActivePendingUserInputOption,
464 );
465
466 const writePrompt = useStableCallback((prompt: string) => {
467 promptRef.current = prompt;
468 });
469 const onChangeActivePendingUserInputCustomAnswer = makePendingCustomAnswerSetter({
470 activePendingUserInput,
471 activePendingRequestKey,
472 writePrompt,
473 setPendingUserInputAnswersByRequestId,
474 });
475
476 const onAdvanceActivePendingUserInput = () => {
477 if (
478 !activePendingUserInput ||
479 activePendingUserInput.responseCapability === "not_resumable" ||
480 !activePendingProgress
481 ) {
482 return;
483 }
484 if (activePendingProgress.isLastQuestion) {
485 if (activePendingResolvedAnswers) {
486 void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers);
487 }
488 return;
489 }
490 setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1);
491 };
492 const onAdvanceActivePendingUserInputStable = useStableCallback(onAdvanceActivePendingUserInput);
493
494 const onPreviousActivePendingUserInputQuestion = () => {
495 if (!activePendingProgress) {
496 return;
497 }
498 setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0));
499 };
500 const onPreviousActivePendingUserInputQuestionStable = useStableCallback(
501 onPreviousActivePendingUserInputQuestion,
502 );
503
504 return {
505 pendingApprovals,
506 pendingUserInputs,
507 activePendingApproval,
508 activePendingUserInput,
509 activePendingDraftAnswers,
510 activePendingQuestionIndex,
511 activePendingProgress,
512 activePendingResolvedAnswers,
513 activePendingIsResponding,
514 respondingRequestIds,
515 onRespondToApproval: onRespondToApprovalStable,
516 onDismissUserInput: onDismissUserInputStable,
517 onSelectActivePendingUserInputOption: onSelectActivePendingUserInputOptionStable,
518 onChangeActivePendingUserInputCustomAnswer,
519 onAdvanceActivePendingUserInput,
520 onAdvanceActivePendingUserInputStable,
521 onPreviousActivePendingUserInputQuestion: onPreviousActivePendingUserInputQuestionStable,
522 };
523}