Skip to content

Commit d788264

Browse files
committed
feat(task): auto-generate session title from the first user message
1 parent bb6cbee commit d788264

8 files changed

Lines changed: 1390 additions & 5 deletions

File tree

‎src/core/task-persistence/TaskHistoryStore.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ function mergeWithDisk(delta: Partial<HistoryItem>): (existing: unknown, incomin
2626
return (existing, incoming) => mergeHistoryDelta(existing, incoming as HistoryItem, delta)
2727
}
2828

29+
/** Thrown inside the `setTitleIfUnset` merge callback to abort the write without touching the file. */
30+
// Stryker disable next-line StringLiteral: diagnostic error message only, caught internally
31+
class TitleWriteSkipped extends Error {
32+
constructor(readonly reason: "missing" | "titled") {
33+
super(`title write skipped: ${reason}`)
34+
}
35+
}
36+
2937
/**
3038
* Durable intent for the one repair that spans an active delegated child and
3139
* its parent. Task files remain authoritative; this file only records the
@@ -996,6 +1004,66 @@ export class TaskHistoryStore {
9961004

9971005
// ────────────────────────────── Atomic read-modify-write ──────────────────────────────
9981006

1007+
/**
1008+
* Set `title` only while the item has none, checking the title on disk inside the
1009+
* per-file lock. The cache can be stale when another store (for example a second
1010+
* provider on the same storage path) saved a manual title, and a delta merge would
1011+
* otherwise overwrite it.
1012+
*
1013+
* @returns "conflict" when a title already exists or the record was deleted on disk (the cache is refreshed).
1014+
* @throws If the task ID is not present in the cache.
1015+
*/
1016+
public setTitleIfUnset(taskId: string, title: string): Promise<"applied" | "conflict"> {
1017+
return this.withLock(async () => {
1018+
const current = this.cache.get(taskId)
1019+
if (!current) {
1020+
throw new Error(`[TaskHistoryStore] setTitleIfUnset: task ${taskId} not found in cache`)
1021+
}
1022+
if (current.title) {
1023+
return "conflict"
1024+
}
1025+
1026+
const filePath = await this.getTaskFilePath(taskId)
1027+
let written: HistoryItem = { ...current, title }
1028+
try {
1029+
await safeWriteJson(filePath, written, {
1030+
merge: (existing, incoming) => {
1031+
// Throwing aborts the write, so a deleted record is never recreated from the cache
1032+
// and an existing title is never rewritten.
1033+
// Stryker disable next-line ConditionalExpression: defense-in-depth, corrupted disk content cannot be merged
1034+
if (!existing || typeof existing !== "object" || !("id" in existing)) {
1035+
throw new TitleWriteSkipped("missing")
1036+
}
1037+
if ((existing as HistoryItem).title) {
1038+
throw new TitleWriteSkipped("titled")
1039+
}
1040+
written = mergeHistoryDelta(existing, incoming as HistoryItem, { title })
1041+
return written
1042+
},
1043+
})
1044+
} catch (error) {
1045+
if (!(error instanceof TitleWriteSkipped)) {
1046+
throw error
1047+
}
1048+
if (error.reason === "missing") {
1049+
this.cache.delete(taskId)
1050+
} else {
1051+
const diskItem = await this.readTaskFile(taskId)
1052+
if (diskItem) {
1053+
this.cache.set(taskId, diskItem)
1054+
}
1055+
}
1056+
return "conflict"
1057+
}
1058+
1059+
this.cache.set(taskId, written)
1060+
if (this.onWrite) {
1061+
await this.onWrite(this.getAll())
1062+
}
1063+
return "applied"
1064+
})
1065+
}
1066+
9991067
/**
10001068
* Read a HistoryItem from the in-memory cache and write back an updated version,
10011069
* all within a single lock acquisition so no concurrent writer can interleave

‎src/core/task-persistence/__tests__/TaskHistoryStore.crossInstance.spec.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,104 @@ describe("TaskHistoryStore cross-instance safety", () => {
7373
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {})
7474
})
7575

76+
describe("setTitleIfUnset", () => {
77+
it("keeps a manual title that another instance wrote after this cache was loaded", async () => {
78+
await storeA.initialize()
79+
await storeB.initialize()
80+
await storeA.upsert(makeHistoryItem({ id: "title-task", task: "Original prompt" }))
81+
await storeB.reconcile()
82+
expect(storeB.get("title-task")?.title).toBeUndefined()
83+
84+
// Instance A still caches no title when B renames the task on disk.
85+
await storeB.atomicReadAndUpdate("title-task", (item) => ({ ...item, title: "Manual title" }))
86+
expect(storeA.get("title-task")?.title).toBeUndefined()
87+
88+
await expect(storeA.setTitleIfUnset("title-task", "Auto title")).resolves.toBe("conflict")
89+
90+
expect(storeA.get("title-task")?.title).toBe("Manual title")
91+
await storeB.reconcile()
92+
expect(storeB.get("title-task")?.title).toBe("Manual title")
93+
})
94+
95+
it("does not recreate a task that another instance deleted", async () => {
96+
await storeA.initialize()
97+
await storeB.initialize()
98+
await storeA.upsert(makeHistoryItem({ id: "title-deleted", task: "Original prompt" }))
99+
await storeB.reconcile()
100+
101+
await storeB.delete("title-deleted")
102+
expect(storeA.get("title-deleted")).toBeDefined()
103+
104+
await expect(storeA.setTitleIfUnset("title-deleted", "Auto title")).resolves.toBe("conflict")
105+
106+
expect(storeA.get("title-deleted")).toBeUndefined()
107+
await storeB.reconcile()
108+
expect(storeB.get("title-deleted")).toBeUndefined()
109+
})
110+
111+
it("applies the title when no instance has set one", async () => {
112+
await storeA.initialize()
113+
await storeA.upsert(makeHistoryItem({ id: "title-free", task: "Original prompt" }))
114+
115+
await expect(storeA.setTitleIfUnset("title-free", "Auto title")).resolves.toBe("applied")
116+
117+
expect(storeA.get("title-free")).toMatchObject({ title: "Auto title", task: "Original prompt" })
118+
})
119+
120+
it("persists the title to disk so reloading from storage preserves it", async () => {
121+
await storeA.initialize()
122+
await storeA.upsert(makeHistoryItem({ id: "persist-check", task: "Original task prompt" }))
123+
124+
await expect(storeA.setTitleIfUnset("persist-check", "Persisted title")).resolves.toBe("applied")
125+
126+
// Reload a fresh store instance pointing to the same disk directory
127+
const storeReloaded = new TaskHistoryStore(tmpDir)
128+
await storeReloaded.initialize()
129+
130+
const diskItem = storeReloaded.get("persist-check")
131+
expect(diskItem).toBeDefined()
132+
expect(diskItem?.title).toBe("Persisted title")
133+
expect(diskItem?.task).toBe("Original task prompt")
134+
storeReloaded.dispose()
135+
})
136+
137+
it("throws when the task is not in the cache", async () => {
138+
await storeA.initialize()
139+
await expect(storeA.setTitleIfUnset("missing-id", "Auto title")).rejects.toThrow("not found in cache")
140+
})
141+
142+
it("returns conflict immediately when cached item already has a title", async () => {
143+
await storeA.initialize()
144+
await storeA.upsert(makeHistoryItem({ id: "already-titled", title: "Existing", task: "Prompt" }))
145+
await expect(storeA.setTitleIfUnset("already-titled", "New title")).resolves.toBe("conflict")
146+
})
147+
148+
it("notifies onWrite callback when title is successfully applied", async () => {
149+
const onWriteSpy = vi.fn().mockResolvedValue(undefined)
150+
const storeWithOnWrite = new TaskHistoryStore(tmpDir, { onWrite: onWriteSpy })
151+
await storeWithOnWrite.initialize()
152+
await storeWithOnWrite.upsert(makeHistoryItem({ id: "title-onwrite", task: "Prompt" }))
153+
onWriteSpy.mockClear()
154+
155+
await expect(storeWithOnWrite.setTitleIfUnset("title-onwrite", "Notified title")).resolves.toBe("applied")
156+
expect(onWriteSpy).toHaveBeenCalledWith(
157+
expect.arrayContaining([expect.objectContaining({ id: "title-onwrite", title: "Notified title" })]),
158+
)
159+
storeWithOnWrite.dispose()
160+
})
161+
162+
it("re-throws unexpected errors from safeWriteJson", async () => {
163+
await storeA.initialize()
164+
await storeA.upsert(makeHistoryItem({ id: "title-io-err", task: "Prompt" }))
165+
166+
const { safeWriteJson } = await import("../../../utils/safeWriteJson")
167+
const mockedSafeWrite = vi.mocked(safeWriteJson)
168+
mockedSafeWrite.mockRejectedValueOnce(new Error("disk IO error"))
169+
170+
await expect(storeA.setTitleIfUnset("title-io-err", "Auto title")).rejects.toThrow("disk IO error")
171+
})
172+
})
173+
76174
it("two instances can write different tasks without conflict", async () => {
77175
await storeA.initialize()
78176
await storeB.initialize()

‎src/core/task/Task.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ import { prepareApiConversationMessage } from "./apiConversationHistory"
145145
import { shouldAddUserMessageToHistory } from "./messageCounting"
146146
import { type TaskExecutionContext } from "./providerHandoff"
147147
import { initialRunState, type Ask, type RunEvent, type RunState } from "./run-state/runState"
148+
import { generateSessionTitle } from "./session-title"
148149
import { applyRunEvent, type RunRejection } from "./run-state/runStateShadow"
149150
import {
150151
divergenceKey,
@@ -286,6 +287,9 @@ export class PendingActionSettlementError extends Error {
286287
}
287288
}
288289

290+
// Literal, not the vscode enum: specs that mock "vscode" without ExtensionMode would throw on the read.
291+
const EXTENSION_MODE_TEST = 3
292+
289293
export class Task extends EventEmitter<TaskEvents> implements TaskLike {
290294
readonly taskId: string
291295
readonly rootTaskId?: string
@@ -3110,6 +3114,31 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
31103114

31113115
await this.say("text", task, images)
31123116

3117+
// Fire-and-forget session title generation: the run must never wait
3118+
// on it and no title failure may surface in the chat. Only a root
3119+
// task's first message triggers this — resumes go through
3120+
// resumeTaskFromHistory, subtask continuations re-enter the task
3121+
// loop directly, and both must keep their existing names. `say`
3122+
// above persisted the history item, so the conditional write will
3123+
// find it.
3124+
// The extra provider request would break E2E and visual tests that assert
3125+
// exact request sequences and rendered task names, so Test mode skips it.
3126+
if (!this.parentTask && task) {
3127+
const provider = this.providerRef.deref()
3128+
if (provider && provider.context.extensionMode !== EXTENSION_MODE_TEST) {
3129+
void generateSessionTitle({
3130+
provider,
3131+
taskId: this.taskId,
3132+
userMessage: task,
3133+
apiConfiguration: this.apiConfiguration,
3134+
}).catch((error) => {
3135+
// generateSessionTitle never rejects by contract; this
3136+
// arm is defense-in-depth for future regressions.
3137+
console.error(`[Task#startTask] session title generation failed: ${error}`)
3138+
})
3139+
}
3140+
}
3141+
31133142
// Check for too many MCP tools and warn the user
31143143
const { enabledToolCount, enabledServerCount } = await this.getEnabledMcpToolsCount()
31153144
if (enabledToolCount > MAX_MCP_TOOLS_THRESHOLD) {
@@ -4419,7 +4448,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
44194448
nativeToolCallParserScope,
44204449
)
44214450

4422-
// Stryker disable next-line ConditionalExpression, EqualityOperator: equivalent mutants, streamingKey is always defined here, so both conditions reduce to the partialToolUse check
4451+
// Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent mutants, streamingKey is always defined here, so both conditions reduce to the partialToolUse check
44234452
if (partialToolUse && streamingKey !== undefined) {
44244453
// Reuse the compound key built above: it is exactly the key the start event
44254454
// registered under, so the delta lookup needs no second encoding.
@@ -4855,7 +4884,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
48554884
// name (provider quirk), the compound-key lookup above misses and both the
48564885
// parser entry and the dedup tracking would stay stale. Resolve the tracked
48574886
// entry by id and target the real compound key for finalization and cleanup.
4858-
// Stryker disable next-line ConditionalExpression, LogicalOperator, EqualityOperator: equivalent mutants, the both-miss case is unreachable via the raw-chunk pipeline
4887+
// Stryker disable next-line ConditionalExpression,LogicalOperator,EqualityOperator: equivalent mutants, the both-miss case is unreachable via the raw-chunk pipeline
48594888
if (finalToolUse === null && toolUseIndex === undefined) {
48604889
const resolved = NativeToolCallParser.getStreamingToolCallById(
48614890
event.id,

0 commit comments

Comments
 (0)