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