Skip to content

Commit 2345d6b

Browse files
committed
fix(task): preserve manual title clears and respect rate limits in session titles
- Cancel in-flight session title generation when renaming or clearing a task so an auto-generated title never overwrites a user's manual clear. - Skip LLM completion and use fallback title immediately when provider rateLimitSeconds > 0. - Reinforce extractLlmTitle boundary tests with internal 'Title:' and quotes. - Fix formatting in Stryker disable directives to satisfy stryker-diff.
1 parent 27c9b1a commit 2345d6b

5 files changed

Lines changed: 188 additions & 23 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4448,7 +4448,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
44484448
nativeToolCallParserScope,
44494449
)
44504450

4451-
// 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
44524452
if (partialToolUse && streamingKey !== undefined) {
44534453
// Reuse the compound key built above: it is exactly the key the start event
44544454
// registered under, so the delta lookup needs no second encoding.
@@ -4884,7 +4884,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
48844884
// name (provider quirk), the compound-key lookup above misses and both the
48854885
// parser entry and the dedup tracking would stay stale. Resolve the tracked
48864886
// entry by id and target the real compound key for finalization and cleanup.
4887-
// 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
48884888
if (finalToolUse === null && toolUseIndex === undefined) {
48894889
const resolved = NativeToolCallParser.getStreamingToolCallById(
48904890
event.id,

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
SESSION_TITLE_TIMEOUT_MS,
1010
fallbackTitle,
1111
generateSessionTitle,
12+
cancelSessionTitle,
1213
sanitizeUserMessageForTitle,
1314
extractLlmTitle,
1415
type SessionTitleApplyResult,
@@ -83,6 +84,10 @@ describe("sanitizeUserMessageForTitle", () => {
8384
describe("extractLlmTitle", () => {
8485
it.each([
8586
["Fix login bug in auth flow", "Fix login bug in auth flow"],
87+
["Fix Title: parsing in task history", "Fix Title: parsing in task history"],
88+
['Fix "quoted" search terms', 'Fix "quoted" search terms'],
89+
['"Leading quote only', "Leading quote only"],
90+
['Trailing quote only"', "Trailing quote only"],
8691
["Title: Fix login bug", "Fix login bug"],
8792
["title: lowercase prefix", "lowercase prefix"],
8893
['"Quoted title"', "Quoted title"],
@@ -352,6 +357,66 @@ describe("generateSessionTitle", () => {
352357
expect(applied[0].title).toBe("First Title")
353358
})
354359

360+
it("aborts in-flight generation and does not apply title when cancelled", async () => {
361+
let abortSignal: AbortSignal | undefined
362+
let resolveCompletion!: (val: string) => void
363+
const completionPromise = new Promise<string>((resolve) => {
364+
resolveCompletion = resolve
365+
})
366+
const recorder = createCompletePromptRecorder(async ({ options }) => {
367+
abortSignal = options?.abortSignal
368+
return completionPromise
369+
})
370+
const applied: ApplyTitleCall[] = []
371+
const provider = createTitleProvider({
372+
applySessionTitle: async (taskId, title) => {
373+
applied.push({ taskId, title })
374+
return "applied"
375+
},
376+
})
377+
378+
const generation = generateSessionTitle({
379+
provider,
380+
taskId: "task-cancel",
381+
userMessage: "User prompt to name",
382+
apiConfiguration: testApiConfiguration,
383+
completePrompt: recorder.fn,
384+
})
385+
386+
expect(recorder.calls).toHaveLength(1)
387+
expect(abortSignal?.aborted).toBe(false)
388+
389+
cancelSessionTitle("task-cancel")
390+
391+
expect(abortSignal?.aborted).toBe(true)
392+
resolveCompletion("Generated title")
393+
await generation
394+
395+
expect(applied).toHaveLength(0)
396+
})
397+
398+
it("skips LLM completion and uses fallback title when rateLimitSeconds is set", async () => {
399+
const recorder = createCompletePromptRecorder(async () => "LLM Title")
400+
const applied: ApplyTitleCall[] = []
401+
const provider = createTitleProvider({
402+
applySessionTitle: async (taskId, title) => {
403+
applied.push({ taskId, title })
404+
return "applied"
405+
},
406+
})
407+
408+
await generateSessionTitle({
409+
provider,
410+
taskId: "task-ratelimit",
411+
userMessage: "Fix urgent production issue in login flow",
412+
apiConfiguration: { ...testApiConfiguration, rateLimitSeconds: 5 },
413+
completePrompt: recorder.fn,
414+
})
415+
416+
expect(recorder.calls).toHaveLength(0)
417+
expect(applied).toEqual([{ taskId: "task-ratelimit", title: "Fix urgent production issue in login flow" }])
418+
})
419+
355420
it("never rejects even when everything fails", async () => {
356421
const provider = createTitleProvider({
357422
applySessionTitle: async () => {

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

Lines changed: 84 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export function sanitizeUserMessageForTitle(raw: string): string {
3232
break
3333
}
3434
result += raw.slice(cursor, start)
35+
// Stryker disable next-line ArithmeticOperator: equivalent mutant, </system-reminder> (18 chars) cannot start in the [start-17, start+17] window around <system-reminder> (17 chars)
3536
const end = raw.indexOf(close, start + open.length)
3637
// An unterminated block would otherwise leak the rest of the message as user text; drop it.
3738
if (end === -1) {
@@ -70,8 +71,26 @@ export interface GenerateSessionTitleOptions {
7071
completePrompt?: CompletePromptFn
7172
}
7273

73-
/** One in-flight title generation per session (spec). */
74-
const inFlightTitleTaskIds = new Set<string>()
74+
interface InFlightTitleGeneration {
75+
controller: AbortController
76+
cancelled: boolean
77+
}
78+
79+
/** In-flight title generation controllers by task ID. */
80+
const inFlightTitles = new Map<string, InFlightTitleGeneration>()
81+
82+
/**
83+
* Cancels any pending or in-flight title generation for a task.
84+
* Called when a task is manually renamed, cleared, or deleted so an auto-generated title
85+
* never overwrites the user's manual intent.
86+
*/
87+
export function cancelSessionTitle(taskId: string): void {
88+
const inFlight = inFlightTitles.get(taskId)
89+
if (inFlight) {
90+
inFlight.cancelled = true
91+
inFlight.controller.abort()
92+
}
93+
}
7594

7695
/**
7796
* Generates and applies a session title from the root user message.
@@ -88,29 +107,49 @@ export async function generateSessionTitle(options: GenerateSessionTitleOptions)
88107
return
89108
}
90109

91-
if (inFlightTitleTaskIds.has(taskId)) {
110+
if (inFlightTitles.has(taskId)) {
92111
return
93112
}
94-
inFlightTitleTaskIds.add(taskId)
113+
const inFlight: InFlightTitleGeneration = {
114+
controller: new AbortController(),
115+
cancelled: false,
116+
}
117+
inFlightTitles.set(taskId, inFlight)
95118

96119
try {
97120
let title: string | undefined
98-
try {
99-
title = await completeTitleViaLlm(completePrompt, apiConfiguration, taskId, sanitized)
100-
} catch (error) {
101-
// LLM failure or timeout falls back to the message's first line.
102-
console.error(`[session-title] LLM call failed for task ${taskId}:`, error)
121+
const rateLimitSeconds = apiConfiguration.rateLimitSeconds ?? 0
122+
if (rateLimitSeconds <= 0 && !inFlight.cancelled) {
123+
try {
124+
title = await completeTitleViaLlm(
125+
completePrompt,
126+
apiConfiguration,
127+
taskId,
128+
sanitized,
129+
inFlight.controller,
130+
)
131+
} catch (error) {
132+
// LLM failure, cancellation, or timeout falls back to the message's first line.
133+
if (!inFlight.cancelled) {
134+
console.error(`[session-title] LLM call failed for task ${taskId}:`, error)
135+
}
136+
}
137+
}
138+
if (inFlight.cancelled) {
139+
return
103140
}
104141
title ??= fallbackTitle(sanitized)
105-
if (!title) {
142+
if (!title || inFlight.cancelled) {
106143
return
107144
}
108-
await applyTitleWithRetry(provider, taskId, title)
145+
await applyTitleWithRetry(provider, taskId, title, () => inFlight.cancelled)
109146
} catch (error) {
110147
// Best-effort by design: a failed title must never surface in the chat.
111-
console.error(`[session-title] generation failed for task ${taskId}:`, error)
148+
if (!inFlight.cancelled) {
149+
console.error(`[session-title] generation failed for task ${taskId}:`, error)
150+
}
112151
} finally {
113-
inFlightTitleTaskIds.delete(taskId)
152+
inFlightTitles.delete(taskId)
114153
}
115154
}
116155

@@ -119,8 +158,8 @@ async function completeTitleViaLlm(
119158
apiConfiguration: ProviderSettings,
120159
taskId: string,
121160
sanitized: string,
161+
controller: AbortController,
122162
): Promise<string | undefined> {
123-
const controller = new AbortController()
124163
let timeoutId: ReturnType<typeof setTimeout> | undefined
125164
try {
126165
// Both options are honored only by some providers, so the race below is
@@ -137,26 +176,51 @@ async function completeTitleViaLlm(
137176
reject(new Error(`[session-title] timed out after ${SESSION_TITLE_TIMEOUT_MS}ms`))
138177
}, SESSION_TITLE_TIMEOUT_MS)
139178
})
140-
// Promise.race attaches handlers to both inputs, so the completion
141-
// rejecting after the timeout is already considered handled.
142-
const raw = await Promise.race([completion, timeout])
179+
const abortPromise = new Promise<never>((_, reject) => {
180+
if (controller.signal.aborted) {
181+
reject(new Error("[session-title] aborted"))
182+
} else {
183+
controller.signal.addEventListener(
184+
"abort",
185+
() => {
186+
reject(new Error("[session-title] aborted"))
187+
},
188+
{ once: true },
189+
)
190+
}
191+
})
192+
// Promise.race attaches handlers to all inputs, so rejections after completion are considered handled.
193+
const raw = await Promise.race([completion, timeout, abortPromise])
143194
return extractLlmTitle(raw)
144195
} finally {
145196
clearTimeout(timeoutId)
146197
}
147198
}
148199

149-
async function applyTitleWithRetry(provider: ClineProvider, taskId: string, title: string): Promise<void> {
200+
async function applyTitleWithRetry(
201+
provider: ClineProvider,
202+
taskId: string,
203+
title: string,
204+
isCancelled: () => boolean,
205+
): Promise<void> {
150206
for (let attempt = 0; ; attempt++) {
207+
if (isCancelled()) {
208+
return
209+
}
151210
try {
152211
await provider.applySessionTitle(taskId, title)
153212
// Both outcomes end the attempt: "applied" is done, and "conflict"
154213
// means the user named the session (or another generation applied
155214
// first) — the existing title always wins.
156215
return
157216
} catch (error) {
158-
if (attempt >= TITLE_WRITE_MAX_RETRIES) {
159-
console.error(`[session-title] giving up on task ${taskId} after ${attempt + 1} write attempts:`, error)
217+
if (isCancelled() || attempt >= TITLE_WRITE_MAX_RETRIES) {
218+
if (!isCancelled()) {
219+
console.error(
220+
`[session-title] giving up on task ${taskId} after ${attempt + 1} write attempts:`,
221+
error,
222+
)
223+
}
160224
return
161225
}
162226
}

‎src/core/webview/ClineProvider.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ import {
7676
providerIdentifiers,
7777
} from "@roo-code/types"
7878
import { RateLimitClock, createRateLimitClock } from "../task/RateLimitClock"
79-
import type { SessionTitleApplyResult } from "../task/session-title"
79+
import { cancelSessionTitle, type SessionTitleApplyResult } from "../task/session-title"
8080
import { TaskRegistry } from "../task/TaskRegistry"
8181
import { TaskScheduler } from "../task/TaskScheduler"
8282
import {
@@ -2810,6 +2810,7 @@ export class ClineProvider
28102810
* clears it so the history falls back to the original prompt.
28112811
*/
28122812
async renameTaskWithId(id: string, title: string | undefined) {
2813+
cancelSessionTitle(id)
28132814
if (!this.taskHistoryStore.get(id)) {
28142815
this.log(`[renameTaskWithId] task ${id} not found in history`)
28152816
return
@@ -2826,6 +2827,7 @@ export class ClineProvider
28262827

28272828
if (this.isViewLaunched) {
28282829
const updatedItem = this.taskHistoryStore.get(id)
2830+
// Stryker disable next-line ConditionalExpression: equivalent mutant, setTitleIfUnset guarantees the item is in the cache
28292831
if (updatedItem) {
28302832
await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedItem })
28312833
}
@@ -2855,6 +2857,7 @@ export class ClineProvider
28552857

28562858
if (this.isViewLaunched) {
28572859
const updatedItem = this.taskHistoryStore.get(id)
2860+
// Stryker disable next-line ConditionalExpression: equivalent mutant, setTitleIfUnset guarantees the item is in the cache
28582861
if (updatedItem) {
28592862
await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedItem })
28602863
}
@@ -2876,6 +2879,7 @@ export class ClineProvider
28762879
// this function deletes a task from task history, and deletes its checkpoints and delete the task folder
28772880
// If the task has subtasks (childIds), they will also be deleted recursively
28782881
async deleteTaskWithId(id: string, cascadeSubtasks: boolean = true) {
2882+
cancelSessionTitle(id)
28792883
try {
28802884
await this.getTaskWithId(id)
28812885

‎src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { ContextProxy } from "../../config/ContextProxy"
1111
import { Task } from "../../task/Task"
1212
import { ProfileValidator } from "../../../shared/ProfileValidator"
1313
import { ClineProvider } from "../ClineProvider"
14+
import { generateSessionTitle } from "../../task/session-title"
1415

1516
// Mock setup
1617
vi.mock("p-wait-for", () => ({
@@ -653,6 +654,35 @@ describe("ClineProvider Task History Synchronization", () => {
653654
expect(getStored("task-race")).toMatchObject({ title: "Renamed", tokensIn: 500 })
654655
})
655656

657+
it("cancels in-flight session title generation and preserves a manual title clear", async () => {
658+
await provider.updateTaskHistory(createHistoryItem({ id: "task-manual-clear", task: "Original prompt" }), {
659+
broadcast: false,
660+
})
661+
let resolveCompletion!: (title: string) => void
662+
const completionPromise = new Promise<string>((resolve) => {
663+
resolveCompletion = resolve
664+
})
665+
const generation = generateSessionTitle({
666+
provider,
667+
taskId: "task-manual-clear",
668+
userMessage: "Original prompt",
669+
apiConfiguration: {
670+
apiProvider: providerIdentifiers.anthropic,
671+
apiModelId: "claude-3-5-sonnet-20241022",
672+
apiKey: "test-api-key",
673+
},
674+
completePrompt: async () => completionPromise,
675+
})
676+
677+
await provider.renameTaskWithId("task-manual-clear", "")
678+
expect(getStored("task-manual-clear")?.title).toBeUndefined()
679+
680+
resolveCompletion("Generated Title")
681+
await generation
682+
683+
expect(getStored("task-manual-clear")?.title).toBeUndefined()
684+
})
685+
656686
it("does not write a title through a full-item update", async () => {
657687
await provider.updateTaskHistory(
658688
createHistoryItem({ id: "task-title-owner", task: "Original prompt", title: "Stale title" }),
@@ -761,6 +791,8 @@ describe("ClineProvider Task History Synchronization", () => {
761791
})
762792

763793
it("does not broadcast when the view is not launched", async () => {
794+
await provider.resolveWebviewView(mockWebviewView)
795+
provider.isViewLaunched = false
764796
await provider.updateTaskHistory(createHistoryItem({ id: "task-auto-silent", task: "Original prompt" }), {
765797
broadcast: false,
766798
})

0 commit comments

Comments
 (0)