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

textGenerationPrompts.test.ts

419 lines15.3 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import {
4 buildBranchNamePrompt,
5 buildCommitMessagePrompt,
6 buildPrContentPrompt,
7 buildReviewGuidePrompt,
8 buildThreadTitlePrompt,
9} from "./textGenerationPrompts.ts";
10import {
11 normalizeCliError,
12 sanitizeThreadTitle,
13 toJsonSchemaObject,
14} from "./textGenerationUtils.ts";
15import { TextGenerationError } from "@t3tools/contracts";
16​
17describe("buildCommitMessagePrompt", () => {
18 it("includes staged patch and summary in the prompt", () => {
19 const result = buildCommitMessagePrompt({
20 branch: "main",
21 stagedSummary: "M README.md",
22 stagedPatch: "diff --git a/README.md b/README.md\n+hello",
23 includeBranch: false,
24 });
25​
26 expect(result.prompt).toContain("Staged files:");
27 expect(result.prompt).toContain("M README.md");
28 expect(result.prompt).toContain("Staged patch:");
29 expect(result.prompt).toContain("diff --git a/README.md b/README.md");
30 expect(result.prompt).toContain("Branch: main");
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("requests a semantic prefix as part of the same branch response", () => {
122 const { prompt, outputSchema } = buildBranchNamePrompt({
123 message: "Add search",
124 naming: { mode: "semantic", prefix: "ignored", instructions: "ignored instruction" },
125 });
126 expect(prompt).toContain("feat/add-search");
127 expect(prompt).not.toContain("ignored instruction");
128 expect(toJsonSchemaObject(outputSchema)).toMatchObject({ required: ["branch"] });
129 });
130 it("appends custom instructions without imposing a prefix, case or word limit", () => {
131 const { prompt } = buildBranchNamePrompt({
132 message: "Add search",
133 naming: {
134 mode: "custom",
135 prefix: "ignored",
136 instructions: "Use Julius/ABC-123 and preserve capitalization.",
137 },
138 });
139 expect(prompt).toContain("Use Julius/ABC-123 and preserve capitalization.");
140 expect(prompt).toContain("complete branch name");
141 expect(prompt).not.toContain("2-6 words");
142 expect(prompt).not.toContain("lowercase");
143 expect(prompt).not.toContain("no issue prefixes");
144 });
145 it("asks for just the fragment in static mode", () => {
146 const { prompt } = buildBranchNamePrompt({
147 message: "Add search",
148 naming: { mode: "static", prefix: "team", instructions: "ignored instruction" },
149 });
150 expect(prompt).toContain("without a prefix or namespace");
151 expect(prompt).not.toContain("ignored instruction");
152 });
153​
154 it("includes the user message in the prompt", () => {
155 const result = buildBranchNamePrompt({
156 message: "Fix the login timeout bug",
157 });
158​
159 expect(result.prompt).toContain("User message:");
160 expect(result.prompt).toContain("Fix the login timeout bug");
161 expect(result.prompt).not.toContain("Attachment metadata:");
162 });
163​
164 it("includes attachment metadata when attachments are provided", () => {
165 const result = buildBranchNamePrompt({
166 message: "Fix the layout from screenshot",
167 attachments: [
168 {
169 type: "image" as const,
170 id: "att-123",
171 name: "screenshot.png",
172 mimeType: "image/png",
173 sizeBytes: 12345,
174 },
175 ],
176 });
177​
178 expect(result.prompt).toContain("Attachment metadata:");
179 expect(result.prompt).toContain("screenshot.png");
180 expect(result.prompt).toContain("image/png");
181 expect(result.prompt).toContain("12345 bytes");
182 });
183});
184​
185describe("buildReviewGuidePrompt", () => {
186 const input = {
187 number: 42,
188 title: "Add search",
189 description: "",
190 baseBranch: "main",
191 baseCommit: "abc123",
192 settledReview: "",
193 };
194​
195 it("adds the maintainer's preferences after the change context", () => {
196 const { prompt } = buildReviewGuidePrompt({
197 ...input,
198 instructions: " Skip test files unless they change behavior. ",
199 });
200 const preferences = prompt.indexOf("The maintainer's preferences for guides:");
201 expect(preferences).toBeGreaterThan(prompt.indexOf("Already settled in review:"));
202 expect(prompt.slice(preferences)).toContain("Skip test files unless they change behavior.");
203 expect(prompt.slice(preferences)).toContain("do not change the JSON format");
204 });
205​
206 it("names the stack's other layers as context the guide may point at", () => {
207 const { prompt } = buildReviewGuidePrompt({
208 ...input,
209 stack: [
210 { number: 41, title: "Add the index", headSha: "aaa111", state: "merged" },
211 { number: 42, title: "Add search", headSha: "bbb222", state: "open" },
212 { number: 43, title: "Search UI", headSha: null, state: "open" },
213 ],
214 });
215 expect(prompt).toContain("1. #41: Add the index, merged, head aaa111");
216 expect(prompt).toContain("2. #42 (this change): Add search\n");
217 expect(prompt).toContain("3. #43: Search UI, head not available");
218 expect(prompt).toContain("Never excerpt another layer's code");
219 });
220​
221 it("leaves the stack out for a change that is not in one", () => {
222 expect(buildReviewGuidePrompt(input).prompt).not.toContain("layer of a stack");
223 expect(
224 buildReviewGuidePrompt({
225 ...input,
226 stack: [{ number: 42, title: "Add search", headSha: "bbb222", state: "open" }],
227 }).prompt,
228 ).not.toContain("layer of a stack");
229 });
230​
231 it("leaves the section out when there are no preferences", () => {
232 expect(buildReviewGuidePrompt(input).prompt).not.toContain("preferences for guides");
233 expect(buildReviewGuidePrompt({ ...input, instructions: " " }).prompt).not.toContain(
234 "preferences for guides",
235 );
236 });
237});
238​
239describe("buildThreadTitlePrompt", () => {
240 it("requires each generated field in the strict response schema", () => {
241 const { outputSchema } = buildThreadTitlePrompt({ message: "Fix this" });
242 expect(toJsonSchemaObject(outputSchema)).toMatchObject({
243 required: ["title", "needsRefinement"],
244 properties: { title: { type: "string" }, needsRefinement: { type: "boolean" } },
245 });
246 });
247​
248 it("includes the user message without absent attachment metadata", () => {
249 const result = buildThreadTitlePrompt({
250 message: "Investigate reconnect regressions after session restore",
251 });
252​
253 expect(result.prompt).toContain("User message:");
254 expect(result.prompt).toContain("Investigate reconnect regressions after session restore");
255 expect(result.prompt).not.toContain("Attachment metadata:");
256 });
257​
258 it("includes attachment metadata when attachments are provided", () => {
259 const result = buildThreadTitlePrompt({
260 message: "Name this thread from the screenshot",
261 attachments: [
262 {
263 type: "image" as const,
264 id: "att-456",
265 name: "thread.png",
266 mimeType: "image/png",
267 sizeBytes: 67890,
268 },
269 ],
270 });
271​
272 expect(result.prompt).toContain("Attachment metadata:");
273 expect(result.prompt).toContain("thread.png");
274 expect(result.prompt).toContain("image/png");
275 expect(result.prompt).toContain("67890 bytes");
276 });
277​
278 it("regenerates from recent thread contents and identifies the previous title", () => {
279 const result = buildThreadTitlePrompt({
280 message: `USER:\nInvestigate reconnect regressions\n\nASSISTANT:\nThe remaining issue is stale session state`,
281 previousTitle: "Investigate reconnect regressions",
282 });
283​
284 expect(result.prompt).toContain(
285 "Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.",
286 );
287 expect(result.prompt).toContain('The previous title was "Investigate reconnect regressions".');
288 expect(result.prompt).toContain("Thread contents:");
289 expect(result.prompt).toContain("The remaining issue is stale session state");
290 });
291​
292 it("keeps the latest thread contents when regeneration context is truncated", () => {
293 const result = buildThreadTitlePrompt({
294 message: `${"old context ".repeat(1_000)}\n\nASSISTANT:\nCurrent thread state`,
295 previousTitle: "Old title",
296 });
297​
298 expect(result.prompt).toContain("[Earlier content truncated]");
299 expect(result.prompt).toContain("Current thread state");
300 expect(result.prompt).not.toContain("[truncated]");
301 });
302​
303 it("does not truncate an already-marked regeneration context twice", () => {
304 const retainedContext = "x".repeat(7_998);
305 const result = buildThreadTitlePrompt({
306 message: `[Earlier content truncated]\n\n${retainedContext}`,
307 previousTitle: "Old title",
308 });
309​
310 expect(result.prompt).toContain(
311 `Thread contents:\n[Earlier content truncated]\n\n${retainedContext}`,
312 );
313 expect(result.prompt.match(/\[Earlier content truncated\]/g)).toHaveLength(1);
314 });
315});
316​
317describe("sanitizeThreadTitle", () => {
318 it.each([
319 '{"title": "Refresh ev-stg APP ASG instances"}',
320 '{\n "title": "Refresh ev-stg APP ASG instances"\n}',
321 ])("unwraps a JSON title before normalizing: %s", (raw) => {
322 expect(sanitizeThreadTitle(raw)).toBe("Refresh ev-stg APP ASG instances");
323 });
324​
325 it.each([
326 "Rolling ES Refresh ev-stg",
327 "Fix {title} interpolation",
328 '{"title": 42}',
329 '{"subject": "Fix parsing"}',
330 '{"title": "unfinished}',
331 ])("preserves text that is not a JSON title: %s", (raw) => {
332 expect(sanitizeThreadTitle(raw)).toBe(raw);
333 });
334​
335 it("normalizes the extracted title", () => {
336 expect(sanitizeThreadTitle('{"title": " Fix reconnect failures "}')).toBe(
337 "Fix reconnect failures",
338 );
339 expect(sanitizeThreadTitle('{"title": " "}')).toBe("New thread");
340 expect(
341 sanitizeThreadTitle(
342 '{"title": "Reconnect failures after restart because the session state does not recover"}',
343 ),
344 ).toBe("Reconnect failures after restart because the session state does not recover");
345 });
346​
347 it("keeps complete titles for client display truncation", () => {
348 expect(
349 sanitizeThreadTitle(
350 ' "Reconnect failures after restart because the session state does not recover" ',
351 ),
352 ).toBe("Reconnect failures after restart because the session state does not recover");
353 });
354​
355 it("caps runaway titles so a paragraph cannot reach the sidebar", () => {
356 const words = Array.from({ length: 40 }, (_, index) => `word${index}`).join(" ");
357 const title = sanitizeThreadTitle(words);
358 expect(title.length).toBeLessThanOrEqual(120);
359 expect(title.endsWith("...")).toBe(true);
360 });
361});
362​
363describe("normalizeCliError", () => {
364 it("detects 'Command not found' and includes CLI name in the message", () => {
365 const error = normalizeCliError(
366 "claude",
367 "generateCommitMessage",
368 new Error("Command not found: claude"),
369 "Something went wrong",
370 );
371​
372 expect(error).toBeInstanceOf(TextGenerationError);
373 expect(error.detail).toContain("Claude CLI");
374 expect(error.detail).toContain("not available on PATH");
375 });
376​
377 it("uses the CLI name from the first argument for codex", () => {
378 const error = normalizeCliError(
379 "codex",
380 "generateBranchName",
381 new Error("Command not found: codex"),
382 "Something went wrong",
383 );
384​
385 expect(error).toBeInstanceOf(TextGenerationError);
386 expect(error.detail).toContain("Codex CLI");
387 expect(error.detail).toContain("not available on PATH");
388 });
389​
390 it("returns the error as-is if it is already a TextGenerationError", () => {
391 const existing = new TextGenerationError({
392 operation: "generatePrContent",
393 detail: "Already wrapped",
394 });
395​
396 const result = normalizeCliError("claude", "generatePrContent", existing, "fallback");
397​
398 expect(result).toBe(existing);
399 });
400​
401 it("wraps unknown non-Error values with the fallback message", () => {
402 const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback");
403​
404 expect(result).toBeInstanceOf(TextGenerationError);
405 expect(result.detail).toBe("fallback");
406 });
407​
408 it("does not expose CLI failure details in the public error message", () => {
409 const result = normalizeCliError(
410 "codex",
411 "generateCommitMessage",
412 new Error("request failed with access_token=secret-token"),
413 "Failed to generate a commit message",
414 );
415​
416 expect(result.detail).toBe("Failed to generate a commit message");
417 expect(result.message).not.toContain("secret-token");
418 });
419});