Skip to content

Commit 3d4776e

Browse files
byapparovclaude
andcommitted
fix(run): title from the typed prompt, by code point (#154 review)
The default title was derived from the message sent to the model, which re-quotes multi-word args, so `aictrl run "fix the login bug"` was titled with literal quotes. Build it from the positional words as typed, falling back to the stdin message only when no words were given. Truncate titles by code point so an emoji at the cut is not split into a lone surrogate, document the command-run default in the --title help, and bind the test fixture server to loopback. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent de32c74 commit 3d4776e

2 files changed

Lines changed: 118 additions & 92 deletions

File tree

‎packages/cli/src/cli/cmd/run.ts‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,9 @@ function normalizePath(input?: string) {
302302
}
303303

304304
function truncatedTitle(text: string) {
305-
return text.slice(0, 50) + (text.length > 50 ? "..." : "")
305+
// Count code points so an emoji or other astral character is never split in half.
306+
const chars = [...text]
307+
return chars.slice(0, 50).join("") + (chars.length > 50 ? "..." : "")
306308
}
307309

308310
/**
@@ -313,13 +315,20 @@ function truncatedTitle(text: string) {
313315
*
314316
* @internal exported for unit-testing only
315317
*/
316-
export function sessionTitle(input: { title?: string; message: string; command?: string }) {
318+
export function sessionTitle(input: {
319+
title?: string
320+
/** The positional words as typed, before they are re-quoted for the model. */
321+
prompt: string
322+
/** The message sent to the model: the re-quoted prompt plus any stdin. */
323+
message: string
324+
command?: string
325+
}) {
317326
if (input.title) return input.title
318-
// `--title ""` predates the default and keeps titling with the raw prompt.
327+
// `--title ""` predates the default and keeps titling with the raw message.
319328
if (input.title === "") return truncatedTitle(input.message)
320-
const prompt = input.message.trim()
321-
if (input.command) return truncatedTitle(`/${input.command} ${prompt}`.trimEnd())
322-
return truncatedTitle(prompt)
329+
const readable = input.prompt.trim() || input.message.trim()
330+
if (input.command) return truncatedTitle(`/${input.command} ${readable}`.trimEnd())
331+
return truncatedTitle(readable)
323332
}
324333

325334
export const RunCommand = cmd({
@@ -388,7 +397,7 @@ export const RunCommand = cmd({
388397
})
389398
.option("title", {
390399
type: "string",
391-
describe: "title for the session (defaults to the truncated prompt)",
400+
describe: "title for the session (defaults to the truncated prompt, or /<command> <args> for command runs)",
392401
})
393402
.option("attach", {
394403
type: "string",
@@ -421,9 +430,8 @@ export const RunCommand = cmd({
421430
process.exit(exit)
422431
}
423432

424-
let message = [...args.message, ...(args["--"] || [])]
425-
.map((arg) => (arg.includes(" ") ? `"${arg.replace(/"/g, '\\"')}"` : arg))
426-
.join(" ")
433+
const words = [...args.message, ...(args["--"] || [])]
434+
let message = words.map((arg) => (arg.includes(" ") ? `"${arg.replace(/"/g, '\\"')}"` : arg)).join(" ")
427435

428436
const directory = await (async () => {
429437
if (!args.dir) return undefined
@@ -518,7 +526,7 @@ export const RunCommand = cmd({
518526

519527
if (baseID) return baseID
520528

521-
const title = sessionTitle({ title: args.title, message, command: args.command })
529+
const title = sessionTitle({ title: args.title, prompt: words.join(" "), message, command: args.command })
522530
const result = await sdk.session.create(input(undefined, { title, permission: rules }))
523531
return result.data?.id
524532
}

‎packages/cli/test/cli/run-session-title.test.ts‎

Lines changed: 99 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -8,101 +8,119 @@ const TITLE_PROMPT = "Generate a title for this conversation"
88

99
describe("sessionTitle (#145)", () => {
1010
test("--title <text> is used as given", () => {
11-
expect(sessionTitle({ title: "Release notes", message: "Summarise the changes." })).toBe("Release notes")
11+
expect(sessionTitle({ title: "Release notes", prompt: "Summarise.", message: "Summarise." })).toBe("Release notes")
1212
})
1313

14-
test('--title "" keeps the raw prompt, truncated', () => {
15-
expect(sessionTitle({ title: "", message: "Summarise the changes.\n" })).toBe("Summarise the changes.\n")
16-
expect(sessionTitle({ title: "", message: "x".repeat(60) })).toBe("x".repeat(50) + "...")
14+
test('--title "" keeps the raw message, truncated', () => {
15+
const message = '"Summarise the changes."\n'
16+
expect(sessionTitle({ title: "", prompt: "Summarise the changes.", message })).toBe(message)
17+
expect(sessionTitle({ title: "", prompt: "", message: "x".repeat(60) })).toBe("x".repeat(50) + "...")
1718
})
1819

19-
test("defaults to the trimmed prompt, truncated", () => {
20-
expect(sessionTitle({ message: "\nSummarise the changes.\n" })).toBe("Summarise the changes.")
21-
expect(sessionTitle({ message: "x".repeat(60) })).toBe("x".repeat(50) + "...")
20+
test("defaults to the prompt as typed, without the quoting added for the model", () => {
21+
const message = '"fix the \\"login\\" bug"\n'
22+
expect(sessionTitle({ prompt: 'fix the "login" bug', message })).toBe('fix the "login" bug')
23+
expect(sessionTitle({ prompt: "x".repeat(60), message: "x".repeat(60) })).toBe("x".repeat(50) + "...")
24+
})
25+
26+
test("defaults to the trimmed message when the prompt only arrives on stdin", () => {
27+
expect(sessionTitle({ prompt: "", message: "\nReview this diff.\n" })).toBe("Review this diff.")
28+
})
29+
30+
test("truncates by code point, never splitting a surrogate pair", () => {
31+
const prompt = "a" + "\u{1F600}".repeat(60)
32+
expect(sessionTitle({ prompt, message: prompt })).toBe("a" + "\u{1F600}".repeat(49) + "...")
2233
})
2334

2435
test("defaults to the command and its arguments for command runs", () => {
25-
expect(sessionTitle({ message: "123\n", command: "review" })).toBe("/review 123")
26-
expect(sessionTitle({ message: "\n", command: "review" })).toBe("/review")
36+
expect(sessionTitle({ prompt: "this input", message: '"this input"\n', command: "check" })).toBe(
37+
"/check this input",
38+
)
39+
expect(sessionTitle({ prompt: "", message: "\n", command: "review" })).toBe("/review")
2740
})
2841
})
2942

3043
describe("headless run title generation (#145)", () => {
3144
test.each([
3245
["prompt", ["Check this input."]],
3346
["command", ["--command", "check", "this input"]],
34-
] as const)("a %s run without --title makes no title-generation request", async (_, input) => {
35-
await using tmp = await tmpdir()
36-
const requests: string[] = []
37-
const server = Bun.serve({
38-
port: 0,
39-
async fetch(request) {
40-
requests.push(await request.text())
41-
const chunk = {
42-
candidates: [{ index: 0, content: { role: "model", parts: [{ text: "Done." }] }, finishReason: "STOP" }],
43-
usageMetadata: { promptTokenCount: 7, candidatesTokenCount: 3, totalTokenCount: 10 },
44-
}
45-
return new Response(`data: ${JSON.stringify(chunk)}\n\n`, {
46-
headers: { "content-type": "text/event-stream" },
47-
})
48-
},
49-
})
50-
// Unlike the other run fixtures, the title agent stays enabled, and small_model routes
51-
// any title-generation request to this fixture server so the test can observe it.
52-
await Bun.write(
53-
path.join(tmp.path, "aictrl.json"),
54-
JSON.stringify({
55-
provider: {
56-
fixture: {
57-
npm: "@ai-sdk/google",
58-
options: { apiKey: "fixture", baseURL: `http://127.0.0.1:${server.port}` },
59-
models: { "gemini-fixture": { name: "fixture", limit: { context: 100000, output: 1000 } } },
60-
},
47+
] as const)(
48+
"a %s run without --title makes no title-generation request",
49+
async (_, input) => {
50+
await using tmp = await tmpdir()
51+
const requests: string[] = []
52+
const server = Bun.serve({
53+
hostname: "127.0.0.1",
54+
port: 0,
55+
async fetch(request) {
56+
requests.push(await request.text())
57+
const chunk = {
58+
candidates: [{ index: 0, content: { role: "model", parts: [{ text: "Done." }] }, finishReason: "STOP" }],
59+
usageMetadata: { promptTokenCount: 7, candidatesTokenCount: 3, totalTokenCount: 10 },
60+
}
61+
return new Response(`data: ${JSON.stringify(chunk)}\n\n`, {
62+
headers: { "content-type": "text/event-stream" },
63+
})
6164
},
62-
small_model: "fixture/gemini-fixture",
63-
command: { check: { template: "Check $ARGUMENTS." } },
64-
}),
65-
)
66-
const proc = Bun.spawn(
67-
[
68-
"bun",
69-
"run",
70-
"--conditions=browser",
71-
entry,
72-
"run",
73-
"--format",
74-
"json",
75-
"--model",
76-
"fixture/gemini-fixture",
77-
...input,
78-
],
79-
{
80-
cwd: tmp.path,
81-
env: {
82-
...process.env,
83-
AICTRL_DISABLE_DEFAULT_PLUGINS: "true",
84-
AICTRL_DISABLE_MODELS_FETCH: "true",
85-
AICTRL_DISABLE_AUTOCOMPACT: "true",
65+
})
66+
// Unlike the other run fixtures, the title agent stays enabled, and small_model routes
67+
// any title-generation request to this fixture server so the test can observe it.
68+
await Bun.write(
69+
path.join(tmp.path, "aictrl.json"),
70+
JSON.stringify({
71+
provider: {
72+
fixture: {
73+
npm: "@ai-sdk/google",
74+
options: { apiKey: "fixture", baseURL: `http://127.0.0.1:${server.port}` },
75+
models: { "gemini-fixture": { name: "fixture", limit: { context: 100000, output: 1000 } } },
76+
},
77+
},
78+
small_model: "fixture/gemini-fixture",
79+
command: { check: { template: "Check $ARGUMENTS." } },
80+
}),
81+
)
82+
const proc = Bun.spawn(
83+
[
84+
"bun",
85+
"run",
86+
"--conditions=browser",
87+
entry,
88+
"run",
89+
"--format",
90+
"json",
91+
"--model",
92+
"fixture/gemini-fixture",
93+
...input,
94+
],
95+
{
96+
cwd: tmp.path,
97+
env: {
98+
...process.env,
99+
AICTRL_DISABLE_DEFAULT_PLUGINS: "true",
100+
AICTRL_DISABLE_MODELS_FETCH: "true",
101+
AICTRL_DISABLE_AUTOCOMPACT: "true",
102+
},
103+
stdin: "ignore",
104+
stdout: "pipe",
105+
stderr: "pipe",
86106
},
87-
stdin: "ignore",
88-
stdout: "pipe",
89-
stderr: "pipe",
90-
},
91-
)
92-
const timeout = setTimeout(() => proc.kill("SIGKILL"), 15000)
93-
try {
94-
const [stdout, stderr, exit] = await Promise.all([
95-
new Response(proc.stdout).text(),
96-
new Response(proc.stderr).text(),
97-
proc.exited,
98-
])
99-
expect(exit, stderr + stdout).toBe(0)
100-
expect(requests.filter((body) => body.includes(TITLE_PROMPT))).toHaveLength(0)
101-
expect(requests).toHaveLength(1)
102-
} finally {
103-
clearTimeout(timeout)
104-
proc.kill("SIGKILL")
105-
server.stop(true)
106-
}
107-
}, 20000)
107+
)
108+
const timeout = setTimeout(() => proc.kill("SIGKILL"), 15000)
109+
try {
110+
const [stdout, stderr, exit] = await Promise.all([
111+
new Response(proc.stdout).text(),
112+
new Response(proc.stderr).text(),
113+
proc.exited,
114+
])
115+
expect(exit, stderr + stdout).toBe(0)
116+
expect(requests.filter((body) => body.includes(TITLE_PROMPT))).toHaveLength(0)
117+
expect(requests).toHaveLength(1)
118+
} finally {
119+
clearTimeout(timeout)
120+
proc.kill("SIGKILL")
121+
server.stop(true)
122+
}
123+
},
124+
20000,
125+
)
108126
})

0 commit comments

Comments
 (0)