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

usePendingThreadRequests.ts

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