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