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

usePendingUserInputDraft.ts

288 lines12.9 KB

1import type { ScopedThreadRef } from "@t3tools/contracts";
2import { useCallback, useLayoutEffect, useRef, type Dispatch, type SetStateAction } from "react";
3import { useComposerDraftStore, type DraftId } from "../../composerDraftStore";
4import {
5 setPendingUserInputCustomAnswer,
6 type PendingUserInputDraftAnswer,
7} from "../../pendingUserInput";
8import {
9 collectPendingUserInputCustomAnswers,
10 type PendingUserInputRequestSnapshot,
11 mergeComposerDraftPromptWithPendingAnswer,
12 resolveComposerDraftPromptAfterReturningPendingAnswer,
13 resolveComposerDraftToCarryIntoPendingUserInput,
14 shouldRescueCancelledPendingUserInput,
15 pendingUserInputRequestKey,
16} from "../ChatView.logic";
17​
18type AnswersByRequest = Record<string, Record<string, PendingUserInputDraftAnswer>>;
19​
20/** Keeps persisted composer text through question transitions, navigation and failed responses. */
21export function usePendingUserInputDraft({
22 composerDraftTarget,
23 activePendingUserInput,
24 pendingUserInputAnswersByRequestId,
25 setPendingUserInputAnswersByRequestId,
26}: {
27 composerDraftTarget: ScopedThreadRef | DraftId;
28 activePendingUserInput: {
29 requestId: string;
30 questions: ReadonlyArray<{ id: string; allowCustomAnswer?: boolean | undefined }>;
31 } | null;
32 pendingUserInputAnswersByRequestId: AnswersByRequest;
33 setPendingUserInputAnswersByRequestId: Dispatch<SetStateAction<AnswersByRequest>>;
34}) {
35 const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
36 const activePendingRequestKey = pendingUserInputRequestKey(
37 composerDraftTarget,
38 activePendingUserInput?.requestId ?? null,
39 );
40 // The pending question seen on the previous render; see the rescue effect
41 // below.
42 const prevPendingUserInputRef = useRef<PendingUserInputRequestSnapshot<
43 ScopedThreadRef | DraftId
44 > | null>(null);
45 // Request ids with an answer submitted via onRespondToUserInput. A submitted
46 // question also disappears from pendingUserInputs, but that's the answer
47 // being sent, not the question being cancelled, so the effect below must
48 // not rescue its text. Unmarked when the submit fails.
49 const submittedPendingUserInputRequestIdsRef = useRef<Set<string>>(new Set());
50 // Persisted answer copies, initially carried from the composer and refreshed
51 // on submission failure. Retain the unrelated draft separately so replacing
52 // or removing the answer copy never consumes that draft.
53 const carriedComposerDraftByRequestIdRef = useRef(
54 new Map<string, { text: string; unrelatedText: string }>(),
55 );
56 // Text typed in the composer is never dropped: it is sent, or it stays in
57 // the draft. Appends text that is leaving a request's answer slot unsent to
58 // the thread's composer draft, replacing the persisted copy of text that
59 // was carried in from the draft.
60 const returnTextToComposerDraft = useCallback(
61 (
62 requestId: string,
63 text: string,
64 draftTarget: ScopedThreadRef | DraftId,
65 discardEmptyCarriedDraft = false,
66 ) => {
67 const requestKey = pendingUserInputRequestKey(draftTarget, requestId);
68 // The request key already includes the draft owner; object identity changes on navigation.
69 const carried = carriedComposerDraftByRequestIdRef.current.get(requestKey);
70 const draftPrompt =
71 useComposerDraftStore.getState().getComposerDraft(draftTarget)?.prompt ?? "";
72 const nextDraftPrompt = resolveComposerDraftPromptAfterReturningPendingAnswer({
73 draftPrompt,
74 carriedDraftPrompt: carried?.text ?? null,
75 unrelatedDraftPrompt: carried?.unrelatedText ?? "",
76 pendingCustomAnswer: text,
77 discardEmptyCarriedDraft,
78 });
79 if (nextDraftPrompt === null) {
80 return;
81 }
82 carriedComposerDraftByRequestIdRef.current.delete(requestKey);
83 if (nextDraftPrompt !== draftPrompt) {
84 setComposerDraftPrompt(draftTarget, nextDraftPrompt);
85 }
86 },
87 [setComposerDraftPrompt],
88 );
89 // An option returns only one question's text. Move it into the unrelated
90 // draft while retaining tracking for the other answers; the following answer
91 // state update synchronizes their complete remaining set in the layout effect.
92 const returnQuestionTextToComposerDraft = useCallback(
93 (requestId: string, text: string, draftTarget: ScopedThreadRef | DraftId) => {
94 if (text.trim().length === 0) return;
95 const requestKey = pendingUserInputRequestKey(draftTarget, requestId);
96 const carried = carriedComposerDraftByRequestIdRef.current.get(requestKey);
97 const draftPrompt =
98 useComposerDraftStore.getState().getComposerDraft(draftTarget)?.prompt ?? "";
99 const unrelatedText =
100 carried && draftPrompt === carried.text ? carried.unrelatedText : draftPrompt;
101 carriedComposerDraftByRequestIdRef.current.set(requestKey, {
102 text: draftPrompt,
103 unrelatedText:
104 mergeComposerDraftPromptWithPendingAnswer(unrelatedText, text) ?? unrelatedText,
105 });
106 },
107 [],
108 );
109 // Merges a request's typed custom answers into a thread's composer draft.
110 // Answers by request id are never pruned, so they stay readable after the
111 // request itself has disappeared.
112 const rescuePendingUserInputAnswers = useCallback(
113 (requestId: string, draftTarget: ScopedThreadRef | DraftId) => {
114 const text = collectPendingUserInputCustomAnswers(
115 pendingUserInputAnswersByRequestId[pendingUserInputRequestKey(draftTarget, requestId)],
116 );
117 if (text !== null) {
118 returnTextToComposerDraft(requestId, text, draftTarget);
119 }
120 },
121 [pendingUserInputAnswersByRequestId, returnTextToComposerDraft],
122 );
123 const activePendingFirstQuestionId = activePendingUserInput?.questions[0]?.id ?? null;
124 const activePendingFirstQuestionAllowsCustomAnswer =
125 activePendingUserInput?.questions[0]?.allowCustomAnswer !== false;
126 const activePendingHasAnswerState =
127 activePendingUserInput !== null &&
128 pendingUserInputAnswersByRequestId[activePendingRequestKey] !== undefined;
129 // Moves composer text across the pending-question boundary (issue #8963).
130 // A question that just appeared takes over the composer, so the draft is
131 // carried into its first question's free-form answer and stays visible;
132 // a question that disappears without being answered has its typed answers
133 // rescued back into the draft. Both run in a layout effect so the composer
134 // never paints a frame without the text. `prevPendingUserInputRef` is
135 // written only here, so "previous" is always the state before this
136 // transition.
137 useLayoutEffect(() => {
138 const nextRequestId = activePendingUserInput?.requestId ?? null;
139 const previous = prevPendingUserInputRef.current;
140 // A thread switch only hides the question, so it neither rescues nor
141 // consumes the submitted mark; the real resolve may arrive after the user
142 // returns and must still read as an answer, not a cancel.
143 if (
144 previous &&
145 previous.requestId !== nextRequestId &&
146 pendingUserInputRequestKey(previous.draftTarget, null) ===
147 pendingUserInputRequestKey(composerDraftTarget, null)
148 ) {
149 const previousKey = pendingUserInputRequestKey(previous.draftTarget, previous.requestId);
150 const wasSubmitted = submittedPendingUserInputRequestIdsRef.current.has(previousKey);
151 submittedPendingUserInputRequestIdsRef.current.delete(previousKey);
152 if (
153 shouldRescueCancelledPendingUserInput({
154 previous,
155 nextRequestId,
156 currentDraftTarget: composerDraftTarget,
157 wasSubmitted,
158 })
159 ) {
160 rescuePendingUserInputAnswers(previous.requestId, previous.draftTarget);
161 }
162 }
163 // Runs after the rescue so text from a question replaced in the same
164 // render follows the user into the new one.
165 if (
166 nextRequestId !== null &&
167 activePendingFirstQuestionId !== null &&
168 (previous?.requestId !== nextRequestId ||
169 pendingUserInputRequestKey(previous.draftTarget, null) !==
170 pendingUserInputRequestKey(composerDraftTarget, null))
171 ) {
172 const draftToCarry = resolveComposerDraftToCarryIntoPendingUserInput({
173 hasAnswerState: activePendingHasAnswerState,
174 allowCustomAnswer: activePendingFirstQuestionAllowsCustomAnswer,
175 draftPrompt:
176 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "",
177 });
178 if (draftToCarry !== null) {
179 carriedComposerDraftByRequestIdRef.current.set(activePendingRequestKey, {
180 text: draftToCarry,
181 unrelatedText: "",
182 });
183 setPendingUserInputAnswersByRequestId((existing) => ({
184 ...existing,
185 [activePendingRequestKey]: {
186 ...existing[activePendingRequestKey],
187 [activePendingFirstQuestionId]: setPendingUserInputCustomAnswer(
188 existing[activePendingRequestKey]?.[activePendingFirstQuestionId],
189 draftToCarry,
190 ),
191 },
192 }));
193 }
194 }
195 prevPendingUserInputRef.current = nextRequestId
196 ? { requestId: nextRequestId, draftTarget: composerDraftTarget }
197 : null;
198 }, [
199 activePendingFirstQuestionId,
200 activePendingFirstQuestionAllowsCustomAnswer,
201 activePendingHasAnswerState,
202 activePendingRequestKey,
203 activePendingUserInput?.requestId,
204 composerDraftTarget,
205 rescuePendingUserInputAnswers,
206 setPendingUserInputAnswersByRequestId,
207 ]);
208 // Persist the full current answer set after edits. A failed submission can
209 // contain several answers, so clearing one must retain the others even if
210 // this thread is hidden before the request disappears.
211 useLayoutEffect(() => {
212 const carried = carriedComposerDraftByRequestIdRef.current.get(activePendingRequestKey);
213 const answers = pendingUserInputAnswersByRequestId[activePendingRequestKey];
214 if (!activePendingUserInput || !carried || !answers) {
215 return;
216 }
217 const draftPrompt =
218 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
219 const unrelatedText = draftPrompt === carried.text ? carried.unrelatedText : draftPrompt;
220 const text =
221 mergeComposerDraftPromptWithPendingAnswer(
222 unrelatedText,
223 collectPendingUserInputCustomAnswers(answers) ?? "",
224 ) ?? unrelatedText;
225 carriedComposerDraftByRequestIdRef.current.set(activePendingRequestKey, {
226 text,
227 unrelatedText,
228 });
229 if (text !== draftPrompt) {
230 setComposerDraftPrompt(composerDraftTarget, text);
231 }
232 }, [
233 activePendingRequestKey,
234 activePendingUserInput,
235 composerDraftTarget,
236 pendingUserInputAnswersByRequestId,
237 setComposerDraftPrompt,
238 ]);
239 const beginSubmission = useCallback(
240 (requestId: string) => {
241 // Marked before the round trip: the resolved activity can arrive over the
242 // socket before this RPC settles, and the rescue effect must already know
243 // the question was answered rather than cancelled. Unmarked on failure so
244 // a later real Stop of the still-open question can rescue the text.
245 const requestKey = pendingUserInputRequestKey(composerDraftTarget, requestId);
246 submittedPendingUserInputRequestIdsRef.current.add(requestKey);
247 // The answer is what gets sent, so the persisted copy of text carried in
248 // from the draft goes now, before the resolve can bring the draft back
249 // on screen.
250 const carried = carriedComposerDraftByRequestIdRef.current.get(requestKey);
251 carriedComposerDraftByRequestIdRef.current.delete(requestKey);
252 const draftPrompt =
253 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
254 if (carried && draftPrompt === carried.text) {
255 setComposerDraftPrompt(composerDraftTarget, carried.unrelatedText);
256 }
257 // Capture what was submitted, rather than the original composer carry.
258 // Failure may arrive while a different thread or environment is visible.
259 const submittedText = collectPendingUserInputCustomAnswers(
260 pendingUserInputAnswersByRequestId[requestKey],
261 );
262 return () => {
263 submittedPendingUserInputRequestIdsRef.current.delete(requestKey);
264 if (submittedText === null) {
265 return;
266 }
267 const unrelatedText =
268 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
269 const restoredText = mergeComposerDraftPromptWithPendingAnswer(
270 unrelatedText,
271 submittedText,
272 );
273 if (restoredText === null) {
274 return;
275 }
276 // Keep the unrelated draft separate so editing, erasing or retrying the
277 // answer replaces only its persisted copy, even after navigation.
278 carriedComposerDraftByRequestIdRef.current.set(requestKey, {
279 text: restoredText,
280 unrelatedText,
281 });
282 setComposerDraftPrompt(composerDraftTarget, restoredText);
283 };
284 },
285 [composerDraftTarget, pendingUserInputAnswersByRequestId, setComposerDraftPrompt],
286 );
287 return { returnQuestionTextToComposerDraft, beginSubmission };