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