Open History to see the last commit
1import type { ThreadContextRecord } from "@t3tools/contracts";
2import type { ThreadUserInputQuestion as UserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
3import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
4import { formatThreadLink } from "@t3tools/shared/threadLinks";
5
6import { collectInlineContextIds } from "./lib/composerContextReferences";
7
8export function projectPendingUserInputAnswer(
9 answer: unknown,
10 threadContexts: ReadonlyArray<ThreadContextRecord>,
11) {
12 if (typeof answer !== "string" || threadContexts.length === 0) return answer;
13 const recordsById = new Map(threadContexts.map((record) => [record.contextId, record]));
14 return replaceComposerContextReferences(answer, (reference) => {
15 const record = reference.kind === "thread" ? recordsById.get(reference.contextId) : undefined;
16 return record ? formatThreadLink(record.threadId, reference.label) : reference.source;
17 });
18}
19
20// Question drafts retain deleted chip records for undo; only transfer referenced records.
21export function threadContextsReferencedByAnswer(
22 answer: string,
23 threadContexts: ReadonlyArray<ThreadContextRecord>,
24) {
25 const referencedIds = new Set(collectInlineContextIds(answer));
26 return threadContexts.filter((record) => referencedIds.has(record.contextId));
27}
28
29export interface PendingUserInputDraftAnswer {
30 selectedOptionValues?: string[];
31 customAnswer?: string;
32 attachmentCount?: number;
33 attachmentsBlocked?: boolean;
34}
35
36export interface PendingUserInputProgress {
37 questionIndex: number;
38 activeQuestion: UserInputQuestion | null;
39 activeDraft: PendingUserInputDraftAnswer | undefined;
40 selectedOptionValues: string[];
41 customAnswer: string;
42 resolvedAnswer: string | string[] | null;
43 usingCustomAnswer: boolean;
44 answeredQuestionCount: number;
45 isLastQuestion: boolean;
46 isComplete: boolean;
47 canAdvance: boolean;
48}
49
50function normalizeDraftAnswer(value: string | undefined): string | null {
51 if (typeof value !== "string") {
52 return null;
53 }
54
55 const trimmed = value.trim();
56 return trimmed.length > 0 ? trimmed : null;
57}
58
59function normalizeSelectedOptionValues(value: string[] | undefined): string[] {
60 if (!Array.isArray(value)) {
61 return [];
62 }
63
64 // Provider option IDs must stay unchanged, including whitespace.
65 return Array.from(new Set(value.filter((entry) => typeof entry === "string")));
66}
67
68export function resolvePendingUserInputAnswer(
69 question: UserInputQuestion,
70 draft: PendingUserInputDraftAnswer | undefined,
71): string | string[] | null {
72 if (draft?.attachmentsBlocked) return null;
73 const customAnswer =
74 question.allowCustomAnswer === false
75 ? null
76 : question.initialAnswer !== undefined
77 ? (draft?.customAnswer ?? null)
78 : normalizeDraftAnswer(draft?.customAnswer);
79 if (customAnswer !== null && customAnswer.length > 0) {
80 return customAnswer;
81 }
82
83 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues).filter(
84 (value) => question.options.some((option) => (option.value ?? option.label) === value),
85 );
86 if (question.multiSelect) {
87 return selectedOptionValues.length > 0
88 ? selectedOptionValues
89 : (customAnswer ??
90 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null));
91 }
92
93 return (
94 selectedOptionValues[0] ??
95 customAnswer ??
96 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
97 );
98}
99
100export function setPendingUserInputCustomAnswer(
101 draft: PendingUserInputDraftAnswer | undefined,
102 customAnswer: string,
103 question?: Pick<UserInputQuestion, "initialAnswer">,
104): PendingUserInputDraftAnswer {
105 const selectedOptionValues =
106 question?.initialAnswer !== undefined || customAnswer.trim().length > 0
107 ? undefined
108 : normalizeSelectedOptionValues(draft?.selectedOptionValues);
109
110 return {
111 customAnswer,
112 ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
113 };
114}
115
116export function pendingUserInputRequestKey(
117 environmentId: string,
118 threadId: string | null,
119 requestId: string | undefined,
120): string {
121 return JSON.stringify([environmentId, threadId, requestId]);
122}
123
124/** Drops a thread's drafts for requests that are no longer pending. Unchanged input is returned as is. */
125export function pruneResolvedUserInputDrafts<T>(
126 draftsByRequestKey: Record<string, T>,
127 environmentId: string,
128 threadId: string,
129 pendingRequestIds: ReadonlyArray<string>,
130): Record<string, T> {
131 const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
132 const pendingKeys = new Set(
133 pendingRequestIds.map((requestId) =>
134 pendingUserInputRequestKey(environmentId, threadId, requestId),
135 ),
136 );
137 const retained = Object.entries(draftsByRequestKey).filter(
138 ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
139 );
140 return retained.length === Object.keys(draftsByRequestKey).length
141 ? draftsByRequestKey
142 : Object.fromEntries(retained);
143}
144
145const DISPLACED_ANSWER_SEPARATOR = "\n\n";
146
147export function carryDisplacedCustomAnswerIntoPrompt(
148 prompt: string,
149 customAnswer: string | undefined,
150): string {
151 const displaced = customAnswer?.trim() ?? "";
152 if (displaced.length === 0) {
153 return prompt;
154 }
155 if (prompt.trim().length === 0) {
156 return displaced;
157 }
158 return `${prompt.trimEnd()}${DISPLACED_ANSWER_SEPARATOR}${displaced}`;
159}
160
161export function togglePendingUserInputOptionSelection(
162 question: UserInputQuestion,
163 draft: PendingUserInputDraftAnswer | undefined,
164 optionValue: string,
165): PendingUserInputDraftAnswer {
166 if (question.multiSelect) {
167 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues);
168 const nextSelectedOptionValues = selectedOptionValues.includes(optionValue)
169 ? selectedOptionValues.filter((value) => value !== optionValue)
170 : [...selectedOptionValues, optionValue];
171
172 return {
173 customAnswer: "",
174 ...(nextSelectedOptionValues.length > 0
175 ? { selectedOptionValues: nextSelectedOptionValues }
176 : {}),
177 };
178 }
179
180 return {
181 customAnswer: "",
182 selectedOptionValues: [optionValue],
183 };
184}
185
186export function buildPendingUserInputAnswers(
187 questions: ReadonlyArray<UserInputQuestion>,
188 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
189): Record<string, string | string[]> | null {
190 const answers: Record<string, string | string[]> = {};
191
192 for (const question of questions) {
193 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
194 if (answer === null) {
195 return null;
196 }
197 answers[question.id] = answer;
198 }
199
200 return answers;
201}
202
203export function countAnsweredPendingUserInputQuestions(
204 questions: ReadonlyArray<UserInputQuestion>,
205 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
206): number {
207 return questions.reduce((count, question) => {
208 return resolvePendingUserInputAnswer(question, draftAnswers[question.id]) !== null
209 ? count + 1
210 : count;
211 }, 0);
212}
213
214export function findFirstUnansweredPendingUserInputQuestionIndex(
215 questions: ReadonlyArray<UserInputQuestion>,
216 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
217): number {
218 const unansweredIndex = questions.findIndex(
219 (question) => resolvePendingUserInputAnswer(question, draftAnswers[question.id]) === null,
220 );
221
222 return unansweredIndex === -1 ? Math.max(questions.length - 1, 0) : unansweredIndex;
223}
224
225export function derivePendingUserInputProgress(
226 questions: ReadonlyArray<UserInputQuestion>,
227 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
228 questionIndex: number,
229): PendingUserInputProgress {
230 const normalizedQuestionIndex =
231 questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
232 const activeQuestion = questions[normalizedQuestionIndex] ?? null;
233 const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
234 const resolvedAnswer = activeQuestion
235 ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
236 : null;
237 const customAnswer =
238 activeQuestion?.allowCustomAnswer === false ? "" : (activeDraft?.customAnswer ?? "");
239 const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
240 const isLastQuestion =
241 questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
242
243 return {
244 questionIndex: normalizedQuestionIndex,
245 activeQuestion,
246 activeDraft,
247 selectedOptionValues: normalizeSelectedOptionValues(activeDraft?.selectedOptionValues),
248 customAnswer,
249 resolvedAnswer,
250 usingCustomAnswer:
251 (activeQuestion?.initialAnswer !== undefined ? customAnswer : customAnswer.trim()).length > 0,
252 answeredQuestionCount,
253 isLastQuestion,
254 isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
255 canAdvance: resolvedAnswer !== null,
256 };
257}