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