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