Preserve independent naming while fencing Claude title reuse

This commit is contained in:
Brennan Benson
2026-11-08 19:50:44 -08:00
parent 76d35db4a2
commit a67405808b
9 changed files with 469 additions and 100 deletions
@@ -1,3 +1,5 @@
import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router'
import * as installedRouter from '../../claude-accounts/claude-profile-installed-router'
import { afterEach, expect, it, vi } from 'vitest'
import { acquired, fakeClaude, PROVIDER_SESSION_ID } from './claude-structured-session-test-support'
import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
@@ -7,7 +9,25 @@ afterEach(() => vi.restoreAllMocks())
it('reads only cached support and rejects a retired acquisition or changed account/context', async () => {
const cliFlag = vi.fn(async () => 'supported' as const)
const cli = fakeClaude()
const adapter = await acquired(cli, { cliFlag })
const router = new ClaudeProfileRouter({
getSettings: () => ({
claudeManagedAccounts: [],
activeClaudeManagedAccountId: null,
agentStatusHooksEnabled: false,
disabledTuiAgents: []
}),
dataRoot: '/isolated',
userHome: '/users/test',
env: {}
})
const preparation = vi.spyOn(router, 'preparation')
vi.spyOn(installedRouter, 'getClaudeProfileRouter').mockReturnValue(router)
const adapter = await acquired(cli, {
cliFlag,
account: 'system',
claudeConfigDir: '/accounts/claude',
accountRecipe: { route: 'system', home: '/accounts/claude', configDir: '/accounts/claude' }
})
try {
const record = agentSessionRecordFixture()
record.sessionId = 'session-1'
@@ -34,6 +54,15 @@ it('reads only cached support and rejects a retired acquisition or changed accou
providerContextBoundary: { operationId: 'clear-1', afterFence: 7, clearedAt: 1 }
})
).toBe(false)
const system = router.preparation()
preparation.mockReturnValue({
...system,
provenance: 'profile:other',
configDir: '/accounts/other'
})
expect(owner.isCurrent(record)).toBe(false)
preparation.mockReturnValue(system)
expect(owner.isCurrent(record)).toBe(true)
await adapter.closeAll()
expect(owner.isCurrent(record)).toBe(false)
} finally {
@@ -62,3 +91,21 @@ it.each(['unknown', 'unsupported'] as const)(
}
}
)
it('retains retirement knowledge when the optional title method is missing', async () => {
const cli = fakeClaude()
const adapter = await acquired(cli)
try {
const record = agentSessionRecordFixture()
record.sessionId = 'session-1'
record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID
const owner = adapter.captureConversationTitleOwner(record)!
expect(owner.isCurrent(record)).toBe(true)
expect(await owner.generate('Repair login', () => owner.isCurrent(record))).toBeNull()
await adapter.closeAll()
expect(owner.isCurrent(record)).toBe(false)
} finally {
await adapter.closeAll()
cli.dispose()
}
})
@@ -1,10 +1,10 @@
import { resolve } from 'node:path'
import { getClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router'
import { agentSessionAccountHomesEqual } from '../../../shared/agent-session/lifecycle/agent-session-account-home'
import { claudeNamingContextId } from '../claude-conversation-naming'
import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS } from '../claude-cli-flag-support'
import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter'
import type { ClaudeSession } from './claude-structured-session-state'
import { resolve } from 'node:path'
export const captureClaudeConversationTitleOwner =
(
@@ -12,21 +12,31 @@ export const captureClaudeConversationTitleOwner =
): NonNullable<StructuredAgentSessionAdapter['captureConversationTitleOwner']> =>
(record) => {
const session = sessions.get(record.sessionId)
if (!session?.initialization.startup.opened() || !session.connection.generateSessionTitle) {
if (!session) {
return null
}
const { connection, acquisitionGeneration, fence, providerSessionId, initialization } = session
const policy = getClaudeProfileRouter()?.preparation()
if (
policy &&
resolve(initialization.cwd, policy.configDir) !== initialization.claudeConfigDir
) {
return null
}
const boundary = record.providerContextBoundary?.operationId
const account = () => {
const policy = getClaudeProfileRouter()?.preparation()
return JSON.stringify([policy?.configDir, policy?.provenance])
const recipe = initialization.accountRecipe
if (policy) {
if ((recipe?.route ?? initialization.account) === 'managed') {
if (
!policy.provenance.startsWith('profile:') ||
(recipe?.route === 'managed' && policy.provenance !== `profile:${recipe.accountId}`) ||
resolve(initialization.cwd, policy.configDir) !== initialization.claudeConfigDir
) {
return null
}
} else if (policy.provenance !== 'system') {
return null
}
}
return JSON.stringify([
policy?.provenance,
policy?.provenance.startsWith('profile:') ? policy.configDir : null
])
}
const selectedAccount = account()
const isCurrent: NonNullable<
@@ -47,13 +57,18 @@ export const captureClaudeConversationTitleOwner =
current.location.workspaceId === record.location.workspaceId &&
current.location.executionHostId === record.location.executionHostId &&
session.initialization === initialization &&
selectedAccount !== null &&
account() === selectedAccount
if (!isCurrent(record)) {
return null
}
return {
isCurrent,
generate: async (firstPrompt, shouldExecute) => {
if (
!session.initialization.startup.opened() ||
!connection.generateSessionTitle ||
!shouldExecute()
) {
return null
}
// Verified support floor, not the request's introduction version; never start a probe here.
const supported = await session.cliFlag?.(
{ option: 'generate_session_title', firstVersion: '2.1.310' },
@@ -2,13 +2,13 @@ import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/ag
import type { StructuredChatNamingDeps } from './structured-chat-naming'
export async function runStructuredChatNameGeneration(input: {
automatic: boolean
automaticTitle?: Parameters<StructuredChatNamingDeps['generate']>[3]
getRecord: () => AgentSessionRecord | null | undefined
applicable: () => boolean
applicable: (current?: AgentSessionRecord) => boolean
generate: (
stillCurrent: () => boolean,
automaticTitle?: Parameters<StructuredChatNamingDeps['generate']>[3]
) => Promise<{ name: string; shouldApply?: () => boolean } | null>
) => Promise<{ name: string; shouldApply?: (record?: AgentSessionRecord) => boolean } | null>
setName: (
name: string,
applicable: (record: AgentSessionRecord) => boolean
@@ -17,15 +17,16 @@ export async function runStructuredChatNameGeneration(input: {
let owner: ((record: AgentSessionRecord) => boolean) | undefined
const stillCurrent = (latest?: AgentSessionRecord) => {
const record = latest ?? input.getRecord()
return input.applicable() && !!record && (owner?.(record) ?? true)
return !!record && input.applicable(record) && (owner?.(record) ?? true)
}
if (!stillCurrent()) {
return
}
const name = await input.generate(
stillCurrent,
input.automatic
input.automaticTitle
? {
...input.automaticTitle,
retainOwnership: (check) => {
owner = check
}
@@ -37,10 +38,10 @@ export async function runStructuredChatNameGeneration(input: {
}
const named = await input.setName(
name.name,
(current) => stillCurrent(current) && (name.shouldApply?.() ?? true)
(current) => stillCurrent(current) && (name.shouldApply?.(current) ?? true)
)
// A queued write can lose its naming settings while retaining its live session owner.
if (!named && name.shouldApply && !name.shouldApply() && stillCurrent()) {
// Independent fallback retains the canonical name/context owner; only timeout retains live ownership.
if (!named && name.shouldApply && stillCurrent()) {
const fallback = await input.generate(stillCurrent)
if (fallback && stillCurrent()) {
await input.setName(fallback.name, stillCurrent)
@@ -9,7 +9,10 @@ import {
setAgentSessionRecordUserName
} from '../runtime/agent-session/records/agent-session-record-conversation-name'
function rig(generate: StructuredChatNamingDeps['generate']) {
function rig(
generate: StructuredChatNamingDeps['generate'],
captureAutomaticTitle: StructuredChatNamingDeps['captureAutomaticTitle'] = () => ({ owner: null })
) {
let record = agentSessionRecordFixture({ sessionId: 'chat-1' })
let beforeWrite: (() => Promise<void>) | undefined
const handler = createStructuredChatNamingHandler({
@@ -40,6 +43,7 @@ function rig(generate: StructuredChatNamingDeps['generate']) {
readJournalFirstPrompt: async () => 'Repair login',
workerTaskTitle: () => null,
generate,
captureAutomaticTitle,
wait: async () => {},
onNamed: () => {},
logger: { warn: vi.fn(), error: vi.fn() }
@@ -92,10 +96,13 @@ it.each(['owner', 'same-text rename'] as const)(
'rejects a queued title write after %s changes',
async (change) => {
let owned = true
const state = rig(async (_record, _prompt, _current, automatic) => {
automatic!.retainOwnership(() => owned)
return { name: 'CLI title' }
})
const state = rig(
async (_record, _prompt, _current, automatic) =>
automatic ? { name: 'CLI title', shouldApply: () => owned } : { name: 'Independent title' },
() => ({
owner: { isCurrent: () => owned, generate: async () => null }
})
)
state.beforeWrite(async () => {
if (change === 'owner') {
owned = false
@@ -105,7 +112,9 @@ it.each(['owner', 'same-text rename'] as const)(
})
state.start()
await state.done()
expect(state.record().conversationName).toBe('Repair login')
expect(state.record().conversationName).toBe(
change === 'owner' ? 'Independent title' : 'Repair login'
)
}
)
@@ -3,10 +3,16 @@ import type { GlobalSettings } from '../../shared/global-settings-types'
import type { AgentSessionRecordStore } from '../runtime/agent-session/records/agent-session-record-store'
import type { AgentGenerationFailureOutput } from '../text-generation/agent-failure-output'
import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger'
import type { StructuredAgentSessionAdapter } from './agent-session-wire/providers/structured-agent-session-adapter'
export type AutomaticChatTitle = {
owner: ReturnType<NonNullable<StructuredAgentSessionAdapter['captureConversationTitleOwner']>>
retainOwnership?: (isCurrent: (record: AgentSessionRecord) => boolean) => void
}
/** null means unavailable/canceled: no failure to display or retry. */
export type StructuredChatNameGeneration =
| { name: string; shouldApply?: () => boolean }
| { name: string; shouldApply?: (record?: AgentSessionRecord) => boolean }
| { error: string; errorCode?: string; failureOutput?: AgentGenerationFailureOutput }
| null
@@ -21,13 +27,12 @@ export type StructuredChatNamingDeps = {
readJournalFirstPrompt: (sessionId: string) => Promise<string>
now?: () => number
workerTaskTitle: (record: AgentSessionRecord) => { title: string } | null
captureAutomaticTitle?: (record: AgentSessionRecord) => AutomaticChatTitle | undefined
generate: (
record: AgentSessionRecord,
firstPrompt: string,
shouldExecute?: () => boolean,
automaticTitle?: {
retainOwnership: (isCurrent: (record: AgentSessionRecord) => boolean) => void
}
automaticTitle?: AutomaticChatTitle
) => Promise<StructuredChatNameGeneration>
onNamed: (workspaceId: string, sessionId: string) => void
logger: StructuredAgentSessionLogger
@@ -1,6 +1,12 @@
import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record'
import type { AutomaticChatTitle } from './structured-chat-naming-types'
export type NamingRequest = { record: AgentSessionRecord; automatic: boolean; firstPrompt?: string }
export type NamingRequest = {
record: AgentSessionRecord
automatic: boolean
firstPrompt?: string
automaticTitle?: AutomaticChatTitle
}
type NamingJob = { desired?: NamingRequest; executing?: NamingRequest; preparing: boolean }
export function createStructuredChatNamingWork(deps: {
@@ -31,7 +37,7 @@ export function createStructuredChatNamingWork(deps: {
}
}
return {
run(record: AgentSessionRecord, automatic: boolean) {
run(record: AgentSessionRecord, automatic: boolean, automaticTitle?: AutomaticChatTitle) {
const { sessionId } = record
const job: NamingJob = jobs.get(sessionId) ?? { preparing: false }
const pending = job.desired ?? job.executing
@@ -44,7 +50,7 @@ export function createStructuredChatNamingWork(deps: {
) {
return
}
job.desired = { record, automatic }
job.desired = { record, automatic, automaticTitle }
jobs.set(sessionId, job)
if (!job.preparing) {
job.preparing = true
+15 -18
View File
@@ -66,11 +66,13 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps
const record = deps.getStore()?.getRecord(sessionId)
return !!record && contextId(record) === context
}
const applicable = (request: NamingRequest) => {
const store = deps.getStore()
const applicable = (request: NamingRequest, latest?: AgentSessionRecord) => {
const current = latest ?? deps.getStore()?.getRecord(request.record.sessionId)
return (
!!store &&
generationStillCurrent(store, request.record) &&
!!current &&
current.conversationNameSource !== 'user' &&
current.conversationName === request.record.conversationName &&
contextId(current) === contextId(request.record) &&
(!request.automatic || deps.getSettings().nativeChatAutoName !== false)
)
}
@@ -79,9 +81,9 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps
prepare,
execute: (request, firstPrompt) =>
runStructuredChatNameGeneration({
automatic: request.automatic,
automaticTitle: request.automaticTitle,
getRecord: () => deps.getStore()?.getRecord(request.record.sessionId),
applicable: () => applicable(request),
applicable: (current) => applicable(request, current),
generate: (stillCurrent, automaticTitle) =>
generateName(
request.record,
@@ -135,7 +137,7 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps
retryDelays: readonly number[],
stillCurrent: () => boolean,
automaticTitle?: Parameters<StructuredChatNamingDeps['generate']>[3]
): Promise<{ name: string; shouldApply?: () => boolean } | null> {
): Promise<{ name: string; shouldApply?: (record?: AgentSessionRecord) => boolean } | null> {
attempted.set(record.sessionId, contextId(record))
for (let attempt = 0; stillCurrent(); attempt += 1) {
let failure: NamingRunFailure
@@ -195,16 +197,6 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps
return named
}
const generationStillCurrent = (store: NamingStore, record: AgentSessionRecord) => {
const current = store.getRecord(record.sessionId)
return (
current !== null &&
current.conversationNameSource !== 'user' &&
current.conversationName === record.conversationName &&
contextId(current) === contextId(record)
)
}
async function prepare(request: NamingRequest): Promise<NamingRequest | null> {
const store = deps.getStore()
if (!store || !applicable(request)) {
@@ -267,7 +259,12 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps
return
}
attempted.set(summary.sessionId, contextId(record))
work.run(record, true)
const automaticTitle =
record.conversationName === undefined &&
!(!record.providerContextBoundary && deps.workerTaskTitle(record))
? deps.captureAutomaticTitle?.(record)
: undefined
work.run(record, true, automaticTitle)
} catch (error) {
warn(summary.sessionId, error)
}
@@ -1,3 +1,18 @@
import {
acquired,
fakeClaude,
identityFor,
recordingJournalSink,
PROVIDER_SESSION_ID
} from '../../../claude/structured/claude-structured-session-test-support'
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
import type { Query } from '@anthropic-ai/claude-agent-sdk'
import { createClaudeControlSurface } from '../../../claude/claude-agent-sdk-control-requests'
import {
createStructuredChatNamingHandler,
type StructuredChatNamingDeps
} from '../../../native-chat/structured-chat-naming'
import { compareAndSetAgentSessionRecordName } from '../records/agent-session-record-conversation-name'
import { rm } from 'node:fs/promises'
import { installClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -15,7 +30,11 @@ const mocks = vi.hoisted(() => ({
})),
native: vi.fn(async () => 'Native title'),
titleOwner: vi.fn(),
generate: vi.fn(async () => ({ success: true as const, name: 'Login repair' })),
record: vi.fn(),
generate: vi.fn<typeof TextGeneration.generateConversationNameFromContext>(async () => ({
success: true as const,
name: 'Login repair'
})),
target: vi.fn(async (cwd: string) => ({ kind: 'local' as const, cwd })),
publishConversationName: vi.fn<(sessionId: string) => void>(),
journalCurrentRead: vi.fn<(sessionId: string) => Promise<AgentJournalSnapshot>>()
@@ -31,6 +50,7 @@ vi.mock('../../../agent-hooks/first-work/first-work-generation-target', () => ({
vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({
getStructuredAgentSessionHost: () => ({
deps: {
store: { getRecord: mocks.record },
adapter: { generateText: mocks.native, captureConversationTitleOwner: mocks.titleOwner }
},
publishConversationName: mocks.publishConversationName,
@@ -46,12 +66,14 @@ vi.mock('../../../managed-data-accounts/service', () => ({
}))
const roots: string[] = []
afterEach(async () => {
vi.useRealTimers()
installClaudeProfileRouter(undefined)
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
beforeEach(() => {
vi.clearAllMocks()
mocks.titleOwner.mockReset()
mocks.record.mockReset()
})
function rig() {
@@ -85,9 +107,13 @@ describe('structured chat naming runtime', () => {
const record = agentSessionRecordFixture()
const pending = Promise.withResolvers<string>()
const generate = vi.fn(() => pending.promise)
const retainOwnership = vi.fn()
mocks.titleOwner.mockReturnValue({ isCurrent: () => true, generate })
const result = state.deps.generate(record, 'Repair login', () => true, { retainOwnership })
const result = state.deps.generate(
record,
'Repair login',
() => true,
state.deps.captureAutomaticTitle!(record)
)
await vi.waitFor(() => expect(generate).toHaveBeenCalled())
pending.resolve('Broken chat title')
expect(await result).toMatchObject({ name: 'Broken chat title' })
@@ -102,11 +128,16 @@ describe('structured chat naming runtime', () => {
return 'Wrong settings title'
})
expect(
await state.deps.generate(record, 'Repair login', () => true, { retainOwnership })
await state.deps.generate(
record,
'Repair login',
() => true,
state.deps.captureAutomaticTitle!(record)
)
).toEqual({ name: 'Login repair' })
})
it.each(['action', 'shared', 'legacy', 'effort', 'template'] as const)(
it.each(['action', 'shared', 'legacy', 'seeded-default', 'effort', 'template'] as const)(
'preserves authored %s naming choices without consulting the CLI',
async (choice) => {
const state = rig()
@@ -122,16 +153,24 @@ describe('structured chat naming runtime', () => {
if (choice === 'legacy') {
state.settings.commitMessageAi!.selectedModelByAgent = { claude: 'opus' }
}
if (choice === 'seeded-default') {
state.settings.commitMessageAi!.selectedModelByAgent = { claude: 'sonnet' }
state.settings.commitMessageAi!.selectedThinkingByModel = { sonnet: 'high' }
}
if (choice === 'effort') {
source.selectedThinkingByModel = { sonnet: 'high' }
}
if (choice === 'template') {
source.actions!.conversationName = { commandInputTemplate: 'Custom {basePrompt}' }
}
const record = agentSessionRecordFixture()
expect(
await state.deps.generate(agentSessionRecordFixture(), 'Repair login', () => true, {
retainOwnership: () => {}
})
await state.deps.generate(
record,
'Repair login',
() => true,
state.deps.captureAutomaticTitle!(record)
)
).toEqual({ name: 'Login repair' })
expect(mocks.titleOwner).not.toHaveBeenCalled()
}
@@ -156,3 +195,224 @@ describe('structured chat naming runtime', () => {
}
)
})
function automaticNaming(state: ReturnType<typeof rig>, before?: 'prompt' | 'seed') {
let record = agentSessionRecordFixture()
record.sessionId = 'session-1'
record.lease.sessionId = 'session-1'
record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID
const blocked = Promise.withResolvers<void>()
const entered = Promise.withResolvers<void>()
const pause = async (stage: 'prompt' | 'seed') => {
if (before === stage) {
entered.resolve()
await blocked.promise
}
}
const store = {
getRecord: () => record,
compareAndSetConversationName: async (_id, name, expected, context, applicable) =>
compareAndSetAgentSessionRecordName(
async (apply) => {
if (expected === null) {
await pause('seed')
}
record = apply(record)
return record
},
name,
expected,
context,
applicable
),
setUserConversationName: vi.fn()
} satisfies NonNullable<ReturnType<StructuredChatNamingDeps['getStore']>>
mocks.record.mockImplementation(() => record)
const handler = createStructuredChatNamingHandler({
...state.deps,
getStore: () => store,
readFirstPrompt: async () => {
await pause('prompt')
return 'Repair login'
},
wait: async () => {}
})
return {
handler,
entered: entered.promise,
release: () => blocked.resolve(),
record: () => record,
replace: () => {
record = { ...record, lease: { ...record.lease, runtimeFence: 8 } }
},
start: () =>
handler(
{
sessionId: record.sessionId,
workspaceId: 'workspace-1',
agent: 'claude',
status: 'working',
latestPrompt: 'Repair login',
updatedAt: 1
},
{ replay: false, firstInputSubmissionKey: 'input-1' }
)
}
}
it.each(['prompt', 'seed', 'workspace', 'support'] as const)(
'retains the accepted input owner while %s preparation is pending',
async (stage) => {
const state = rig()
const blocked = Promise.withResolvers<void>()
const entered = Promise.withResolvers<void>()
if (stage === 'workspace') {
state.runtime.resolveWorkspace.mockImplementationOnce(async () => {
entered.resolve()
await blocked.promise
return { path: '/workspace/folder', executionHostId: 'local' }
})
}
const naming = automaticNaming(
state,
stage === 'prompt' || stage === 'seed' ? stage : undefined
)
const control = vi.fn(async () => 'Successor title')
mocks.titleOwner.mockImplementation(() => {
const fence = naming.record().lease.runtimeFence
return {
isCurrent: (current: AgentSessionRecord) => current.lease.runtimeFence === fence,
generate: async (_prompt: string, shouldExecute: () => boolean) => {
if (stage === 'support') {
entered.resolve()
await blocked.promise
}
return shouldExecute() ? control() : null
}
}
})
naming.start()
await (stage === 'workspace' || stage === 'support' ? entered.promise : naming.entered)
naming.replace()
naming.release()
blocked.resolve()
await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([]))
expect(control).not.toHaveBeenCalled()
expect(mocks.generate).toHaveBeenCalledOnce()
expect(naming.record().conversationName).toBe('Login repair')
}
)
it.each([false, true])(
'bounds timeout fallback to its owner (retired=%s), retries independently, and ignores late CLI results',
async (retired) => {
const state = rig()
const pending = Promise.withResolvers<string>()
const generateSessionTitle = vi.fn(() => pending.promise)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this flow calls only the feature-detected title method.
const controls = createClaudeControlSurface({ generateSessionTitle } as unknown as Query)
let owned = true
mocks.titleOwner.mockReturnValue({
isCurrent: () => owned,
generate: controls.generateSessionTitle
})
mocks.generate
.mockResolvedValueOnce({ success: false, error: 'Retry naming' })
.mockImplementationOnce(async () => {
if (retired) {
owned = false
}
return { success: true, name: 'Recovered name' }
})
const naming = automaticNaming(state)
vi.useFakeTimers()
naming.start()
await vi.advanceTimersByTimeAsync(30_000)
expect(naming.record().conversationName).toBe(retired ? 'Repair login' : 'Recovered name')
pending.resolve('Late CLI name')
await vi.advanceTimersByTimeAsync(0)
expect(naming.record().conversationName).toBe(retired ? 'Repair login' : 'Recovered name')
expect(generateSessionTitle).toHaveBeenCalledOnce()
expect(mocks.generate).toHaveBeenCalledTimes(2)
expect(naming.handler.activeSessionIds()).toEqual([])
}
)
it.each([
{ support: 'unsupported' as const, transition: 'close', response: 'unused' },
{ support: 'unknown' as const, transition: 'replacement', response: 'unused' },
{ support: 'supported' as const, transition: 'replacement', response: 'error' },
{ support: 'supported' as const, transition: 'close', response: 'null' }
])(
'finishes independent naming after $transition with support=$support and response=$response',
async ({ support, transition, response }) => {
const cli = fakeClaude()
const adapter = await acquired(cli, { cliFlag: async () => support })
const state = rig()
const naming = automaticNaming(state)
const entered = Promise.withResolvers<void>()
const independent =
Promise.withResolvers<
Awaited<ReturnType<typeof TextGeneration.generateConversationNameFromContext>>
>()
const control = vi.fn(async () => {
if (response === 'error') {
throw new Error('Optional control rejected')
}
return response === 'null' ? null : 'Wrong live title'
})
cli.connections[0]!.generateSessionTitle = control
mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record))
mocks.generate.mockImplementationOnce(async () => {
entered.resolve()
return independent.promise
})
try {
naming.start()
await entered.promise
await adapter.closeSession('session-1')
if (transition === 'replacement') {
naming.replace()
await adapter.acquire({
identity: identityFor(),
fence: 8,
spawnToken: 'replacement',
events: recordingJournalSink()
})
cli.connections[1]!.generateSessionTitle = control
}
independent.resolve({ success: true, name: 'Independent completion' })
await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([]))
expect(naming.record().conversationName).toBe('Independent completion')
expect(control).toHaveBeenCalledTimes(response === 'unused' ? 0 : 1)
} finally {
await adapter.closeAll()
cli.dispose()
}
}
)
it('discards a retired CLI result and publishes only independent fallback text', async () => {
const cli = fakeClaude()
const adapter = await acquired(cli)
const state = rig()
const naming = automaticNaming(state)
const pending = Promise.withResolvers<string>()
const started = Promise.withResolvers<void>()
cli.connections[0]!.generateSessionTitle = async () => {
started.resolve()
return pending.promise
}
mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record))
try {
naming.start()
await started.promise
await adapter.closeSession('session-1')
pending.resolve('Stale CLI title')
await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([]))
expect(naming.record().conversationName).toBe('Login repair')
} finally {
await adapter.closeAll()
cli.dispose()
}
})
@@ -1,3 +1,4 @@
import { ClaudeControlRequestTimeoutError } from '../../../claude/claude-agent-sdk-control-requests'
import { normalizeSourceControlAiSettings } from '../../../../shared/source-control/ai/settings/source-control-ai-settings'
import {
resolveSourceControlActionRecipe,
@@ -64,6 +65,35 @@ function canReuseClaudeTitle(
)
}
function resolveChatNamingParams(
current: Parameters<typeof resolveTextGenerationParams>[0],
provider: Parameters<StructuredChatNamingDeps['generate']>[0]['provider'],
recipe = resolveSourceControlActionRecipe({ settings: current, actionId: 'conversationName' })
) {
const source = normalizeSourceControlAiSettings(current.sourceControlAi, current.commitMessageAi)
const useChatAgent = !recipe.agentId && !recipe.agentArgs?.trim()
return resolveTextGenerationParams(
useChatAgent
? {
...current,
sourceControlAi: {
...source,
actions: {
...source.actions,
conversationName: normalizeSourceControlActionRecipe({
...recipe,
agentId: provider
})
}
}
}
: current,
LOCAL_COMMIT_MESSAGE_HOST_KEY,
'conversationName',
null
)
}
export function structuredChatNamingDeps(
getStore: () => {
getSettings: () => Parameters<typeof resolveTextGenerationParams>[0] &
@@ -91,6 +121,25 @@ export function structuredChatNamingDeps(
: ''
},
workerTaskTitle: runtime.workerTaskTitle,
captureAutomaticTitle: (record) => {
const current = getStore().getSettings()
if (
record.provider !== 'claude' ||
record.location.wslDistro !== null ||
current.nativeChatAutoName === false
) {
return undefined
}
const settings = resolveChatNamingParams(current, record.provider)
if (!settings.ok || !canReuseClaudeTitle(current, settings.params.model)) {
return undefined
}
return {
owner:
getStructuredAgentSessionHost()?.deps.adapter.captureConversationTitleOwner?.(record) ??
null
}
},
generate: async function generate(record, firstPrompt, shouldExecute, automaticTitle) {
// Unsupported execution contexts keep the seed regardless of native naming settings.
if (record.location.wslDistro !== null) {
@@ -101,10 +150,6 @@ export function structuredChatNamingDeps(
return null
}
const current = getStore().getSettings()
const source = normalizeSourceControlAiSettings(
current.sourceControlAi,
current.commitMessageAi
)
const recipe = resolveSourceControlActionRecipe({
settings: current,
actionId: 'conversationName'
@@ -139,26 +184,7 @@ export function structuredChatNamingDeps(
return chatNamingFailure(record.provider === 'grok' ? 'grokFailed' : 'antigravityFailed')
}
}
const settings = resolveTextGenerationParams(
useChatAgent
? {
...current,
sourceControlAi: {
...source,
actions: {
...source.actions,
conversationName: normalizeSourceControlActionRecipe({
...recipe,
agentId: record.provider
})
}
}
}
: current,
LOCAL_COMMIT_MESSAGE_HOST_KEY,
'conversationName',
null
)
const settings = resolveChatNamingParams(current, record.provider, recipe)
if (!settings.ok) {
logger.warn(settings.error, log)
return { error: settings.error }
@@ -169,29 +195,32 @@ export function structuredChatNamingDeps(
current.nativeChatAutoName !== false &&
canReuseClaudeTitle(current, settings.params.model)
) {
const owner =
getStructuredAgentSessionHost()?.deps.adapter.captureConversationTitleOwner?.(record)
const owner = automaticTitle.owner
if (owner) {
automaticTitle.retainOwnership(owner.isCurrent)
const isCurrent = () => shouldExecute?.() ?? true
const isCurrent = (
current = getStructuredAgentSessionHost()?.deps.store?.getRecord(record.sessionId) ??
record
) => (shouldExecute?.() ?? true) && owner.isCurrent(current)
const eligible = () =>
getStore().getSettings().nativeChatAutoName !== false &&
canReuseClaudeTitle(getStore().getSettings(), settings.params.model)
if (!isCurrent()) {
return null
}
let output: unknown
try {
output = await owner.generate(firstPrompt, () => isCurrent() && eligible())
} catch {
// Optional CLI control failure keeps the existing generator's recovery path.
}
if (!isCurrent()) {
return null
if (isCurrent()) {
output = await owner.generate(firstPrompt, () => isCurrent() && eligible())
}
} catch (error) {
if (error instanceof ClaudeControlRequestTimeoutError) {
// A timed-out control is still in flight; its fallback keeps the original live owner.
automaticTitle.retainOwnership?.(owner.isCurrent)
if (!isCurrent()) {
return null
}
}
}
const name = typeof output === 'string' ? sanitizeGeneratedConversationName(output) : ''
if (name && eligible()) {
return { name, shouldApply: eligible }
if (name && isCurrent() && eligible()) {
return { name, shouldApply: (current) => isCurrent(current) && eligible() }
}
return generate(record, firstPrompt, shouldExecute, undefined)
}