Skip to content

Commit 3b6f2c1

Browse files
author
daewoongoh
committed
fix(task-title): address pre-merge review findings
- Check the effective title profile against the current organization allow-list before each request; a prohibited profile gets only the fallback title. - Evict the cache in setAutoTitleIfAbsent only when the task file is confirmed missing, so a read or parse error cannot let a stale save overwrite a peer's fields. - Generate titles for prompts of any length and use the first 42 characters of the prompt as the fallback, as issue Zoo-Code-Org#2333 specifies. - Store only the task id, parent id, and profile for unscheduled candidates, and drop them when the task leaves the stack. - Strip markdown emphasis only around words so identifiers such as snake_case and __init__.py stay intact. - Add provider event-wiring tests and a SettingsView save test.
1 parent 5fbe82d commit 3b6f2c1

9 files changed

Lines changed: 448 additions & 95 deletions

File tree

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

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ interface DelegationRepairIntent {
7171
/**
7272
* Options for TaskHistoryStore constructor.
7373
*/
74+
type AutoTitleDiskRead = { kind: "found"; item: HistoryItem } | { kind: "missing" } | { kind: "unreadable" }
75+
7476
export interface TaskHistoryStoreOptions {
7577
/**
7678
* Optional callback invoked inside the write lock after each mutation
@@ -1027,19 +1029,18 @@ export class TaskHistoryStore {
10271029
/**
10281030
* Record a generated title unless the task already has one. The persisted record is re-checked
10291031
* under the per-file lock, so a task deleted by another host is never resurrected and a title
1030-
* written by another host is never overwritten.
1032+
* written by another host is never overwritten. Only a confirmed missing file evicts the cache:
1033+
* a read or parse failure leaves it intact so a later save still merges against a known record.
10311034
*/
10321035
public setAutoTitleIfAbsent(taskId: string, autoTitle: string): Promise<{ applied: boolean; item?: HistoryItem }> {
10331036
return this.withLock(async () => {
10341037
const title = autoTitle.trim()
1035-
const disk = await this.readTaskFile(taskId)
1036-
if (!disk || disk.id !== taskId) {
1037-
this.cache.delete(taskId)
1038-
return { applied: false }
1038+
const disk = await this.readTaskFileForAutoTitle(taskId)
1039+
if (disk.kind !== "found") {
1040+
return this.settleSkippedAutoTitle(taskId, disk)
10391041
}
1040-
if (disk.autoTitle || !title) {
1041-
this.cache.set(taskId, disk)
1042-
return { applied: false, item: disk }
1042+
if (disk.item.autoTitle || !title) {
1043+
return this.settleSkippedAutoTitle(taskId, disk)
10431044
}
10441045

10451046
const skipped = Symbol("auto-title-skipped")
@@ -1048,7 +1049,7 @@ export class TaskHistoryStore {
10481049
const filePath = await this.getTaskFilePath(taskId)
10491050
await safeWriteJson(
10501051
filePath,
1051-
{ ...disk, autoTitle: title },
1052+
{ ...disk.item, autoTitle: title },
10521053
{
10531054
merge: (existing) => {
10541055
const current = existing as Partial<HistoryItem> | null
@@ -1064,13 +1065,8 @@ export class TaskHistoryStore {
10641065
if (!(error instanceof Error) || !(skipped in error)) {
10651066
throw error
10661067
}
1067-
const latest = await this.readTaskFile(taskId)
1068-
if (latest) {
1069-
this.cache.set(taskId, latest)
1070-
} else {
1071-
this.cache.delete(taskId)
1072-
}
1073-
return { applied: false, item: latest ?? undefined }
1068+
// safeWriteJson reports both a missing and an unparsable file as `null`, so re-read to tell them apart.
1069+
return this.settleSkippedAutoTitle(taskId, await this.readTaskFileForAutoTitle(taskId))
10741070
}
10751071

10761072
if (!persisted) {
@@ -1084,6 +1080,35 @@ export class TaskHistoryStore {
10841080
})
10851081
}
10861082

1083+
private settleSkippedAutoTitle(taskId: string, disk: AutoTitleDiskRead): { applied: false; item?: HistoryItem } {
1084+
switch (disk.kind) {
1085+
case "found":
1086+
this.cache.set(taskId, disk.item)
1087+
return { applied: false, item: disk.item }
1088+
case "missing":
1089+
this.cache.delete(taskId)
1090+
return { applied: false }
1091+
case "unreadable":
1092+
return { applied: false, item: this.cache.get(taskId) }
1093+
}
1094+
}
1095+
1096+
private async readTaskFileForAutoTitle(taskId: string): Promise<AutoTitleDiskRead> {
1097+
let raw: string
1098+
try {
1099+
raw = await readFileWithMissingRetry(await this.getTaskFilePath(taskId))
1100+
} catch (error) {
1101+
return getErrorCode(error) === "ENOENT" ? { kind: "missing" } : { kind: "unreadable" }
1102+
}
1103+
try {
1104+
const item: unknown = JSON.parse(raw)
1105+
const id = typeof item === "object" && item !== null ? (item as { id?: unknown }).id : undefined
1106+
return id === taskId ? { kind: "found", item: item as HistoryItem } : { kind: "unreadable" }
1107+
} catch {
1108+
return { kind: "unreadable" }
1109+
}
1110+
}
1111+
10871112
/**
10881113
* Update two related HistoryItems within a single in-process lock acquisition.
10891114
* Both updaters run synchronously (no I/O, no lock re-entry). Both writes

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

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -496,14 +496,59 @@ describe("TaskHistoryStore real cross-host locking", () => {
496496
})
497497
})
498498

499-
it("rejects a record whose on-disk id does not match", async () => {
499+
const ioError = () => Object.assign(new Error("EIO: i/o error, read"), { code: "EIO" })
500+
// Each case corrupts the read and returns the file content that must remain on disk.
501+
const unreadableCases: Array<{ name: string; corrupt(storagePath: string, before: string): Promise<string> }> =
502+
[
503+
{
504+
name: "a read error",
505+
corrupt: async (_storagePath, before) => {
506+
vi.mocked(fs.readFile).mockRejectedValueOnce(ioError())
507+
return before
508+
},
509+
},
510+
{
511+
name: "unparsable JSON",
512+
corrupt: async (storagePath) => {
513+
await fs.writeFile(taskFile(storagePath), "{ torn")
514+
return "{ torn"
515+
},
516+
},
517+
{
518+
name: "a record with a different id",
519+
corrupt: async (storagePath) => {
520+
const other = JSON.stringify(item("other-task"))
521+
await fs.writeFile(taskFile(storagePath), other)
522+
return other
523+
},
524+
},
525+
]
526+
527+
it.each(unreadableCases)("keeps the cache and writes nothing on $name", async ({ corrupt }) => {
500528
await withTwoStores(async (storeA, _storeB, storagePath) => {
501-
await fs.writeFile(taskFile(storagePath), JSON.stringify(item("other-task")))
529+
const cached = storeA.get("shared-task")
530+
const expectedOnDisk = await corrupt(storagePath, await fs.readFile(taskFile(storagePath), "utf8"))
502531

503532
const result = await storeA.setAutoTitleIfAbsent("shared-task", "Title")
504-
expect(result).toEqual({ applied: false })
505-
expect(storeA.get("shared-task")).toBeUndefined()
506-
expect(JSON.parse(await fs.readFile(taskFile(storagePath), "utf8")).autoTitle).toBeUndefined()
533+
expect(result.applied).toBe(false)
534+
expect(storeA.get("shared-task")).toEqual(cached)
535+
expect(await fs.readFile(taskFile(storagePath), "utf8")).toBe(expectedOnDisk)
536+
})
537+
})
538+
539+
it("does not let a stale save overwrite a peer update after a read error", async () => {
540+
await withTwoStores(async (storeA, storeB) => {
541+
await storeA.upsert({ ...item("shared-task"), mode: "code" })
542+
const stale = storeA.get("shared-task")!
543+
await storeB.invalidate("shared-task")
544+
await storeB.upsert({ ...storeB.get("shared-task")!, mode: "architect" })
545+
546+
vi.mocked(fs.readFile).mockRejectedValueOnce(ioError())
547+
await storeA.setAutoTitleIfAbsent("shared-task", "Title")
548+
await storeA.upsert({ ...stale, tokensOut: 5 })
549+
550+
await storeB.invalidate("shared-task")
551+
expect(storeB.get("shared-task")).toMatchObject({ mode: "architect", tokensOut: 5 })
507552
})
508553
})
509554

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

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
11
import type { HistoryItem, ProviderSettings, TokenUsage } from "@roo-code/types"
22

3-
import {
4-
fallbackTitle,
5-
generateTaskTitle,
6-
normalizeWhitespace,
7-
TASK_TITLE_SHORT_PROMPT_CHARS,
8-
type GenerateTaskTitleOptions,
9-
} from "./generateTaskTitle"
3+
import { fallbackTitle, generateTaskTitle, type GenerateTaskTitleOptions } from "./generateTaskTitle"
104

115
export const TASK_TITLE_MAX_CONCURRENT = 2
126

@@ -30,6 +24,8 @@ export interface TaskTitleServiceDeps {
3024
getSettings(): Promise<TaskTitleSettings>
3125
/** Resolve a saved provider profile by id; `undefined` when it no longer exists. */
3226
resolveProfile(apiConfigId: string): Promise<ProviderSettings | undefined>
27+
/** Whether the current organization policy allows sending the prompt to this profile. */
28+
isProfileAllowed(profile: ProviderSettings): Promise<boolean>
3329
generate?(options: GenerateTaskTitleOptions): Promise<string | undefined>
3430
log?(message: string): void
3531
}
@@ -63,7 +59,17 @@ export class TaskTitleService {
6359
if (this.disposed || task.parentTaskId || this.deps.getHistoryItem(task.taskId)) {
6460
return
6561
}
66-
this.candidates.set(task.taskId, task)
62+
// Copy the fields so an unscheduled candidate does not keep the live task alive.
63+
const { taskId, parentTaskId, apiConfiguration } = task
64+
this.candidates.set(taskId, { taskId, parentTaskId, apiConfiguration })
65+
}
66+
67+
/**
68+
* Drop a task that left the stack before its first API usage. A title request that is already
69+
* scheduled keeps running, so switching tasks does not lose it.
70+
*/
71+
forget(taskId: string): void {
72+
this.candidates.delete(taskId)
6773
}
6874

6975
/** Called on every token-usage update; schedules once, after the first real API usage. */
@@ -162,9 +168,6 @@ export class TaskTitleService {
162168
if (!item || item.title || item.autoTitle) {
163169
return undefined
164170
}
165-
if (Array.from(normalizeWhitespace(item.task)).length <= TASK_TITLE_SHORT_PROMPT_CHARS) {
166-
return undefined
167-
}
168171
return { prompt: item.task, settings }
169172
}
170173

@@ -177,12 +180,15 @@ export class TaskTitleService {
177180
const taskProfile = job.task.apiConfiguration
178181
const titleProfile = settings.apiConfigId ? await this.deps.resolveProfile(settings.apiConfigId) : undefined
179182

183+
const profile = titleProfile ?? taskProfile
184+
180185
let title: string | undefined
181186
const rateLimited = (taskProfile.rateLimitSeconds ?? 0) > 0 || (titleProfile?.rateLimitSeconds ?? 0) > 0
182-
if (!rateLimited && !job.cancelReason) {
187+
// Checked per request: the organization policy may have changed since the task started.
188+
if (!rateLimited && !job.cancelReason && (await this.deps.isProfileAllowed(profile))) {
183189
try {
184190
title = await (this.deps.generate ?? generateTaskTitle)({
185-
profile: titleProfile ?? taskProfile,
191+
profile,
186192
prompt,
187193
customSupportPrompts: settings.customSupportPrompts,
188194
signal: job.controller.signal,

0 commit comments

Comments
 (0)