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

TextGenerationPrompts.test.ts

332 lines11.8 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import {
4 buildBranchNamePrompt,
5 buildCommitMessagePrompt,
6 buildPrContentPrompt,
7 buildThreadTitlePrompt,
8} from "./TextGenerationPrompts.ts";
9import {
10 normalizeCliError,
11 sanitizeThreadTitle,
12 toJsonSchemaObject,
13} from "./TextGenerationUtils.ts";
14import { TextGenerationError } from "@t3tools/contracts";
15​
16describe("buildCommitMessagePrompt", () => {
17 it("includes staged patch and summary in the prompt", () => {
18 const result = buildCommitMessagePrompt({
19 branch: "main",
20 stagedSummary: "M README.md",
21 stagedPatch: "diff --git a/README.md b/README.md\n+hello",
22 includeBranch: false,
23 });
24​
25 expect(result.prompt).toContain("Staged files:");
26 expect(result.prompt).toContain("M README.md");
27 expect(result.prompt).toContain("Staged patch:");
28 expect(result.prompt).toContain("diff --git a/README.md b/README.md");
29 expect(result.prompt).toContain("Branch: main");
30 // Should NOT include the branch generation instruction
31 expect(result.prompt).not.toContain("branch must be a short semantic git branch fragment");
32 });
33​
34 it("includes branch generation instruction when includeBranch is true", () => {
35 const result = buildCommitMessagePrompt({
36 branch: "feature/foo",
37 stagedSummary: "M README.md",
38 stagedPatch: "diff",
39 includeBranch: true,
40 });
41​
42 expect(result.prompt).toContain("branch must be a short semantic git branch fragment");
43 expect(result.prompt).toContain("Return a JSON object with keys: subject, body, branch.");
44 });
45​
46 it("shows (detached) when branch is null", () => {
47 const result = buildCommitMessagePrompt({
48 branch: null,
49 stagedSummary: "M a.ts",
50 stagedPatch: "diff",
51 includeBranch: false,
52 });
53​
54 expect(result.prompt).toContain("Branch: (detached)");
55 });
56​
57 it("includes policy instructions", () => {
58 const result = buildCommitMessagePrompt({
59 branch: "main",
60 stagedSummary: "M a.ts",
61 stagedPatch: "diff",
62 includeBranch: false,
63 policy: {
64 kind: "custom",
65 commitInstructions: "Use a terse repository-specific subject.",
66 inferRepositoryConventions: false,
67 },
68 });
69​
70 expect(result.prompt).toContain("Additional instructions:");
71 expect(result.prompt).toContain("Use a terse repository-specific subject.");
72 });
73});
74​
75describe("buildPrContentPrompt", () => {
76 it("includes branch names, commits, and diff in the prompt", () => {
77 const result = buildPrContentPrompt({
78 baseBranch: "main",
79 headBranch: "feature/auth",
80 commitSummary: "feat: add login page",
81 diffSummary: "3 files changed",
82 diffPatch: "diff --git a/auth.ts b/auth.ts\n+export function login()",
83 });
84​
85 expect(result.prompt).toContain("Base branch: main");
86 expect(result.prompt).toContain("Head branch: feature/auth");
87 expect(result.prompt).toContain("Commits:");
88 expect(result.prompt).toContain("feat: add login page");
89 expect(result.prompt).toContain("Diff stat:");
90 expect(result.prompt).toContain("3 files changed");
91 expect(result.prompt).toContain("Diff patch:");
92 expect(result.prompt).toContain("export function login()");
93 expect(result.prompt).toContain("include headings '## Summary' and '## Testing'");
94 });
95​
96 it("follows a repository PR template instead of the default body headings", () => {
97 const result = buildPrContentPrompt({
98 baseBranch: "main",
99 headBranch: "feature/auth",
100 commitSummary: "feat: add login page",
101 diffSummary: "3 files changed",
102 diffPatch: "diff",
103 changeRequestTemplate: "<!-- remove me -->\n## What changed\n\n## Verification",
104 policy: {
105 kind: "custom",
106 changeRequestInstructions: "Keep the title in sentence case.",
107 inferRepositoryConventions: false,
108 },
109 });
110​
111 expect(result.prompt).toContain("Keep the title in sentence case.");
112 expect(result.prompt).toContain("follow the repository change request template structure");
113 expect(result.prompt).toContain("drop HTML comments from the template");
114 expect(result.prompt).toContain("Repository change request template:");
115 expect(result.prompt).toContain("<!-- remove me -->\n## What changed\n\n## Verification");
116 expect(result.prompt).not.toContain("include headings '## Summary' and '## Testing'");
117 });
118});
119​
120describe("buildBranchNamePrompt", () => {
121 it("includes the user message in the prompt", () => {
122 const result = buildBranchNamePrompt({
123 message: "Fix the login timeout bug",
124 });
125​
126 expect(result.prompt).toContain("User message:");
127 expect(result.prompt).toContain("Fix the login timeout bug");
128 expect(result.prompt).not.toContain("Attachment metadata:");
129 });
130​
131 it("includes attachment metadata when attachments are provided", () => {
132 const result = buildBranchNamePrompt({
133 message: "Fix the layout from screenshot",
134 attachments: [
135 {
136 type: "image" as const,
137 id: "att-123",
138 name: "screenshot.png",
139 mimeType: "image/png",
140 sizeBytes: 12345,
141 },
142 ],
143 });
144​
145 expect(result.prompt).toContain("Attachment metadata:");
146 expect(result.prompt).toContain("screenshot.png");
147 expect(result.prompt).toContain("image/png");
148 expect(result.prompt).toContain("12345 bytes");
149 });
150});
151​
152describe("buildThreadTitlePrompt", () => {
153 it("requires each generated field in the strict response schema", () => {
154 const { outputSchema } = buildThreadTitlePrompt({ message: "Fix this" });
155 expect(toJsonSchemaObject(outputSchema)).toMatchObject({
156 required: ["title", "needsRefinement"],
157 properties: { title: { type: "string" }, needsRefinement: { type: "boolean" } },
158 });
159 });
160​
161 it("includes the user message without absent attachment metadata", () => {
162 const result = buildThreadTitlePrompt({
163 message: "Investigate reconnect regressions after session restore",
164 });
165​
166 expect(result.prompt).toContain("User message:");
167 expect(result.prompt).toContain("Investigate reconnect regressions after session restore");
168 expect(result.prompt).not.toContain("Attachment metadata:");
169 });
170​
171 it("includes attachment metadata when attachments are provided", () => {
172 const result = buildThreadTitlePrompt({
173 message: "Name this thread from the screenshot",
174 attachments: [
175 {
176 type: "image" as const,
177 id: "att-456",
178 name: "thread.png",
179 mimeType: "image/png",
180 sizeBytes: 67890,
181 },
182 ],
183 });
184​
185 expect(result.prompt).toContain("Attachment metadata:");
186 expect(result.prompt).toContain("thread.png");
187 expect(result.prompt).toContain("image/png");
188 expect(result.prompt).toContain("67890 bytes");
189 });
190​
191 it("regenerates from recent thread contents and identifies the previous title", () => {
192 const result = buildThreadTitlePrompt({
193 message: `USER:\nInvestigate reconnect regressions\n\nASSISTANT:\nThe remaining issue is stale session state`,
194 previousTitle: "Investigate reconnect regressions",
195 });
196​
197 expect(result.prompt).toContain(
198 "Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.",
199 );
200 expect(result.prompt).toContain('The previous title was "Investigate reconnect regressions".');
201 expect(result.prompt).toContain("Thread contents:");
202 expect(result.prompt).toContain("The remaining issue is stale session state");
203 });
204​
205 it("keeps the latest thread contents when regeneration context is truncated", () => {
206 const result = buildThreadTitlePrompt({
207 message: `${"old context ".repeat(1_000)}\n\nASSISTANT:\nCurrent thread state`,
208 previousTitle: "Old title",
209 });
210​
211 expect(result.prompt).toContain("[Earlier content truncated]");
212 expect(result.prompt).toContain("Current thread state");
213 expect(result.prompt).not.toContain("[truncated]");
214 });
215​
216 it("does not truncate an already-marked regeneration context twice", () => {
217 const retainedContext = "x".repeat(7_998);
218 const result = buildThreadTitlePrompt({
219 message: `[Earlier content truncated]\n\n${retainedContext}`,
220 previousTitle: "Old title",
221 });
222​
223 expect(result.prompt).toContain(
224 `Thread contents:\n[Earlier content truncated]\n\n${retainedContext}`,
225 );
226 expect(result.prompt.match(/\[Earlier content truncated\]/g)).toHaveLength(1);
227 });
228});
229​
230describe("sanitizeThreadTitle", () => {
231 it.each([
232 '{"title": "Refresh ev-stg APP ASG instances"}',
233 '{\n "title": "Refresh ev-stg APP ASG instances"\n}',
234 ])("unwraps a JSON title before normalizing: %s", (raw) => {
235 expect(sanitizeThreadTitle(raw)).toBe("Refresh ev-stg APP ASG instances");
236 });
237​
238 it.each([
239 "Rolling ES Refresh ev-stg",
240 "Fix {title} interpolation",
241 '{"title": 42}',
242 '{"subject": "Fix parsing"}',
243 '{"title": "unfinished}',
244 ])("preserves text that is not a JSON title: %s", (raw) => {
245 expect(sanitizeThreadTitle(raw)).toBe(raw);
246 });
247​
248 it("normalizes the extracted title", () => {
249 expect(sanitizeThreadTitle('{"title": " Fix reconnect failures "}')).toBe(
250 "Fix reconnect failures",
251 );
252 expect(sanitizeThreadTitle('{"title": " "}')).toBe("New thread");
253 expect(
254 sanitizeThreadTitle(
255 '{"title": "Reconnect failures after restart because the session state does not recover"}',
256 ),
257 ).toBe("Reconnect failures after restart because the session state does not recover");
258 });
259​
260 it("keeps complete titles for client display truncation", () => {
261 expect(
262 sanitizeThreadTitle(
263 ' "Reconnect failures after restart because the session state does not recover" ',
264 ),
265 ).toBe("Reconnect failures after restart because the session state does not recover");
266 });
267​
268 it("caps runaway titles so a paragraph cannot reach the sidebar", () => {
269 const words = Array.from({ length: 40 }, (_, index) => `word${index}`).join(" ");
270 const title = sanitizeThreadTitle(words);
271 expect(title.length).toBeLessThanOrEqual(120);
272 expect(title.endsWith("...")).toBe(true);
273 });
274});
275​
276describe("normalizeCliError", () => {
277 it("detects 'Command not found' and includes CLI name in the message", () => {
278 const error = normalizeCliError(
279 "claude",
280 "generateCommitMessage",
281 new Error("Command not found: claude"),
282 "Something went wrong",
283 );
284​
285 expect(error).toBeInstanceOf(TextGenerationError);
286 expect(error.detail).toContain("Claude CLI");
287 expect(error.detail).toContain("not available on PATH");
288 });
289​
290 it("uses the CLI name from the first argument for codex", () => {
291 const error = normalizeCliError(
292 "codex",
293 "generateBranchName",
294 new Error("Command not found: codex"),
295 "Something went wrong",
296 );
297​
298 expect(error).toBeInstanceOf(TextGenerationError);
299 expect(error.detail).toContain("Codex CLI");
300 expect(error.detail).toContain("not available on PATH");
301 });
302​
303 it("returns the error as-is if it is already a TextGenerationError", () => {
304 const existing = new TextGenerationError({
305 operation: "generatePrContent",
306 detail: "Already wrapped",
307 });
308​
309 const result = normalizeCliError("claude", "generatePrContent", existing, "fallback");
310​
311 expect(result).toBe(existing);
312 });
313​
314 it("wraps unknown non-Error values with the fallback message", () => {
315 const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback");
316​
317 expect(result).toBeInstanceOf(TextGenerationError);
318 expect(result.detail).toBe("fallback");
319 });
320​
321 it("does not expose CLI failure details in the public error message", () => {
322 const result = normalizeCliError(
323 "codex",
324 "generateCommitMessage",
325 new Error("request failed with access_token=secret-token"),
326 "Failed to generate a commit message",
327 );
328​
329 expect(result.detail).toBe("Failed to generate a commit message");
330 expect(result.message).not.toContain("secret-token");
331 });
332});