Skip to content
8 changes: 8 additions & 0 deletions docs/design/web-shell/assistant-response-session-branching.md
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,14 @@ target `<newSessionId>.jsonl` must therefore be the last resource published.
Before creating target resources, compute and sanitize the final title. The
Core fork input includes that title, and Core appends its `custom_title` record
inside the staged transcript. There is no post-publication rename transaction.
Use the source session's picker display name (`customTitle || prompt`) as the
base, remove an existing generated fork suffix, and append the lowest available
numeric suffix: `Title(1)`, `Title(2)`, and so on. Explicitly requested names
remain unchanged before suffix allocation. If a custom title normalizes to
nothing (it was exactly a suffix token), no picker name survives: the daemon
route falls back to a session-id prefix while CLI `/branch` falls back to the
first prompt. The divergence is deliberate; both clients allocate the numeric
suffix from their chosen base.

### 14.2 Temporary resources

Expand Down
187 changes: 173 additions & 14 deletions packages/cli/src/acp-integration/acpAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -638,8 +638,12 @@ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => ({
readonly rpcCode = -32023;
readonly errorKind = 'session_writer_unavailable';
},
computeUniqueBranchTitle: vi.fn(
async (baseName: string) => `${baseName} (Branch)`,
computeUniqueBranchTitle: vi.fn(async (baseName: string) => `${baseName}(1)`),
// The real helper: the route tests below must exercise the shipped
// normalization, not a copy that can silently drift from it.
normalizeDerivedBranchTitle: vi.fn(
(await importOriginal<typeof import('@qwen-code/qwen-code-core')>())
.normalizeDerivedBranchTitle,
),
Storage: {
getGlobalQwenDir: vi.fn(() => '/tmp/qwen-global-test'),
Expand Down Expand Up @@ -16259,6 +16263,7 @@ describe('QwenAgent extMethod renameSession routing', () => {
{
cwd: '/workspace-other',
sessionId: liveSessionId,
name: '创建 MR 描述生成 Skill',
},
);

Expand All @@ -16271,35 +16276,111 @@ describe('QwenAgent extMethod renameSession routing', () => {
expect(sessionService.forkSession).toHaveBeenCalledWith(
liveSessionId,
expect.any(String),
{ title: 'Source session (Branch)' },
{ title: '创建 MR 描述生成 Skill(1)' },
);
expect(sessionService.renameSession).not.toHaveBeenCalled();
expect(result).toMatchObject({
title: 'Source session (Branch)',
displayName: 'Source session (Branch)',
title: '创建 MR 描述生成 Skill(1)',
displayName: '创建 MR 描述生成 Skill(1)',
});

mockConnectionState.resolve();
await agentPromise;
});

it.each([
{
sourceTitle: 'Source session(2)',
name: undefined,
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: 'Source session(1)',
},
{
sourceTitle: 'Source session(2)',
name: 'Source session(2)',
atRecordId: 'checkpoint-1',
persistedDisplayName: undefined,
expectedTitle: 'Source session(2)(1)',
},
{
sourceTitle: 'Recorder title',
name: 'Picker title(2)',
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: 'Picker title(2)(1)',
},
{
sourceTitle: 'Recorder title',
name: 'Roadmap (2026)',
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: 'Roadmap (2026)(1)',
},
{
sourceTitle: 'Source session (Branch)',
name: undefined,
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: 'Source session(1)',
},
{
sourceTitle: 'Source session (Branch 2)',
expectedTitle: 'Source session (Branch)',
name: undefined,
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: 'Source session(1)',
},
{
sourceTitle: '(Branch)',
name: undefined,
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: '550e8400(1)',
},
{
sourceTitle: '(Branch 2)',
name: undefined,
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: '550e8400(1)',
},
{
sourceTitle: undefined,
expectedTitle: '550e8400 (Branch)',
name: undefined,
atRecordId: undefined,
persistedDisplayName: 'Prompt session',
expectedTitle: 'Prompt session(1)',
},
{
sourceTitle: undefined,
name: 'Sprint (2)',
atRecordId: 'checkpoint-2',
persistedDisplayName: 'Sprint (2)',
expectedTitle: 'Sprint (2)(1)',
},
{
sourceTitle: undefined,
name: undefined,
atRecordId: undefined,
persistedDisplayName: undefined,
expectedTitle: '550e8400(1)',
},
])(
'derives the branch title from $sourceTitle',
async ({ sourceTitle, expectedTitle }) => {
async ({
sourceTitle,
name,
atRecordId,
persistedDisplayName,
expectedTitle,
}) => {
const recording = makeRecordingService();
recording.getCurrentCustomTitle.mockReturnValue(sourceTitle);
const sessionService = {
forkSession: vi.fn().mockResolvedValue(undefined),
findSessionTitlesByPrefix: vi.fn().mockResolvedValue([]),
getSessionDisplayName: vi.fn().mockResolvedValue(persistedDisplayName),
renameSession: vi.fn().mockResolvedValue(true),
removeSession: vi.fn().mockResolvedValue(undefined),
};
Expand All @@ -16315,18 +16396,26 @@ describe('QwenAgent extMethod renameSession routing', () => {
{
cwd: '/tmp',
sessionId: liveSessionId,
...(name !== undefined ? { name } : {}),
...(atRecordId !== undefined ? { atRecordId } : {}),
},
);

expect(sessionService.forkSession).toHaveBeenCalledWith(
liveSessionId,
expect.any(String),
{ title: expectedTitle },
{
title: expectedTitle,
...(atRecordId !== undefined ? { atRecordId } : {}),
},
);
expect(result).toMatchObject({
title: expectedTitle,
displayName: expectedTitle,
});
expect(sessionService.getSessionDisplayName).toHaveBeenCalledTimes(
sourceTitle === undefined && name === undefined ? 1 : 0,
);

mockConnectionState.resolve();
await agentPromise;
Expand All @@ -16352,7 +16441,7 @@ describe('QwenAgent extMethod renameSession routing', () => {
{
cwd: '/tmp',
sessionId: liveSessionId,
name: 'Side task',
name: 'Side task(2)',
},
);

Expand All @@ -16364,15 +16453,85 @@ describe('QwenAgent extMethod renameSession routing', () => {
sourceType: 'side_task',
sourceId: liveSessionId,
},
title: 'Side task',
title: 'Side task(2)',
},
);
expect(recording.runWithWriteBarrier).toHaveBeenCalledOnce();
expect(sessionService.renameSession).not.toHaveBeenCalled();
expect(sessionService.removeSession).not.toHaveBeenCalled();
expect(result).toMatchObject({
title: 'Side task',
displayName: 'Side task',
title: 'Side task(2)',
displayName: 'Side task(2)',
});

mockConnectionState.resolve();
await agentPromise;
});

it('falls back to the session id for an empty normalized side-task title', async () => {
const recording = makeRecordingService();
recording.getCurrentCustomTitle.mockReturnValue('(Branch)');
const sessionService = {
forkSession: vi.fn().mockResolvedValue(undefined),
};
const innerConfig = makeLiveSessionInnerConfig(recording);
innerConfig.getSessionService.mockReturnValue(
sessionService as unknown as SessionService,
);
const { agent, agentPromise } = await bootAgent(innerConfig);

await agent.newSession({ cwd: '/tmp', mcpServers: [] });
const result = await agent.extMethod(
SERVE_CONTROL_EXT_METHODS.sessionSideTask,
{
cwd: '/tmp',
sessionId: liveSessionId,
},
);

expect(sessionService.forkSession).toHaveBeenCalledWith(
liveSessionId,
expect.any(String),
expect.objectContaining({ title: '550e8400' }),
);
expect(result).toMatchObject({
title: '550e8400',
displayName: '550e8400',
});

mockConnectionState.resolve();
await agentPromise;
});

it('normalizes the source custom title for a nameless side task', async () => {
const recording = makeRecordingService();
recording.getCurrentCustomTitle.mockReturnValue('My Project(2)');
const sessionService = {
forkSession: vi.fn().mockResolvedValue(undefined),
};
const innerConfig = makeLiveSessionInnerConfig(recording);
innerConfig.getSessionService.mockReturnValue(
sessionService as unknown as SessionService,
);
const { agent, agentPromise } = await bootAgent(innerConfig);

await agent.newSession({ cwd: '/tmp', mcpServers: [] });
const result = await agent.extMethod(
SERVE_CONTROL_EXT_METHODS.sessionSideTask,
{
cwd: '/tmp',
sessionId: liveSessionId,
},
);

expect(sessionService.forkSession).toHaveBeenCalledWith(
liveSessionId,
expect.any(String),
expect.objectContaining({ title: 'My Project' }),
);
expect(result).toMatchObject({
title: 'My Project',
displayName: 'My Project',
});

mockConnectionState.resolve();
Expand Down Expand Up @@ -16437,7 +16596,7 @@ describe('QwenAgent extMethod renameSession routing', () => {
expect(sessionService.forkSession).toHaveBeenCalledWith(
liveSessionId,
expect.any(String),
{ title: 'Source session (Branch)', atRecordId: checkpoint },
{ title: 'Source session(1)', atRecordId: checkpoint },
);
expect(liveBeginHistoryMutation).toHaveBeenCalledOnce();
expect(liveReleaseHistoryMutation).toHaveBeenCalledOnce();
Expand Down
56 changes: 37 additions & 19 deletions packages/cli/src/acp-integration/acpAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import {
subagentGenerator,
redactUrlCredentials,
computeUniqueBranchTitle,
normalizeDerivedBranchTitle,
BranchPointInvalidError,
parseGoalSnapshotV2,
parseGoalStateCause,
Expand Down Expand Up @@ -1141,19 +1142,10 @@ function getLoadReplayPageSize(params: LoadSessionRequest): number | undefined {
return value as number;
}

function deriveForkBaseName(
name: unknown,
recording: { getCurrentCustomTitle(): string | undefined } | undefined,
sessionId: string,
): string {
if (typeof name === 'string' && name.trim().length > 0) {
return name.trim();
}
const existingTitle = recording?.getCurrentCustomTitle();
const stripped = existingTitle
?.replace(/\s*\(Branch(?:\s+\d+)?\)\s*$/, '')
.trim();
return stripped && stripped.length > 0 ? stripped : sessionId.slice(0, 8);
function normalizeRequestedBranchName(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined;
const normalized = value.trim();
return normalized || undefined;
}
function createHiddenWorkspaceMemoryConfig(config: Config): Config {
return new Proxy(config, {
Expand Down Expand Up @@ -11078,11 +11070,29 @@ class QwenAgent implements Agent {
const recording = sourceConfig.getChatRecordingService();
const sessionService = sourceConfig.getSessionService();

const baseName = deriveForkBaseName(
name,
recording,
sessionId,
);
const requestedName = normalizeRequestedBranchName(name);
const sourceCustomTitle =
requestedName === undefined
? recording?.getCurrentCustomTitle()
: undefined;
const persistedDisplayName =
requestedName === undefined &&
sourceCustomTitle === undefined
? await sessionService.getSessionDisplayName(sessionId)
: undefined;
const sourceDisplayName =
sourceCustomTitle ?? persistedDisplayName;
const derivedBaseName = sourceCustomTitle
? normalizeDerivedBranchTitle(sourceCustomTitle)
: sourceDisplayName;
// A title that normalizes to empty (it was exactly a suffix
// token) falls back to the session-id prefix here, while
// CLI /branch falls back to the first prompt. Deliberate:
// no picker name survives to anchor the family to, and one
// shared fallback would need a prompt-only display-name
// read on this route.
const baseName =
requestedName ?? derivedBaseName ?? sessionId.slice(0, 8);

const title = await computeUniqueBranchTitle(
baseName,
Expand Down Expand Up @@ -11120,7 +11130,15 @@ class QwenAgent implements Agent {
const recording = sourceConfig.getChatRecordingService();
if (recording) await recording.flush();
const sessionService = sourceConfig.getSessionService();
const title = deriveForkBaseName(name, recording, sessionId);
const requestedName = normalizeRequestedBranchName(name);
let title = requestedName;
if (title === undefined) {
const sourceCustomTitle = recording?.getCurrentCustomTitle();
title = sourceCustomTitle
? (normalizeDerivedBranchTitle(sourceCustomTitle) ??
sessionId.slice(0, 8))
: sessionId.slice(0, 8);
Comment on lines +11138 to +11142

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for raising this. I kept the side-task persisted-display fallback intentionally unchanged in 8aac1c3abf: side tasks retain their pre-existing explicit name -> live recorder title -> UUID semantics and separate session_source: side_task identity, while ordinary branch naming follows picker semantics. Both paths still share the Core derived-title normalizer, including the empty-result fix. A configurable helper spanning the two different fallback policies would add abstraction without changing the requested behavior.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decline upheld in this round's triage. The two derivations stay separate by design: side tasks keep explicit name → normalized recorder title → session-id prefix and their own side_task identity, while ordinary branches follow picker display-name semantics. Both paths already share the Core derived-title normalizer (including the empty-result fallback fixed in 8aac1c3), so the recognition grammar cannot fragment again; a helper spanning two different fallback policies would add abstraction without changing behavior. Leaving this thread open with the recorded reason.

中文说明

本轮分诊维持拒绝(Decline)。两份推导有意保持分离:side task 保留 显式名称 → 归一化后的记录器标题 → session-id 前缀 链及其独立的 side_task 身份,普通分支则遵循选择器展示名语义。两条路径已共享 Core 的派生标题归一化函数(含 8aac1c3 修复的空结果回退),识别语法不会再次割裂;一个横跨两种不同回退策略的辅助函数只会增加抽象而不改变行为。线程保持打开并附已记录的理由。

}
Comment on lines +11137 to +11143

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8aac1c3abf. The shared normalizer now returns undefined for an empty result, and the side-task path falls back to sessionId.slice(0, 8) before calling forkSession. Added a regression proving (Branch) produces non-empty title/displayName 550e8400 and never persists an empty custom title.

const newSessionId = randomUUID();
const fork = () =>
sessionService.forkSession(sessionId, newSessionId, {
Expand Down
Loading
Loading