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