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

pendingUserInput.ts

256 lines8.7 KB

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 });
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));
27​
28export interface PendingUserInputDraftAnswer {
29 selectedOptionValues?: string[];
30 customAnswer?: string;
31 attachmentCount?: number;
32 attachmentsBlocked?: boolean;
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;
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;
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")));
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 );
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 };
114​
115export function pendingUserInputRequestKey(
116 environmentId: string,
117 threadId: string | null,
118 requestId: string | undefined,
119): string {
120 return JSON.stringify([environmentId, threadId, requestId]);
122​
123/** Drops a thread's drafts for requests that are no longer pending. Unchanged input is returned as is. */
124export function pruneResolvedUserInputDrafts<T>(
125 draftsByRequestKey: Record<string, T>,
126 environmentId: string,
127 threadId: string,
128 pendingRequestIds: ReadonlyArray<string>,
129): Record<string, T> {
130 const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
131 const pendingKeys = new Set(
132 pendingRequestIds.map((requestId) =>
133 pendingUserInputRequestKey(environmentId, threadId, requestId),
134 ),
135 );
136 const retained = Object.entries(draftsByRequestKey).filter(
137 ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
138 );
139 return retained.length === Object.keys(draftsByRequestKey).length
140 ? draftsByRequestKey
141 : Object.fromEntries(retained);
143​
144const DISPLACED_ANSWER_SEPARATOR = "\n\n";
145​
146export function carryDisplacedCustomAnswerIntoPrompt(
147 prompt: string,
148 customAnswer: string | undefined,
149): string {
150 const displaced = customAnswer?.trim() ?? "";
151 if (displaced.length === 0) {
152 return prompt;
153 }
154 if (prompt.trim().length === 0) {
155 return displaced;
156 }
157 return `${prompt.trimEnd()}${DISPLACED_ANSWER_SEPARATOR}${displaced}`;
159​
160export function togglePendingUserInputOptionSelection(
161 question: UserInputQuestion,
162 draft: PendingUserInputDraftAnswer | undefined,
163 optionValue: string,
164): PendingUserInputDraftAnswer {
165 if (question.multiSelect) {
166 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues);
167 const nextSelectedOptionValues = selectedOptionValues.includes(optionValue)
168 ? selectedOptionValues.filter((value) => value !== optionValue)
169 : [...selectedOptionValues, optionValue];
170​
171 return {
172 customAnswer: "",
173 ...(nextSelectedOptionValues.length > 0
174 ? { selectedOptionValues: nextSelectedOptionValues }
175 : {}),
176 };
177 }
178​
179 return {
180 customAnswer: "",
181 selectedOptionValues: [optionValue],
182 };
184​
185export function buildPendingUserInputAnswers(
186 questions: ReadonlyArray<UserInputQuestion>,
187 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
188): Record<string, string | string[]> | null {
189 const answers: Record<string, string | string[]> = {};
190​
191 for (const question of questions) {
192 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
193 if (answer === null) {
194 return null;
195 }
196 answers[question.id] = answer;
197 }
198​
199 return answers;
201​
202function countAnsweredPendingUserInputQuestions(
203 questions: ReadonlyArray<UserInputQuestion>,
204 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
205): number {
206 return questions.reduce((count, question) => {
207 return resolvePendingUserInputAnswer(question, draftAnswers[question.id]) !== null
208 ? count + 1
209 : count;
210 }, 0);
212​
213export function findFirstUnansweredPendingUserInputQuestionIndex(
214 questions: ReadonlyArray<UserInputQuestion>,
215 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
216): number {
217 const unansweredIndex = questions.findIndex(
218 (question) => resolvePendingUserInputAnswer(question, draftAnswers[question.id]) === null,
219 );
220​
221 return unansweredIndex === -1 ? Math.max(questions.length - 1, 0) : unansweredIndex;
223​
224export function derivePendingUserInputProgress(
225 questions: ReadonlyArray<UserInputQuestion>,
226 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
227 questionIndex: number,
228): PendingUserInputProgress {
229 const normalizedQuestionIndex =
230 questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
231 const activeQuestion = questions[normalizedQuestionIndex] ?? null;
232 const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
233 const resolvedAnswer = activeQuestion
234 ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
235 : null;
236 const customAnswer =
237 activeQuestion?.allowCustomAnswer === false ? "" : (activeDraft?.customAnswer ?? "");
238 const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
239 const isLastQuestion =
240 questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
241​
242 return {
243 questionIndex: normalizedQuestionIndex,
244 activeQuestion,
245 activeDraft,
246 selectedOptionValues: normalizeSelectedOptionValues(activeDraft?.selectedOptionValues),
247 customAnswer,
248 resolvedAnswer,
249 usingCustomAnswer:
250 (activeQuestion?.initialAnswer !== undefined ? customAnswer : customAnswer.trim()).length > 0,
251 answeredQuestionCount,
252 isLastQuestion,
253 isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
254 canAdvance: resolvedAnswer !== null,
255 };