@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 174 lines 6.35 KB
Raw
1 import type {
2 PreviewAnnotationContextRecord,
3 PreviewAnnotationPayload,
4 ReviewCommentContextRecord,
5 ThreadContextRecord,
6 UserInputQuestion,
7 } from "@t3tools/contracts";
8 import {
9 projectComposerContextForProvider,
10 replaceComposerContextReferences,
11 } from "@t3tools/shared/composerContextReferences";
12 import { formatThreadLink } from "@t3tools/shared/threadLinks";
13 import {
14 buildPendingUserInputAnswers,
15 normalizeSelectedOptionValues,
16 resolvePendingUserInputAnswer,
17 type PendingUserInputAnswer,
18 type PendingUserInputDraftAnswer,
19 } from "@t3tools/client-runtime/state/pending-user-input";
20
21 import { collectInlineContextIds } from "./lib/composerContextReferences";
22 import {
23 previewAnnotationContextRecord,
24 reviewCommentContextRecord,
25 } from "./lib/composerContextRecords";
26 import type { ReviewCommentContext } from "./reviewCommentContext";
27
28 type AnswerContextRecord =
29 | ThreadContextRecord
30 | ReviewCommentContextRecord
31 | PreviewAnnotationContextRecord;
32
33 // Diff comments and preview annotations land in the thread draft even when their chip is in an answer.
34 export function answerContextRecords(
35 questionDraft: { threadContexts: ReadonlyArray<ThreadContextRecord> } | null | undefined,
36 threadDraft:
37 | {
38 reviewComments: ReadonlyArray<ReviewCommentContext>;
39 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
40 }
41 | null
42 | undefined,
43 ): AnswerContextRecord[] {
44 return [
45 ...(questionDraft?.threadContexts ?? []),
46 ...(threadDraft?.reviewComments ?? []).map(reviewCommentContextRecord),
47 ...(threadDraft?.previewAnnotations ?? []).map((annotation) =>
48 previewAnnotationContextRecord(annotation),
49 ),
50 ];
51 }
52
53 export function projectPendingUserInputAnswer(
54 answer: unknown,
55 records: ReadonlyArray<AnswerContextRecord>,
56 ) {
57 if (typeof answer !== "string" || records.length === 0) return answer;
58 const recordsById = new Map(records.map((record) => [record.contextId, record]));
59 return replaceComposerContextReferences(answer, (reference) => {
60 const record = recordsById.get(reference.contextId);
61 if (record?.kind !== reference.kind) return reference.source;
62 return record.kind === "thread"
63 ? formatThreadLink(record, reference.label)
64 : projectComposerContextForProvider({ text: reference.source, records: [record] });
65 });
66 }
67
68 // Question drafts retain deleted chip records for undo; only transfer referenced records.
69 export function threadContextsReferencedByAnswer(
70 answer: string,
71 threadContexts: ReadonlyArray<ThreadContextRecord>,
72 ) {
73 const referencedIds = new Set(collectInlineContextIds(answer));
74 return threadContexts.filter((record) => referencedIds.has(record.contextId));
75 }
76
77 export interface PendingUserInputProgress<Q extends UserInputQuestion = UserInputQuestion> {
78 questionIndex: number;
79 activeQuestion: Q | null;
80 activeDraft: PendingUserInputDraftAnswer | undefined;
81 selectedOptionValues: ReadonlyArray<string>;
82 customAnswer: string;
83 resolvedAnswer: PendingUserInputAnswer | null;
84 usingCustomAnswer: boolean;
85 answeredQuestionCount: number;
86 isLastQuestion: boolean;
87 isComplete: boolean;
88 canAdvance: boolean;
89 }
90
91 const DISPLACED_ANSWER_SEPARATOR = "\n\n";
92
93 export function carryDisplacedCustomAnswerIntoPrompt(
94 prompt: string,
95 customAnswer: string | undefined,
96 ): string {
97 const displaced = customAnswer?.trim() ?? "";
98 if (displaced.length === 0) {
99 return prompt;
100 }
101 if (prompt.trim().length === 0) {
102 return displaced;
103 }
104 return `${prompt.trimEnd()}${DISPLACED_ANSWER_SEPARATOR}${displaced}`;
105 }
106
107 /**
108 * Takes set-aside answer text back out of the thread draft once it is the answer again.
109 * `laterDisplaced` is what was set aside after it, in order: together they locate this copy,
110 * so equal text inside another answer or the user's own draft is never the one removed.
111 */
112 export function withdrawDisplacedCustomAnswerFromPrompt(
113 prompt: string,
114 displaced: string,
115 laterDisplaced: ReadonlyArray<string> = [],
116 ): string {
117 const text = displaced.trim();
118 if (text.length === 0) return prompt;
119 const later = laterDisplaced.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
120 const suffix = [text, ...later].join(DISPLACED_ANSWER_SEPARATOR);
121 if (!prompt.endsWith(suffix)) return prompt;
122 const before = prompt.slice(0, prompt.length - suffix.length);
123 const after = later.join(DISPLACED_ANSWER_SEPARATOR);
124 if (before.length === 0) return after;
125 if (!before.endsWith(DISPLACED_ANSWER_SEPARATOR)) return prompt;
126 return after.length === 0 ? before.slice(0, -DISPLACED_ANSWER_SEPARATOR.length) : before + after;
127 }
128
129 function countAnsweredPendingUserInputQuestions(
130 questions: ReadonlyArray<UserInputQuestion>,
131 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
132 ): number {
133 return questions.reduce((count, question) => {
134 return resolvePendingUserInputAnswer(question, draftAnswers[question.id]) !== null
135 ? count + 1
136 : count;
137 }, 0);
138 }
139
140 export function derivePendingUserInputProgress<Q extends UserInputQuestion>(
141 questions: ReadonlyArray<Q>,
142 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
143 questionIndex: number,
144 ): PendingUserInputProgress<Q> {
145 const normalizedQuestionIndex =
146 questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
147 const activeQuestion = questions[normalizedQuestionIndex] ?? null;
148 const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
149 const resolvedAnswer = activeQuestion
150 ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
151 : null;
152 const customAnswer =
153 activeQuestion?.allowCustomAnswer === false ? "" : (activeDraft?.customAnswer ?? "");
154 const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
155 const isLastQuestion =
156 questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
157
158 return {
159 questionIndex: normalizedQuestionIndex,
160 activeQuestion,
161 activeDraft,
162 selectedOptionValues: activeQuestion
163 ? normalizeSelectedOptionValues(activeQuestion, activeDraft?.selectedOptionValues)
164 : [],
165 customAnswer,
166 resolvedAnswer,
167 usingCustomAnswer:
168 (activeQuestion?.initialAnswer !== undefined ? customAnswer : customAnswer.trim()).length > 0,
169 answeredQuestionCount,
170 isLastQuestion,
171 isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
172 canAdvance: resolvedAnswer !== null,
173 };
174 }