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

usePendingThreadRequests.ts

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