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

usePendingThreadRequests.ts

551 lines20.7 KB

1import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2import {
3 AuthOrchestrationOperateScope,
4 type EnvironmentId,
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 };
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: ThreadStructure | 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 feedback?: string,
304 ) => {
305 if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
306 return;
307 if (
308 pendingApprovals.find((approval) => approval.requestId === requestId)?.responseCapability !==
309 "live"
310 )
311 return;
312​
313 setRespondingRequestIds((existing) =>
314 existing.includes(requestId) ? existing : [...existing, requestId],
315 );
316 const result = await respondToThreadApproval({
317 environmentId,
318 input: {
319 threadId: activeThreadId,
320 requestId,
321 decision,
322 ...(feedback === undefined ? {} : { feedback }),
323 },
324 });
325 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
326 const error = squashAtomCommandFailure(result);
327 setThreadError(
328 activeThreadId,
329 error instanceof Error ? error.message : "Failed to submit approval decision.",
330 );
331 }
332 setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
333 return result;
334 };
335 const onRespondToApprovalStable = useStableCallback(onRespondToApproval);
336​
337 const onRespondToUserInput = async (
338 requestId: RuntimeRequestId,
339 answers: Record<string, unknown>,
340 ) => {
341 if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
342 return;
343 const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId);
344 if (!pendingInput || pendingInput.responseCapability === "not_resumable") return;
345 const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
346 if (userInputResponsesInFlight.current.has(responseKey)) return;
347 const attachmentsByQuestionId = new Map<string, UserInputAttachments[string]>();
348 const providerAnswers = { ...answers };
349 for (const question of pendingInput.questions) {
350 const target = questionAttachmentDraftId(
351 environmentId,
352 activeThreadId,
353 requestId,
354 question.id,
355 );
356 if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
357 const draft = useComposerDraftStore.getState().getComposerDraft(target);
358 providerAnswers[question.id] = projectPendingUserInputAnswer(
359 answers[question.id],
360 draft?.threadContexts ?? [],
361 );
362 const attachments = draft ? [...draft.images, ...draft.files] : [];
363 if (attachments.length === 0) continue;
364 const uploaded = getUploadedAttachments({ environmentId, images: attachments });
365 if (!uploaded) {
366 setThreadError(
367 activeThreadId,
368 "Wait for attachments to finish uploading, or remove failed uploads.",
369 );
370 return;
371 }
372 attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]);
373 }
374 userInputResponsesInFlight.current.add(responseKey);
375​
376 setRespondingUserInputRequestIds((existing) =>
377 existing.includes(requestId) ? existing : [...existing, requestId],
378 );
379 const result = await respondToThreadUserInput({
380 environmentId,
381 input: {
382 threadId: activeThreadId,
383 requestId,
384 answers: providerAnswers,
385 ...(attachmentsByQuestionId.size > 0
386 ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
387 : {}),
388 },
389 });
390 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
391 const error = squashAtomCommandFailure(result);
392 setThreadError(
393 activeThreadId,
394 error instanceof Error ? error.message : "Failed to submit user input.",
395 );
396 }
397 userInputResponsesInFlight.current.delete(responseKey);
398 setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
399 return result;
400 };
401​
402 // Closes an async question without messaging the agent. The server records
403 // the dismissal so every client releases the composer.
404 const onDismissUserInput = async (requestId: RuntimeRequestId) => {
405 if (!activeThreadId) return;
406​
407 setRespondingUserInputRequestIds((existing) =>
408 existing.includes(requestId) ? existing : [...existing, requestId],
409 );
410 const result = await dismissThreadUserInput({
411 environmentId,
412 input: { threadId: activeThreadId, requestId },
413 });
414 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
415 const error = squashAtomCommandFailure(result);
416 setThreadError(
417 activeThreadId,
418 error instanceof Error ? error.message : "Failed to dismiss the question.",
419 );
420 }
421 setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
422 return result;
423 };
424 const onDismissUserInputStable = useStableCallback(onDismissUserInput);
425​
426 const setActivePendingUserInputQuestionIndex = (nextQuestionIndex: number) => {
427 if (!activePendingUserInput) {
428 return;
429 }
430 setPendingUserInputQuestionIndexByRequestId((existing) => ({
431 ...existing,
432 [activePendingRequestKey]: nextQuestionIndex,
433 }));
434 };
435​
436 const onSelectActivePendingUserInputOption = (questionId: string, optionValue: string) => {
437 if (!activePendingUserInput) {
438 return;
439 }
440 // The option replaces the custom answer. Anything typed there is the
441 // user's text, so it goes back to the thread draft instead of vanishing.
442 const displacedAnswer = activePendingAnswerDrafts[questionId]?.customAnswer;
443 const currentPrompt =
444 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
445 const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer);
446 if (nextPrompt !== currentPrompt) {
447 setComposerDraftPrompt(composerDraftTarget, nextPrompt);
448 if (activeThreadId) {
449 const store = useComposerDraftStore.getState();
450 const questionTarget = questionAttachmentDraftId(
451 environmentId,
452 activeThreadId,
453 activePendingUserInput.requestId,
454 questionId,
455 );
456 store.addThreadContexts(
457 composerDraftTarget,
458 threadContextsReferencedByAnswer(
459 displacedAnswer ?? "",
460 store.getComposerDraft(questionTarget)?.threadContexts ?? [],
461 ),
462 { appendReference: false },
463 );
464 }
465 }
466 setPendingUserInputAnswersByRequestId((existing) => {
467 const question =
468 (activePendingProgress?.activeQuestion?.id === questionId
469 ? activePendingProgress.activeQuestion
470 : undefined) ?? activePendingUserInput.questions.find((entry) => entry.id === questionId);
471 if (!question) {
472 return existing;
473 }
474​
475 return {
476 ...existing,
477 [activePendingRequestKey]: {
478 ...existing[activePendingRequestKey],
479 [questionId]: togglePendingUserInputOptionSelection(
480 question,
481 existing[activePendingRequestKey]?.[questionId],
482 optionValue,
483 ),
484 },
485 };
486 });
487 promptRef.current = "";
488 composerRef.current?.resetCursorState({ cursor: 0 });
489 };
490 const onSelectActivePendingUserInputOptionStable = useStableCallback(
491 onSelectActivePendingUserInputOption,
492 );
493​
494 const writePrompt = useStableCallback((prompt: string) => {
495 promptRef.current = prompt;
496 });
497 const onChangeActivePendingUserInputCustomAnswer = makePendingCustomAnswerSetter({
498 activePendingUserInput,
499 activePendingRequestKey,
500 writePrompt,
501 setPendingUserInputAnswersByRequestId,
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 };