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

usePendingThreadRequests.ts

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