Skip to content

Commit 27c9b1a

Browse files
author
daewoongoh
committed
fix(task): never recreate a deleted task when applying a title
Abort the locked title write when the on-disk record is missing or already titled, cut the fallback at 42 characters before collapsing whitespace, and cover the deleted-task and pending-say startup paths with tests.
1 parent 255d72a commit 27c9b1a

5 files changed

Lines changed: 84 additions & 18 deletions

File tree

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

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ 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+
class TitleWriteSkipped extends Error {
31+
constructor(readonly reason: "missing" | "titled") {
32+
super(`title write skipped: ${reason}`)
33+
}
34+
}
35+
2936
/**
3037
* Durable intent for the one repair that spans an active delegated child and
3138
* its parent. Task files remain authoritative; this file only records the
@@ -1002,7 +1009,7 @@ export class TaskHistoryStore {
10021009
* provider on the same storage path) saved a manual title, and a delta merge would
10031010
* otherwise overwrite it.
10041011
*
1005-
* @returns "conflict" when a title already exists (the cache is refreshed from disk).
1012+
* @returns "conflict" when a title already exists or the record was deleted on disk (the cache is refreshed).
10061013
* @throws If the task ID is not present in the cache.
10071014
*/
10081015
public setTitleIfUnset(taskId: string, title: string): Promise<"applied" | "conflict"> {
@@ -1017,23 +1024,37 @@ export class TaskHistoryStore {
10171024

10181025
const filePath = await this.getTaskFilePath(taskId)
10191026
let written: HistoryItem = { ...current, title }
1020-
let conflict = false
1021-
await safeWriteJson(filePath, written, {
1022-
merge: (existing, incoming) => {
1023-
if (existing && typeof existing === "object" && (existing as HistoryItem).title) {
1024-
conflict = true
1025-
written = existing as HistoryItem
1026-
return existing
1027+
try {
1028+
await safeWriteJson(filePath, written, {
1029+
merge: (existing, incoming) => {
1030+
// Throwing aborts the write, so a deleted record is never recreated from the cache
1031+
// and an existing title is never rewritten.
1032+
if (!existing || typeof existing !== "object" || !("id" in existing)) {
1033+
throw new TitleWriteSkipped("missing")
1034+
}
1035+
if ((existing as HistoryItem).title) {
1036+
throw new TitleWriteSkipped("titled")
1037+
}
1038+
written = mergeHistoryDelta(existing, incoming as HistoryItem, { title })
1039+
return written
1040+
},
1041+
})
1042+
} catch (error) {
1043+
if (!(error instanceof TitleWriteSkipped)) {
1044+
throw error
1045+
}
1046+
if (error.reason === "missing") {
1047+
this.cache.delete(taskId)
1048+
} else {
1049+
const diskItem = await this.readTaskFile(taskId)
1050+
if (diskItem) {
1051+
this.cache.set(taskId, diskItem)
10271052
}
1028-
written = mergeHistoryDelta(existing, incoming as HistoryItem, { title })
1029-
return written
1030-
},
1031-
})
1032-
1033-
this.cache.set(taskId, written)
1034-
if (conflict) {
1053+
}
10351054
return "conflict"
10361055
}
1056+
1057+
this.cache.set(taskId, written)
10371058
if (this.onWrite) {
10381059
await this.onWrite(this.getAll())
10391060
}

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,22 @@ describe("TaskHistoryStore cross-instance safety", () => {
9292
expect(storeB.get("title-task")?.title).toBe("Manual title")
9393
})
9494

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+
95111
it("applies the title when no instance has set one", async () => {
96112
await storeA.initialize()
97113
await storeA.upsert(makeHistoryItem({ id: "title-free", task: "Original prompt" }))

‎src/core/task/__tests__/Task.session-title.spec.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,29 @@ describe("Task#startTask session title trigger", () => {
173173
expect(resolved).toBe(true)
174174
})
175175

176+
it("starts title generation only after the first message is stored", async () => {
177+
const provider = createMockProvider()
178+
const task = createTestTask(provider)
179+
stubStartup(task)
180+
181+
let releaseSay: () => void = () => {}
182+
vi.spyOn(task, "say").mockImplementation(
183+
() =>
184+
new Promise<undefined>((resolve) => {
185+
releaseSay = () => resolve(undefined)
186+
}),
187+
)
188+
189+
const started = getStartTaskAccess(task).startTask("stored first")
190+
await Promise.resolve()
191+
expect(vi.mocked(generateSessionTitle)).not.toHaveBeenCalled()
192+
193+
releaseSay()
194+
await started
195+
196+
expect(lastTitleCall()?.userMessage).toBe("stored first")
197+
})
198+
176199
it("does not wait for a pending title before starting the task loop", async () => {
177200
const provider = createMockProvider()
178201
const task = createTestTask(provider)

‎src/core/task/__tests__/session-title.spec.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,12 @@ describe("fallbackTitle", () => {
107107
expect(fallbackTitle(input)).toBe(expected)
108108
})
109109

110+
it("cuts at the character limit before collapsing whitespace", () => {
111+
const input = "a".repeat(FALLBACK_TITLE_MAX_CHARS - 2) + " ".repeat(5) + "bcd"
112+
expect(fallbackTitle(input)).toBe("a".repeat(FALLBACK_TITLE_MAX_CHARS - 2))
113+
expect(fallbackTitle("ab" + " ".repeat(60) + "cd")).toBe("ab")
114+
})
115+
110116
it("caps the fallback at the character limit", () => {
111117
const long = "a".repeat(FALLBACK_TITLE_MAX_CHARS + 10)
112118
expect(fallbackTitle(long)).toBe("a".repeat(FALLBACK_TITLE_MAX_CHARS))

‎src/core/task/session-title.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@ export function extractLlmTitle(raw: string): string | undefined {
5151
return title.length > 0 ? title : undefined
5252
}
5353

54-
/** Start of the sanitized message with whitespace collapsed, capped at 42 characters. */
54+
/** First 42 characters of the sanitized message, then whitespace collapsed. */
5555
export function fallbackTitle(sanitized: string): string | undefined {
56-
const collapsed = sanitized.replace(/\s+/g, " ").trim()
57-
return collapsed ? collapsed.slice(0, FALLBACK_TITLE_MAX_CHARS).trim() : undefined
56+
const head = sanitized.trim().slice(0, FALLBACK_TITLE_MAX_CHARS)
57+
return head.replace(/\s+/g, " ").trim() || undefined
5858
}
5959

6060
type CompletePromptFn = typeof singleCompletionHandler

0 commit comments

Comments
 (0)