Skip to content

Commit 1b741fb

Browse files
committed
fix(task): make manual title writes disk-authoritative and drain deferred title writes
1 parent 7ad2959 commit 1b741fb

8 files changed

Lines changed: 330 additions & 24 deletions

File tree

‎src/api/providers/__tests__/kimi-code.spec.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,33 @@ describe("KimiCodeHandler", () => {
131131
expect(createCompletion).toHaveBeenCalledTimes(2)
132132
})
133133

134+
it("forwards the caller's cancellation and deadline to each completion attempt", async () => {
135+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" })
136+
const unauthorized = Object.assign(new Error("Unauthorized"), { status: 401 })
137+
const client = (
138+
handler as unknown as { client: { chat: { completions: { create: ReturnType<typeof vi.fn> } } } }
139+
).client
140+
const createCompletion = vi
141+
.spyOn(client.chat.completions, "create")
142+
.mockRejectedValueOnce(unauthorized)
143+
.mockResolvedValueOnce({ choices: [{ message: { content: "retried" } }] })
144+
const { signal } = new AbortController()
145+
146+
await expect(handler.completePrompt("test", { abortSignal: signal, timeoutMs: 5_000 })).resolves.toBe("retried")
147+
148+
// The retry after the forced refresh keeps the same options.
149+
expect(createCompletion).toHaveBeenNthCalledWith(2, expect.anything(), { signal, timeout: 5_000 })
150+
})
151+
152+
it("does not start preparation when the caller already aborted", async () => {
153+
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "oauth" })
154+
const controller = new AbortController()
155+
controller.abort()
156+
157+
await expect(handler.completePrompt("test", { abortSignal: controller.signal })).rejects.toThrow()
158+
expect(mockGetAccessToken).not.toHaveBeenCalled()
159+
})
160+
134161
it("does not retry on 401 when using API key auth", async () => {
135162
const handler = new KimiCodeHandler({ kimiCodeAuthMethod: "api-key", kimiCodeApiKey: "key" })
136163
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response(null, { status: 401 }))

‎src/api/providers/kimi-code.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,15 @@ import {
1313
import type { ApiHandlerOptions, GetModelsOptions } from "../../shared/api"
1414
import { kimiCodeOAuthManager } from "../../integrations/kimi-code/oauth"
1515

16-
import type { ApiHandlerCreateMessageMetadata, ModelCacheScope } from "../index"
16+
import type { ApiHandlerCreateMessageMetadata, CompletePromptOptions, ModelCacheScope } from "../index"
1717
import type { ApiStream } from "../transform/stream"
1818
import { getModelParams } from "../transform/model-params"
1919

2020
import { OpenAiHandler } from "./openai"
2121
import { NOT_PROVIDED } from "./constants"
2222
import { getModels } from "./fetchers/modelCache"
2323
import { getKimiCodeModels } from "./fetchers/kimi-code"
24+
import { throwIfAborted } from "./utils/abort-signal"
2425

2526
const OAUTH_AUTH_METHOD: KimiCodeAuthMethod = "oauth"
2627
const API_KEY_AUTH_METHOD: KimiCodeAuthMethod = "api-key"
@@ -72,8 +73,11 @@ export class KimiCodeHandler extends OpenAiHandler {
7273
return token
7374
}
7475

75-
private async prepareRequest(forceRefresh = false): Promise<void> {
76+
private async prepareRequest(forceRefresh = false, abortSignal?: AbortSignal): Promise<void> {
77+
throwIfAborted(abortSignal)
7678
const accessToken = await this.resolveAccessToken(forceRefresh)
79+
// Token resolution (including an OAuth refresh) may outlive the caller's cancellation.
80+
throwIfAborted(abortSignal)
7781
this.client.apiKey = accessToken
7882
if (!this.modelDiscoveryAttempted) {
7983
this.modelDiscoveryAttempted = true
@@ -107,14 +111,16 @@ export class KimiCodeHandler extends OpenAiHandler {
107111
}
108112
}
109113

110-
override async completePrompt(prompt: string): Promise<string> {
111-
await this.prepareRequest()
114+
override async completePrompt(prompt: string, options?: CompletePromptOptions): Promise<string> {
115+
// Preparation and both attempts run under the caller's cancellation and deadline, so a
116+
// superseded title request stops instead of finishing its token and model work.
117+
await this.prepareRequest(false, options?.abortSignal)
112118
try {
113-
return await super.completePrompt(prompt)
119+
return await super.completePrompt(prompt, options)
114120
} catch (error) {
115121
if (getHttpStatus(error) !== 401 || !this.canRefreshOAuth()) throw error
116-
await this.prepareRequest(true)
117-
return super.completePrompt(prompt)
122+
await this.prepareRequest(true, options?.abortSignal)
123+
return super.completePrompt(prompt, options)
118124
}
119125
}
120126

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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1089,6 +1089,64 @@ export class TaskHistoryStore {
10891089
})
10901090
}
10911091

1092+
/**
1093+
* Apply a user's manual title (or clear it) to the record persisted on disk.
1094+
*
1095+
* The write runs inside the per-file lock and merges into the disk record, so a
1096+
* clear removes a title another instance wrote even when this cache never saw
1097+
* it, and a manual title is never reverted by a stale cached snapshot.
1098+
*
1099+
* @returns The written item, or undefined when the record was deleted or is unusable
1100+
* on disk (the stale cache entry is dropped and the disk record is left untouched).
1101+
*/
1102+
public setTitleManually(taskId: string, title: string | undefined): Promise<HistoryItem | undefined> {
1103+
return this.withLock(async () => {
1104+
const cached = this.cache.get(taskId)
1105+
if (!cached) {
1106+
return undefined
1107+
}
1108+
1109+
// A clear is persisted as an explicit intent, so a later automatic title cannot
1110+
// mistake "no title" for "never titled".
1111+
const delta: Partial<HistoryItem> = title ? { title } : { title: undefined, titleCleared: true }
1112+
const filePath = await this.getTaskFilePath(taskId)
1113+
let written: HistoryItem = { ...cached, ...delta }
1114+
try {
1115+
await safeWriteJson(filePath, written, {
1116+
merge: (existing, incoming) => {
1117+
if (!existing || typeof existing !== "object" || !("id" in existing)) {
1118+
throw new TitleWriteSkipped("missing")
1119+
}
1120+
// The manual write targets the record that is actually persisted: a cached
1121+
// snapshot does not know which of the fields on disk are newer.
1122+
const parsed = historyItemSchema.safeParse(existing)
1123+
if (!parsed.success) {
1124+
throw new TitleWriteSkipped("invalid")
1125+
}
1126+
if (parsed.data.id !== taskId) {
1127+
throw new TitleWriteSkipped("mismatched")
1128+
}
1129+
written = mergeHistoryDelta(existing, incoming as HistoryItem, delta)
1130+
return written
1131+
},
1132+
})
1133+
} catch (error) {
1134+
if (!(error instanceof TitleWriteSkipped)) {
1135+
throw error
1136+
}
1137+
this.cache.delete(taskId)
1138+
this.taskFileMtimes.delete(taskId)
1139+
return undefined
1140+
}
1141+
1142+
this.cache.set(taskId, written)
1143+
if (this.onWrite) {
1144+
await this.onWrite(this.getAll())
1145+
}
1146+
return written
1147+
})
1148+
}
1149+
10921150
/**
10931151
* Read a HistoryItem from the in-memory cache and write back an updated version,
10941152
* all within a single lock acquisition so no concurrent writer can interleave

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

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,126 @@ describe("TaskHistoryStore cross-instance safety", () => {
236236
})
237237
})
238238

239+
describe("setTitleManually", () => {
240+
it("removes a title another instance wrote even when this cache has none", async () => {
241+
await storeA.initialize()
242+
await storeB.initialize()
243+
await storeA.upsert(makeHistoryItem({ id: "manual-clear", task: "Prompt" }))
244+
await storeB.reconcile()
245+
246+
// Instance B renames the task on disk; instance A's cache still has no title.
247+
await storeB.atomicReadAndUpdate("manual-clear", (item) => ({ ...item, title: "Manual title" }))
248+
expect(storeA.get("manual-clear")?.title).toBeUndefined()
249+
250+
// A clear from instance A must remove the disk title, not just the cached one.
251+
await expect(storeA.setTitleManually("manual-clear", undefined)).resolves.toMatchObject({
252+
id: "manual-clear",
253+
titleCleared: true,
254+
})
255+
256+
const filePath = path.join(tmpDir, "tasks", "manual-clear", GlobalFileNames.historyItem)
257+
const onDisk = JSON.parse(await fs.readFile(filePath, "utf8"))
258+
expect(onDisk.title).toBeUndefined()
259+
expect(onDisk.titleCleared).toBe(true)
260+
})
261+
262+
it("keeps a manual title that commits while the automatic title is generating", async () => {
263+
await storeA.initialize()
264+
await storeB.initialize()
265+
await storeA.upsert(makeHistoryItem({ id: "manual-wins", task: "Prompt" }))
266+
await storeB.reconcile()
267+
268+
await storeB.setTitleManually("manual-wins", "Manual title")
269+
// The generating host still has the untitled record cached.
270+
expect(storeA.get("manual-wins")?.title).toBeUndefined()
271+
272+
await expect(storeA.setTitleIfUnset("manual-wins", "Auto title")).resolves.toBe("conflict")
273+
expect(storeA.get("manual-wins")?.title).toBe("Manual title")
274+
})
275+
276+
it("returns undefined for a task that is not in the cache", async () => {
277+
await storeA.initialize()
278+
await expect(storeA.setTitleManually("missing-id", "Manual title")).resolves.toBeUndefined()
279+
})
280+
281+
it("drops the cache entry for a malformed disk record without rewriting it", async () => {
282+
await storeA.initialize()
283+
await storeA.upsert(makeHistoryItem({ id: "manual-malformed", task: "Prompt" }))
284+
const filePath = path.join(tmpDir, "tasks", "manual-malformed", GlobalFileNames.historyItem)
285+
const malformed = JSON.stringify({ id: 123 })
286+
await fs.writeFile(filePath, malformed, "utf8")
287+
288+
await expect(storeA.setTitleManually("manual-malformed", "Manual title")).resolves.toBeUndefined()
289+
290+
expect(storeA.get("manual-malformed")).toBeUndefined()
291+
expect(await fs.readFile(filePath, "utf8")).toBe(malformed)
292+
})
293+
294+
it("drops the cache entry when the disk record belongs to another task", async () => {
295+
await storeA.initialize()
296+
await storeA.upsert(makeHistoryItem({ id: "manual-mismatched", task: "Prompt" }))
297+
const filePath = path.join(tmpDir, "tasks", "manual-mismatched", GlobalFileNames.historyItem)
298+
const otherTask = JSON.stringify(makeHistoryItem({ id: "other-task" }), null, "\t")
299+
await fs.writeFile(filePath, otherTask, "utf8")
300+
301+
await expect(storeA.setTitleManually("manual-mismatched", "Manual title")).resolves.toBeUndefined()
302+
303+
expect(storeA.get("manual-mismatched")).toBeUndefined()
304+
expect(await fs.readFile(filePath, "utf8")).toBe(otherTask)
305+
})
306+
307+
it("re-throws unexpected errors from safeWriteJson", async () => {
308+
await storeA.initialize()
309+
await storeA.upsert(makeHistoryItem({ id: "manual-io-err", task: "Prompt" }))
310+
const { safeWriteJson } = await import("../../../utils/safeWriteJson")
311+
vi.mocked(safeWriteJson).mockRejectedValueOnce(new Error("disk IO error"))
312+
313+
await expect(storeA.setTitleManually("manual-io-err", "Manual title")).rejects.toThrow("disk IO error")
314+
})
315+
316+
it("notifies onWrite when a manual title is applied", async () => {
317+
const onWriteSpy = vi.fn().mockResolvedValue(undefined)
318+
const storeWithOnWrite = new TaskHistoryStore(tmpDir, { onWrite: onWriteSpy })
319+
await storeWithOnWrite.initialize()
320+
await storeWithOnWrite.upsert(makeHistoryItem({ id: "manual-onwrite", task: "Prompt" }))
321+
onWriteSpy.mockClear()
322+
323+
await expect(storeWithOnWrite.setTitleManually("manual-onwrite", "Notified title")).resolves.toMatchObject({
324+
id: "manual-onwrite",
325+
title: "Notified title",
326+
})
327+
expect(onWriteSpy).toHaveBeenCalledWith(
328+
expect.arrayContaining([expect.objectContaining({ id: "manual-onwrite", title: "Notified title" })]),
329+
)
330+
storeWithOnWrite.dispose()
331+
})
332+
333+
it("writes a title on a record this cache has never seen the latest fields of", async () => {
334+
await storeA.initialize()
335+
await storeB.initialize()
336+
await storeA.upsert(makeHistoryItem({ id: "manual-set", task: "Prompt", tokensIn: 1 }))
337+
await storeB.reconcile()
338+
339+
await storeB.atomicReadAndUpdate("manual-set", (item) => ({ ...item, tokensIn: 99 }))
340+
await storeA.setTitleManually("manual-set", "Manual title")
341+
342+
const filePath = path.join(tmpDir, "tasks", "manual-set", GlobalFileNames.historyItem)
343+
const onDisk = JSON.parse(await fs.readFile(filePath, "utf8"))
344+
expect(onDisk).toMatchObject({ title: "Manual title", tokensIn: 99 })
345+
})
346+
347+
it("drops the task when another instance deleted it", async () => {
348+
await storeA.initialize()
349+
await storeB.initialize()
350+
await storeA.upsert(makeHistoryItem({ id: "manual-deleted", task: "Prompt" }))
351+
await storeB.reconcile()
352+
await storeB.delete("manual-deleted")
353+
354+
await expect(storeA.setTitleManually("manual-deleted", "Manual title")).resolves.toBeUndefined()
355+
expect(storeA.get("manual-deleted")).toBeUndefined()
356+
})
357+
})
358+
239359
it("two instances can write different tasks without conflict", async () => {
240360
await storeA.initialize()
241361
await storeB.initialize()

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -856,6 +856,71 @@ describe("flushPendingSessionTitle", () => {
856856
expect(applySpy).toHaveBeenCalledTimes(1)
857857
})
858858

859+
it("does not restore a pending title when the generation is cancelled before the retry", async () => {
860+
const recorder = createCompletePromptRecorder(async () => "Generated Title")
861+
let historyItemPersisted = false
862+
const applySpy = vi.fn().mockImplementation(async () => {
863+
// The task is deleted or renamed while the write is in flight.
864+
cancelSessionTitle("task-not-ready-cancelled")
865+
return historyItemPersisted ? "applied" : "not-ready"
866+
})
867+
const provider = createTitleProvider({ applySessionTitle: applySpy })
868+
869+
await generateSessionTitle({
870+
provider,
871+
taskId: "task-not-ready-cancelled",
872+
userMessage: "Fix the login bug",
873+
apiConfiguration: testApiConfiguration,
874+
completePrompt: recorder.fn,
875+
})
876+
877+
// The cancelled generation must not queue a title that a later save would apply.
878+
historyItemPersisted = true
879+
await flushPendingSessionTitle("task-not-ready-cancelled")
880+
expect(applySpy).toHaveBeenCalledTimes(1)
881+
})
882+
883+
it("drains a deferred title write before the store is released", async () => {
884+
let releaseWrite!: () => void
885+
const writeGate = new Promise<void>((resolve) => {
886+
releaseWrite = resolve
887+
})
888+
let historyItemPersisted = false
889+
const provider = createTitleProvider({
890+
applySessionTitle: async () => {
891+
if (!historyItemPersisted) {
892+
return "not-ready"
893+
}
894+
await writeGate
895+
return "applied"
896+
},
897+
})
898+
const recorder = createCompletePromptRecorder(async () => "Generated Title")
899+
900+
await generateSessionTitle({
901+
provider,
902+
taskId: "task-drain-flush",
903+
userMessage: "Fix the login bug",
904+
apiConfiguration: testApiConfiguration,
905+
completePrompt: recorder.fn,
906+
})
907+
908+
historyItemPersisted = true
909+
void flushPendingSessionTitle("task-drain-flush")
910+
911+
let drained = false
912+
const drain = drainSessionTitles(provider).then(() => {
913+
drained = true
914+
})
915+
await new Promise((resolve) => setTimeout(resolve, 10))
916+
// The drain waits for the deferred write instead of releasing the store underneath it.
917+
expect(drained).toBe(false)
918+
919+
releaseWrite()
920+
await drain
921+
expect(drained).toBe(true)
922+
})
923+
859924
it("does nothing when no title is pending", async () => {
860925
await expect(flushPendingSessionTitle("unknown-task")).resolves.toBeUndefined()
861926
})

0 commit comments

Comments
 (0)