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

pendingUserInput.ts

245 lines8.2 KB

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