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

TextGenerationPrompts.test.ts

365 lines13.2 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("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("buildThreadTitlePrompt", () => {
186 it("requires each generated field in the strict response schema", () => {
187 const { outputSchema } = buildThreadTitlePrompt({ message: "Fix this" });
188 expect(toJsonSchemaObject(outputSchema)).toMatchObject({
189 required: ["title", "needsRefinement"],
190 properties: { title: { type: "string" }, needsRefinement: { type: "boolean" } },
191 });
192 });
193​
194 it("includes the user message without absent attachment metadata", () => {
195 const result = buildThreadTitlePrompt({
196 message: "Investigate reconnect regressions after session restore",
197 });
198​
199 expect(result.prompt).toContain("User message:");
200 expect(result.prompt).toContain("Investigate reconnect regressions after session restore");
201 expect(result.prompt).not.toContain("Attachment metadata:");
202 });
203​
204 it("includes attachment metadata when attachments are provided", () => {
205 const result = buildThreadTitlePrompt({
206 message: "Name this thread from the screenshot",
207 attachments: [
208 {
209 type: "image" as const,
210 id: "att-456",
211 name: "thread.png",
212 mimeType: "image/png",
213 sizeBytes: 67890,
214 },
215 ],
216 });
217​
218 expect(result.prompt).toContain("Attachment metadata:");
219 expect(result.prompt).toContain("thread.png");
220 expect(result.prompt).toContain("image/png");
221 expect(result.prompt).toContain("67890 bytes");
222 });
223​
224 it("regenerates from recent thread contents and identifies the previous title", () => {
225 const result = buildThreadTitlePrompt({
226 message: `USER:\nInvestigate reconnect regressions\n\nASSISTANT:\nThe remaining issue is stale session state`,
227 previousTitle: "Investigate reconnect regressions",
228 });
229​
230 expect(result.prompt).toContain(
231 "Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.",
232 );
233 expect(result.prompt).toContain('The previous title was "Investigate reconnect regressions".');
234 expect(result.prompt).toContain("Thread contents:");
235 expect(result.prompt).toContain("The remaining issue is stale session state");
236 });
237​
238 it("keeps the latest thread contents when regeneration context is truncated", () => {
239 const result = buildThreadTitlePrompt({
240 message: `${"old context ".repeat(1_000)}\n\nASSISTANT:\nCurrent thread state`,
241 previousTitle: "Old title",
242 });
243​
244 expect(result.prompt).toContain("[Earlier content truncated]");
245 expect(result.prompt).toContain("Current thread state");
246 expect(result.prompt).not.toContain("[truncated]");
247 });
248​
249 it("does not truncate an already-marked regeneration context twice", () => {
250 const retainedContext = "x".repeat(7_998);
251 const result = buildThreadTitlePrompt({
252 message: `[Earlier content truncated]\n\n${retainedContext}`,
253 previousTitle: "Old title",
254 });
255​
256 expect(result.prompt).toContain(
257 `Thread contents:\n[Earlier content truncated]\n\n${retainedContext}`,
258 );
259 expect(result.prompt.match(/\[Earlier content truncated\]/g)).toHaveLength(1);
260 });
261});
262​
263describe("sanitizeThreadTitle", () => {
264 it.each([
265 '{"title": "Refresh ev-stg APP ASG instances"}',
266 '{\n "title": "Refresh ev-stg APP ASG instances"\n}',
267 ])("unwraps a JSON title before normalizing: %s", (raw) => {
268 expect(sanitizeThreadTitle(raw)).toBe("Refresh ev-stg APP ASG instances");
269 });
270​
271 it.each([
272 "Rolling ES Refresh ev-stg",
273 "Fix {title} interpolation",
274 '{"title": 42}',
275 '{"subject": "Fix parsing"}',
276 '{"title": "unfinished}',
277 ])("preserves text that is not a JSON title: %s", (raw) => {
278 expect(sanitizeThreadTitle(raw)).toBe(raw);
279 });
280​
281 it("normalizes the extracted title", () => {
282 expect(sanitizeThreadTitle('{"title": " Fix reconnect failures "}')).toBe(
283 "Fix reconnect failures",
284 );
285 expect(sanitizeThreadTitle('{"title": " "}')).toBe("New thread");
286 expect(
287 sanitizeThreadTitle(
288 '{"title": "Reconnect failures after restart because the session state does not recover"}',
289 ),
290 ).toBe("Reconnect failures after restart because the session state does not recover");
291 });
292​
293 it("keeps complete titles for client display truncation", () => {
294 expect(
295 sanitizeThreadTitle(
296 ' "Reconnect failures after restart because the session state does not recover" ',
297 ),
298 ).toBe("Reconnect failures after restart because the session state does not recover");
299 });
300​
301 it("caps runaway titles so a paragraph cannot reach the sidebar", () => {
302 const words = Array.from({ length: 40 }, (_, index) => `word${index}`).join(" ");
303 const title = sanitizeThreadTitle(words);
304 expect(title.length).toBeLessThanOrEqual(120);
305 expect(title.endsWith("...")).toBe(true);
306 });
307});
308​
309describe("normalizeCliError", () => {
310 it("detects 'Command not found' and includes CLI name in the message", () => {
311 const error = normalizeCliError(
312 "claude",
313 "generateCommitMessage",
314 new Error("Command not found: claude"),
315 "Something went wrong",
316 );
317​
318 expect(error).toBeInstanceOf(TextGenerationError);
319 expect(error.detail).toContain("Claude CLI");
320 expect(error.detail).toContain("not available on PATH");
321 });
322​
323 it("uses the CLI name from the first argument for codex", () => {
324 const error = normalizeCliError(
325 "codex",
326 "generateBranchName",
327 new Error("Command not found: codex"),
328 "Something went wrong",
329 );
330​
331 expect(error).toBeInstanceOf(TextGenerationError);
332 expect(error.detail).toContain("Codex CLI");
333 expect(error.detail).toContain("not available on PATH");
334 });
335​
336 it("returns the error as-is if it is already a TextGenerationError", () => {
337 const existing = new TextGenerationError({
338 operation: "generatePrContent",
339 detail: "Already wrapped",
340 });
341​
342 const result = normalizeCliError("claude", "generatePrContent", existing, "fallback");
343​
344 expect(result).toBe(existing);
345 });
346​
347 it("wraps unknown non-Error values with the fallback message", () => {
348 const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback");
349​
350 expect(result).toBeInstanceOf(TextGenerationError);
351 expect(result.detail).toBe("fallback");
352 });
353​
354 it("does not expose CLI failure details in the public error message", () => {
355 const result = normalizeCliError(
356 "codex",
357 "generateCommitMessage",
358 new Error("request failed with access_token=secret-token"),
359 "Failed to generate a commit message",
360 );
361​
362 expect(result.detail).toBe("Failed to generate a commit message");
363 expect(result.message).not.toContain("secret-token");
364 });
365});