Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(session-title): 发送后即时显示标题,清掉界面上的 New Maker 残留 (#1031)

Dash698a81ff31f9
diff --git a/apps/desktop/help-knowledge/collaboration.md b/apps/desktop/help-knowledge/collaboration.md
index cd843badce..efc1962b07 100644
--- a/apps/desktop/help-knowledge/collaboration.md
+++ b/apps/desktop/help-knowledge/collaboration.md
@@ -19,7 +19,7 @@ Collaboration ("协同" / Collab) lets one session — the **lead** — bring in
**While collaborating:**
- Each worker is a full session with its own history, tools, working directory, and model, and runs with permissions bypassed so it doesn't stop to ask. It inherits the lead's working directory by default (or shares the worktree when the lead uses one).
-- A worker's model defaults to your last "New Maker" choice for that vendor, falling back to the lead's model.
+- A worker's model defaults to your last "New Chat" choice for that vendor, falling back to the lead's model.
- Only one worker is **focused** (shown) at a time — switch between them with the worker tabs / dropdown. You can intervene in any worker directly, and archive workers individually.
**Turning it off:**
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index cef40c085c..a862e060b4 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -1257,10 +1257,39 @@ describe('AgentIslandService native publishing', () => {
'/goal 测试一下是不是支持目标模式',
);
await vi.waitFor(() => expect(mocks.getSessionRowSnapshot).toHaveBeenCalledTimes(1));
+ // cache-miss 加载路径同样要过显示投影:发给 native 的是本地化兜底文案,而不是
+ // DB 里那个 locale-independent 的英文哨兵(PR #1031 review P1)。此前只有读路径
+ // hydrateMeta 做了投影,这条断言正好固化了漏掉的那一半。
await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
- title: 'New Maker',
+ title: 'Untitled session',
projectName: null,
}));
+ // 另一条写路径(metadata patch)同样过投影;权威标题到达后照常原样发布 ——
+ // 投影只作用于哨兵,不会把真实标题也顶掉。
+ service.handleSessionMetadataPatch('s1', { title: '登录失败排查' });
+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
+ title: '登录失败排查',
+ }));
+ service.handleSessionMetadataPatch('s1', { title: 'New Maker' });
+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
+ title: 'Untitled session',
+ }));
+ // 切换应用语言后必须**立刻**换语言:投影发生在构建 payload 那一刻,而 state / cache
+ // 存的是原始哨兵,所以 refreshLocalization() 的这次 republish 自然带新语言。若把投影
+ // 固化进 state,这里会一直停在上一语言,直到下一次 metadata 事件(PR #1031 review P1)。
+ {
+ const { setMainLocale } = await import('../../i18n.js');
+ setMainLocale('zh-CN');
+ service.refreshLocalization();
+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
+ title: '未命名对话',
+ }));
+ setMainLocale('en');
+ service.refreshLocalization();
+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
+ title: 'Untitled session',
+ }));
+ }
expect(publish.mock.calls.at(-1)?.[0].strings).toMatchObject({
appName: BRAND_NAME,
newMessage: 'New message',
diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
index 94314fe1ab..2eaf3062f5 100644
--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
@@ -641,6 +641,32 @@ describe('Agent Island display state', () => {
expect(display.pillSnapshot.priorityCompactTitle).not.toBe('codex');
});
+ it('哨兵标题不进 pillSnapshot —— meaningfulSessionTitle 先把它过滤掉', () => {
+ // review 曾担心 priorityCompactTitle 会把原始哨兵带给 native(Swift 侧的 compactTitle
+ // 优先读这个字段)。事实是取值链第一步 meaningfulSessionTitle 就按大小写无关过滤掉
+ // 'new maker' / 'untitled' / 'codex' 等泛化串,pill 因此回落到项目名 —— 小尺寸胶囊里
+ // 项目名本来也比「未命名对话」有信息量。这条断言把该事实钉住,免得日后有人放宽过滤
+ // 又把哨兵漏给 native(PR #1031 review 第 13 轮)。
+ const state = createAgentIslandState();
+
+ applyAgentIslandEvent(
+ state,
+ {
+ sessionId: 's1',
+ title: 'New Maker',
+ agentKind: 'codex',
+ workingDir: '/repo/cindy',
+ },
+ statusEvent(true, 'Thinking'),
+ 1_000,
+ );
+ const display = buildAgentIslandDisplayState(state, 1_050);
+
+ expect(display.pillSnapshot.priorityCompactTitle).toBe('cindy');
+ expect(display.pillSnapshot.priorityCompactTitle).not.toBe('New Maker');
+ expect(display.pillSnapshot.priorityMicroTitle).not.toBe('New Maker');
+ });
+
it('prefers a bounded conversation title over the project name for the compact title', () => {
const state = createAgentIslandState();
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index b6b35ee7a2..065f9f8029 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -10,6 +10,7 @@ import {
} from '@cindy/maker-core';
import type { SchedulerEvent } from '@cindy/maker-scheduler';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
+import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';
import type { ApplicationMenuCommand } from '../../shared/applicationMenuCommands.js';
import { hasSessionAttention as hasAppBadgeSessionAttention } from '../appBadgeService.js';
@@ -1111,19 +1112,41 @@ export class AgentIslandService {
workingDir: patch.workingDir !== undefined ? patch.workingDir : current.workingDir,
workspaceKind: patch.workspaceKind !== undefined ? patch.workspaceKind : current.workspaceKind,
};
- this.metadataCache.set(sessionId, next);
- if (!patchAgentIslandMetadata(this.state, { sessionId, ...next })) return;
- this.publish();
+ this.commitMetadata(sessionId, next);
}
replaySessionActivity(): void {
this.sessionActivityRelay.replay(this.buildSessionActivityPayload());
}
+ /**
+ * 会话元数据的**唯一写出口**:落 cache + patch state + 发布。
+ *
+ * 这里**只存原始标题**,不做本地化投影 —— 投影统一推迟到 {@link localizeDisplayState}
+ * (构建送给 native 的 payload 那一刻)。两个理由:
+ *
+ * - `metadataCache` 必须是原始值 —— {@link ensureMetadata} 靠
+ * `isPlaceholderSessionTitle(cached.title)` 判断「还没拿到权威标题、需要重拉」。
+ * 把本地化文案写进 cache 会让该判定恒为 false,权威标题永远不会再被加载。
+ * - `state` 也必须是原始值 —— 否则切换应用语言时,`refreshLocalization()` 只重建
+ * `state.strings` 并 republish,不会重新投影 metadata,灵动岛会一直显示旧语言的
+ * 兜底文案,直到下一次 metadata 事件才纠正(PR #1031 review P1)。存原始值 +
+ * publish 时投影,切语言后的那次 republish 自然就是新语言,不需要任何重投影逻辑。
+ */
+ private commitMetadata(
+ sessionId: string,
+ meta: { title: string | null; workingDir: string | null; workspaceKind: string | null },
+ ): void {
+ this.metadataCache.set(sessionId, meta);
+ if (!patchAgentIslandMetadata(this.state, { sessionId, ...meta })) return;
+ this.publish();
+ }
+
private hydrateMeta(meta: AgentIslandSessionMeta): AgentIslandSessionMeta & { title?: string | null } {
const cached = this.metadataCache.get(meta.sessionId);
return {
...meta,
+ // 原始标题:投影只在 publish 构建 payload 时做(见 commitMetadata 的说明)。
title: cached?.title ?? null,
workingDir: cached?.workingDir ?? meta.workingDir,
workspaceKind: cached?.workspaceKind ?? meta.workspaceKind,
@@ -1188,15 +1211,11 @@ export class AgentIslandService {
this.metadataLoading.add(sessionId);
void getSessionRowSnapshot(sessionId)
.then((row) => {
- const metadata = {
+ this.commitMetadata(sessionId, {
title: row?.title ?? null,
workingDir: row?.workingDir ?? null,
workspaceKind: row?.workspaceKind ?? null,
- };
- this.metadataCache.set(sessionId, metadata);
- if (patchAgentIslandMetadata(this.state, { sessionId, ...metadata })) {
- this.publish();
- }
+ });
})
.catch((err) => {
log.warn('session metadata load failed', {
@@ -1387,10 +1406,12 @@ export class AgentIslandService {
}
this.hiddenPublished = false;
- const displayState = withAgentIslandConfig(
- buildAgentIslandDisplayState(this.state, now),
- this.soundSettings,
- this.mascotSkin,
+ const displayState = this.localizeDisplayState(
+ withAgentIslandConfig(
+ buildAgentIslandDisplayState(this.state, now),
+ this.soundSettings,
+ this.mascotSkin,
+ ),
);
this.emitSessionActivityToRenderer();
this.scheduleNextPublish(now);
@@ -1413,6 +1434,32 @@ export class AgentIslandService {
}
}
+ /**
+ * 哨兵标题 → 本地化文案的**唯一投影点**:构建送给 native 的 payload 那一刻。
+ *
+ * 不变量:`metadataCache` 与 `state` 一律存**原始**标题,只有这里把哨兵换成兜底文案。
+ *
+ * 放在这里(而不是写 cache / 写 state 时)换来两个性质:
+ * - **切语言即时生效**:`refreshLocalization()` 只重建 `strings` 再 publish,而 publish
+ * 每次都重新走本函数,所以那次 republish 自然带新语言 —— 不需要「本地化刷新时重投影
+ * metadata」这类额外逻辑(PR #1031 review P1)。
+ * - **判定不被污染**:`ensureMetadata` 仍能用 `isPlaceholderSessionTitle(cached.title)`
+ * 判断该不该重拉权威标题。
+ *
+ * 只投影哨兵;真实标题与 null 原样透传(null 由 native 走它自己的空标题分支)。
+ */
+ private localizeDisplayState(state: AgentIslandDisplayState): AgentIslandDisplayState {
+ if (!state.sessions.some((s) => isDefaultDraftSessionTitle(s.title))) return state;
+ return {
+ ...state,
+ sessions: state.sessions.map((session) =>
+ isDefaultDraftSessionTitle(session.title)
+ ? { ...session, title: t('ccAgent.common.unnamedSession') }
+ : session,
+ ),
+ };
+ }
+
private scheduleNextPublish(now: number): void {
this.clearPublishTimer();
const nextAt = getNextAgentIslandTimerAt(this.state, now);
@@ -2201,3 +2248,4 @@ function isPlaceholderSessionTitle(title: string | null): boolean {
const normalized = title.trim().toLowerCase();
return normalized === '' || normalized === 'new maker' || normalized === 'untitled';
}
+
diff --git a/apps/desktop/src/main/applicationMenuLabels.ts b/apps/desktop/src/main/applicationMenuLabels.ts
index ef6a684818..80fa4209f1 100644
--- a/apps/desktop/src/main/applicationMenuLabels.ts
+++ b/apps/desktop/src/main/applicationMenuLabels.ts
@@ -40,7 +40,7 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
settings: '设置…',
checkForUpdates: '检查更新…',
fileMenu: '文件',
- newMaker: '新建 Maker',
+ newMaker: '新建对话',
viewMenu: '显示',
toggleSidebar: '切换侧边栏',
windowMenu: '窗口',
@@ -56,7 +56,7 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
settings: 'Settings…',
checkForUpdates: 'Check for Updates…',
fileMenu: 'File',
- newMaker: 'New Maker',
+ newMaker: 'New Chat',
viewMenu: 'View',
toggleSidebar: 'Toggle Sidebar',
windowMenu: 'Window',
@@ -72,7 +72,7 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
settings: '設定…',
checkForUpdates: 'アップデートを確認…',
fileMenu: 'ファイル',
- newMaker: '新規 Maker',
+ newMaker: '新しい会話',
viewMenu: '表示',
toggleSidebar: 'サイドバーを切り替え',
windowMenu: 'ウインドウ',
@@ -88,7 +88,7 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
settings: '설정…',
checkForUpdates: '업데이트 확인…',
fileMenu: '파일',
- newMaker: '새 Maker',
+ newMaker: '새 대화',
viewMenu: '보기',
toggleSidebar: '사이드바 토글',
windowMenu: '윈도우',
diff --git a/apps/desktop/src/main/commands/builtins.ts b/apps/desktop/src/main/commands/builtins.ts
index ac1dfd5913..4720956cda 100644
--- a/apps/desktop/src/main/commands/builtins.ts
+++ b/apps/desktop/src/main/commands/builtins.ts
@@ -344,7 +344,7 @@ export function registerBuiltinDesktopCommands(
registry.register({
name: 'clear',
description:
- 'Equivalent of "+ New Maker" in the sidebar — opens a fresh empty draft and switches to it. Discards the current conversation context.',
+ 'Equivalent of the sidebar\'s "New Chat" button — opens a fresh empty draft and switches to it. Discards the current conversation context.',
execute: (ctx) => broadcastDesktopCommand(buildPayload('clear', ctx)),
});
diff --git a/apps/desktop/src/main/im/shared/fbotTitle.ts b/apps/desktop/src/main/im/shared/fbotTitle.ts
index 9685bc9292..1d12c66729 100644
--- a/apps/desktop/src/main/im/shared/fbotTitle.ts
+++ b/apps/desktop/src/main/im/shared/fbotTitle.ts
@@ -25,7 +25,10 @@ export const FBOT_DRAFT_TITLE = `${FBOT_TITLE_PREFIX}New`;
export function fbotTitle(displayName: string, prefix: string = FBOT_TITLE_PREFIX): string {
const name = displayName.replace(/\s+/g, ' ').trim().slice(0, 40);
- return `${prefix}${name || 'New Maker'}`;
+ // 空显示名回落到 'New',与 FBOT_DRAFT_TITLE 拼出同一个草稿占位(`FBot · New`)。
+ // 此前写死 'New Maker' 会拼出 `FBot · New Maker`:既和本模块自己的草稿常量不一致,
+ // 也把 desktop 的哨兵串漏进了用户可见的飞书会话标题。
+ return `${prefix}${name || 'New'}`;
}
export function broadcastSessionPatched(
diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
index 1432d61043..c0f6222e22 100644
--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
@@ -14,4 +14,19 @@ describe('conversationSearch source invariants', () => {
"const SEARCH_ROLES = ['user', 'assistant', 'ask_user', 'plan_review'] as const;",
);
});
+
+ // 标题匹配必须按**界面上显示的**标题算:未起名会话行上显示的是本地化兜底文案,
+ // 拿原始哨兵匹配会让「搜得到的」与「看得到的」错位,命中下标也会错位。
+ // renderer 渲染同一个 conversationSearchTitle,两端逐字一致(PR #1031)。
+ it('matches session titles through the shared display projection', () => {
+ expect(conversationSearchSource).toContain(
+ 'fuzzyTitleMatch(conversationSearchTitle(row.title, request.unnamedLabel), query)',
+ );
+ });
+
+ // 返回给 renderer 的 summary 仍是原始存储值:投影只发生在匹配 / 渲染那一刻,
+ // 不把某次请求时的 locale 固化进返回数据(本 PR 第 8 条不变量)。
+ it('keeps the raw stored title in the session summary', () => {
+ expect(conversationSearchSource).toContain('title: row.title,');
+ });
});
diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearchIpc.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearchIpc.test.ts
new file mode 100644
index 0000000000..9802cb4964
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearchIpc.test.ts
@@ -0,0 +1,82 @@
+/**
+ * 会话搜索 IPC:`unnamedLabel` 必须原样转发到 searchConversations。
+ *
+ * 这条测试是补第 6 轮 review 抓到的洞:handler 用白名单重建请求对象,新增字段不加进来
+ * 就会被静默丢掉 —— renderer 传了、main 收不到,表现是「搜界面上看得见的兜底文案搜不到、
+ * 搜内部哨兵 New Maker 反而命中」,而 conversationSearch.ts 那侧的实现完全正确。
+ * 上一轮只钉了投影函数被正确调用,没钉过 IPC 边界(PR #1031)。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ ipcHandle: vi.fn(),
+ searchConversations: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ ipcMain: { handle: h.ipcHandle },
+}));
+vi.mock('../conversationSearch.js', () => ({
+ searchConversations: h.searchConversations,
+}));
+
+import { registerSearchIpc } from '../ipc/search.js';
+
+type Handler = (event: unknown, payload: unknown) => Promise<unknown>;
+
+function handler(): Handler {
+ registerSearchIpc();
+ const call = h.ipcHandle.mock.calls.find(([channel]) => channel === 'local-db:conversations:search');
+ if (!call) throw new Error('search handler not registered');
+ return call[1] as Handler;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.searchConversations.mockResolvedValue({
+ query: 'needle',
+ results: [],
+ vectorUsed: false,
+ vectorSkipReason: null,
+ poolCapped: false,
+ });
+});
+
+describe('local-db:conversations:search — unnamedLabel 透传', () => {
+ it('把 renderer 的已解析文案原样带给 searchConversations', async () => {
+ await handler()(null, { query: 'needle', unnamedLabel: '未命名对话' });
+
+ expect(h.searchConversations).toHaveBeenCalledWith(
+ expect.objectContaining({ query: 'needle', unnamedLabel: '未命名对话' }),
+ );
+ });
+
+ it('不做 trim / 归一:改一个字符就会让两端的命中下标错位', async () => {
+ // main 算 titleMatchIndices、renderer 渲染同一个串,逐字一致是高亮对齐的前提。
+ await handler()(null, { query: 'needle', unnamedLabel: ' Untitled session ' });
+
+ expect(h.searchConversations).toHaveBeenCalledWith(
+ expect.objectContaining({ unnamedLabel: ' Untitled session ' }),
+ );
+ });
+
+ it('没传 / 空白 → undefined(旧 renderer 构建按原始哨兵匹配,不炸)', async () => {
+ const invoke = handler();
+ await invoke(null, { query: 'needle' });
+ await invoke(null, { query: 'needle', unnamedLabel: ' ' });
+
+ for (const call of h.searchConversations.mock.calls) {
+ expect((call[0] as { unnamedLabel?: string }).unnamedLabel).toBeUndefined();
+ }
+ });
+
+ it('类型不对或长度离谱 → INVALID_PARAMS,不静默截断', async () => {
+ const invoke = handler();
+ await expect(invoke(null, { query: 'needle', unnamedLabel: 42 })).rejects.toThrow();
+ await expect(
+ invoke(null, { query: 'needle', unnamedLabel: 'x'.repeat(121) }),
+ ).rejects.toThrow();
+ expect(h.searchConversations).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/localDb/conversationSearch.ts b/apps/desktop/src/main/localDb/conversationSearch.ts
index 92d4fa8ab3..1938059cbc 100644
--- a/apps/desktop/src/main/localDb/conversationSearch.ts
+++ b/apps/desktop/src/main/localDb/conversationSearch.ts
@@ -12,6 +12,7 @@ import type {
ConversationSearchSortBy,
ConversationSearchStatusFilter,
} from '../../shared/conversationSearch.js';
+import { conversationSearchTitle } from '../../shared/conversationSearch.js';
import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';
import { getDbClient } from './client/current.js';
import { messages, sessions } from './schema.js';
@@ -89,7 +90,11 @@ export async function searchConversations(
const titleMatches = sessionRows
.map((row, index) => {
- const match = fuzzyTitleMatch(row.title, query);
+ // 匹配与命中下标都按**界面上显示的**标题算:未起名会话行上显示的是本地化兜底
+ // 文案,拿原始哨兵匹配会两头错位 —— 搜可见文案一条都搜不到,搜 "New Maker" 反而
+ // 命中一堆不显示这个词的行,高亮下标也会落在别的字上(PR #1031 review P1)。
+ // renderer 渲染时调同一个 conversationSearchTitle,两端逐字一致。
+ const match = fuzzyTitleMatch(conversationSearchTitle(row.title, request.unnamedLabel), query);
if (!match) return null;
const session = sessionSummaries.get(row.id);
if (!session) return null;
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
index e17537b99c..a8e3cc0ad9 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
@@ -41,7 +41,6 @@ vi.mock('../../../maker-host/claude-transcript-relocation.js', () => ({
import {
getOverwritableAutoTitle,
isUntitledSessionAwaitingAutoTitle,
- normalizeAutoTitle,
persistSessionTitleIfStillDraft,
} from '../sessions';
@@ -123,14 +122,8 @@ function currentTitle(): string {
}).title;
}
-describe('normalizeAutoTitle', () => {
- it('折叠空白 → trim → 截断 40 字(先 trim 再截断)', () => {
- expect(normalizeAutoTitle(' 帮我\n排查 登录失败 ')).toBe('帮我 排查 登录失败');
- expect(normalizeAutoTitle(`\n${' '.repeat(50)}real text`)).toBe('real text');
- expect(normalizeAutoTitle('排'.repeat(60))).toBe('排'.repeat(40));
- expect(normalizeAutoTitle(' ')).toBe('');
- });
-});
+// normalizeAutoTitle 的用例随实现搬到 packages/maker-shared/src/__tests__/sessionTitle.test.ts
+// (main / renderer / mobile 共用同一份实现,单测跟着实现走)。
describe('persistSessionTitleIfStillDraft — 条件写', () => {
beforeEach(() => createDb('New Maker'));
diff --git a/apps/desktop/src/main/localDb/ipc/search.ts b/apps/desktop/src/main/localDb/ipc/search.ts
index d0be603df8..27720f2637 100644
--- a/apps/desktop/src/main/localDb/ipc/search.ts
+++ b/apps/desktop/src/main/localDb/ipc/search.ts
@@ -35,10 +35,47 @@ export function registerSearchIpc(): void {
| ConversationSearchSemanticMode
| undefined;
const filters = parseFilters(body.filters);
- return searchConversations({ query, limit, includeArchived, sortBy, semanticMode, filters });
+ const unnamedLabel = parseUnnamedLabel(body.unnamedLabel);
+ return searchConversations({
+ query,
+ limit,
+ includeArchived,
+ sortBy,
+ semanticMode,
+ filters,
+ unnamedLabel,
+ });
});
}
+/** i18n 文案不可能有这么长;超限说明调用方拼错了,宁可报错也不静默截断(见下)。 */
+const UNNAMED_LABEL_MAX_LENGTH = 120;
+
+/**
+ * 「尚未起名」会话的显示文案(renderer 已解析的 i18n 值)。
+ *
+ * 必须原样转发,不能截断也不能替换:main 用它算标题匹配与 `titleMatchIndices`、
+ * renderer 用同一个串渲染结果行,两端逐字一致才能保证高亮下标对齐。这里一旦悄悄改动
+ * 或漏传,表现就是「搜界面上看得见的文案搜不到、搜内部哨兵反而命中」——
+ * 本轮 review 抓到的正是漏传(PR #1031)。
+ */
+function parseUnnamedLabel(value: unknown): string | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (typeof value !== 'string') {
+ throwIpcError('INVALID_PARAMS', 'unnamedLabel must be a string');
+ }
+ if (!value.trim()) return undefined;
+ if (value.length > UNNAMED_LABEL_MAX_LENGTH) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ `unnamedLabel must be at most ${UNNAMED_LABEL_MAX_LENGTH} characters`,
+ );
+ }
+ // 刻意**不 trim**:renderer 渲染时用的是 t() 的原串,这里改一个字符就会让两端的
+ // 命中下标错位。只用 trim 判空,转发的仍是原值。
+ return value;
+}
+
function parseFilters(value: unknown): ConversationSearchFilters | undefined {
if (value === undefined || value === null) return undefined;
const body = requireObject(value, 'filters');
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index ea946ecc4a..415ec37008 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -11,6 +11,11 @@ import path from 'node:path';
import { ipcMain, app, BrowserWindow } from 'electron';
import { eq, ne, and, desc, count, inArray, isNotNull, isNull, sql } from 'drizzle-orm';
+import {
+ DEFAULT_DRAFT_SESSION_TITLE,
+ normalizeAutoTitle,
+} from '@cindy/maker-shared/session-title';
+
import { getDbClient } from '../client/current';
import type { DbClient } from '../client/DbClient';
import { sessions, messages } from '../schema';
@@ -51,7 +56,6 @@ import { dismissErrorMessage, rebroadcastAgentSwitchBoundary } from './messages'
import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';
const log = createLogger('sessions');
-const DEFAULT_DRAFT_SESSION_TITLE = 'New Maker';
const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);
/**
@@ -492,14 +496,6 @@ export async function touchUserSendInDb(id: string, atMs?: number): Promise<void
});
}
-/**
- * 自动标题的统一归一化:折叠空白 → trim → 截断 40 字。先 trim 再截断,避免前导
- * 大量空白吃满长度得到空标题。落库出口与占位覆写方都用它算出同一个串。
- */
-export function normalizeAutoTitle(text: string): string {
- return text.replace(/\s+/g, ' ').trim().slice(0, 40).trimEnd();
-}
-
/** fork 出来的会话的占位标题前缀("[Fork] …" / "[Fork·已剥离] …")。 */
const FORK_PLACEHOLDER_TITLE_PREFIX = '[Fork';
diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.ts
index 0c5243df73..4419bffe9c 100644
--- a/apps/desktop/src/main/localDb/mapper.ts
+++ b/apps/desktop/src/main/localDb/mapper.ts
@@ -7,6 +7,8 @@
* 目的:让上层 sessionService/messageService 函数签名与原 HTTP 响应字段完全一致,hooks 零改动。
*/
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+
import type {
sessions,
messages,
@@ -268,7 +270,7 @@ export function sessionCreateToRow(
): SessionInsert {
return {
id,
- title: 'New Maker',
+ title: DEFAULT_DRAFT_SESSION_TITLE,
workingDir: normalizeWorkingDirForStorage(body?.workingDir),
workspaceKind: body?.workspaceKind ?? 'project',
model: body?.model ?? 'claude-sonnet-4-6',
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index b5816669a5..bc8f383176 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -28,7 +28,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
id: "collaboration",
title: "Collaboration mode (lead + workers)",
summary: "Turn on Collab to bring one or more worker agents in beside your session and delegate tasks to them.",
- content: "Collaboration (\"协同\" / Collab) lets one session — the **lead** — bring in one or more **worker** agents to run alongside it (a \"team\"). The lead delegates tasks to workers through a built-in MCP, and you can watch and steer each worker.\n\n**Turning it on:**\n\n- In a project session — local or SSH remote — click the **Collab** pill in the composer toolbar. Both Claude Code and Codex sessions can be the lead, on either side.\n- Pick the first worker's agent (Claude Code or Codex), and optionally its role / model / effort / an initial task.\n- Start. This creates the team plus that first worker.\n\n**Adding more workers:**\n\n- From the collaboration tab's worker list, use **Create new worker** (+) to add more.\n- Default limits are a **soft cap of 5** and a **hard cap of 8** workers per lead — you'll see a warning past the soft cap, and creation is blocked at the hard cap. Both are adjustable (1–20) in the Collaboration section under **Settings > General**.\n\n**While collaborating:**\n\n- Each worker is a full session with its own history, tools, working directory, and model, and runs with permissions bypassed so it doesn't stop to ask. It inherits the lead's working directory by default (or shares the worktree when the lead uses one).\n- A worker's model defaults to your last \"New Maker\" choice for that vendor, falling back to the lead's model.\n- Only one worker is **focused** (shown) at a time — switch between them with the worker tabs / dropdown. You can intervene in any worker directly, and archive workers individually.\n\n**Turning it off:**\n\n- Closing collab **confirms with you first** (in-progress work is lost), then ends the workflow and archives **all** the team's workers. The conversation history stays searchable.\n\n**Notes:**\n\n- The lead must be a Claude Code / Codex **project** session — local **or SSH remote**. On a remote lead, workers are spawned on the **same remote host**, and the collaboration MCP reaches the remote side over an SSH remote-forward to the local bridge (with a persistent bearer token). A worker can't start its own sub-collab (no nesting).\n- A lead can have only **one active collaboration workflow** at a time. If you have two clients open on the same account (e.g. dev + release) and start collab on the same session in both, the second fails with \"开启协同失败\" because a workflow is already active — close one client or end the existing collab.",
+ content: "Collaboration (\"协同\" / Collab) lets one session — the **lead** — bring in one or more **worker** agents to run alongside it (a \"team\"). The lead delegates tasks to workers through a built-in MCP, and you can watch and steer each worker.\n\n**Turning it on:**\n\n- In a project session — local or SSH remote — click the **Collab** pill in the composer toolbar. Both Claude Code and Codex sessions can be the lead, on either side.\n- Pick the first worker's agent (Claude Code or Codex), and optionally its role / model / effort / an initial task.\n- Start. This creates the team plus that first worker.\n\n**Adding more workers:**\n\n- From the collaboration tab's worker list, use **Create new worker** (+) to add more.\n- Default limits are a **soft cap of 5** and a **hard cap of 8** workers per lead — you'll see a warning past the soft cap, and creation is blocked at the hard cap. Both are adjustable (1–20) in the Collaboration section under **Settings > General**.\n\n**While collaborating:**\n\n- Each worker is a full session with its own history, tools, working directory, and model, and runs with permissions bypassed so it doesn't stop to ask. It inherits the lead's working directory by default (or shares the worktree when the lead uses one).\n- A worker's model defaults to your last \"New Chat\" choice for that vendor, falling back to the lead's model.\n- Only one worker is **focused** (shown) at a time — switch between them with the worker tabs / dropdown. You can intervene in any worker directly, and archive workers individually.\n\n**Turning it off:**\n\n- Closing collab **confirms with you first** (in-progress work is lost), then ends the workflow and archives **all** the team's workers. The conversation history stays searchable.\n\n**Notes:**\n\n- The lead must be a Claude Code / Codex **project** session — local **or SSH remote**. On a remote lead, workers are spawned on the **same remote host**, and the collaboration MCP reaches the remote side over an SSH remote-forward to the local bridge (with a persistent bearer token). A worker can't start its own sub-collab (no nesting).\n- A lead can have only **one active collaboration workflow** at a time. If you have two clients open on the same account (e.g. dev + release) and start collab on the same session in both, the second fails with \"开启协同失败\" because a workflow is already active — close one client or end the existing collab.",
},
{
id: "commands",
diff --git a/apps/desktop/src/main/maker-ipc/sessionAutoTitle.ts b/apps/desktop/src/main/maker-ipc/sessionAutoTitle.ts
index efdf9a1be7..92520dadab 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAutoTitle.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAutoTitle.ts
@@ -23,11 +23,11 @@
*/
import type { AgentKind } from '@cindy/maker-core';
+import { normalizeAutoTitle } from '@cindy/maker-shared/session-title';
import {
getOverwritableAutoTitle,
isUntitledSessionAwaitingAutoTitle,
- normalizeAutoTitle,
persistSessionTitleIfStillDraft,
setOnUserSessionTitleWritten,
type OverwritableAutoTitleTarget,
diff --git a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts
index a17dd88972..d5e6c02008 100644
--- a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts
+++ b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts
@@ -309,6 +309,60 @@ describe('ConversationSearchBox live search', () => {
}, { timeout: SEARCH_WAIT_TIMEOUT_MS });
});
+ // 搜索结果行是「列表之外」的第二个标题出口:本 PR 早前只投影了侧边栏 / 会话头 / tab,
+ // 结果行仍渲染原始 title,于是列表写「未命名对话」、搜索结果写 "New Maker"。
+ // 匹配串(main 算下标)与渲染串(这里)必须是同一个 conversationSearchTitle 的结果。
+ it('未起名会话在结果行里显示兜底文案,并把 unnamedLabel 带进请求', async () => {
+ vi.mocked(searchConversations).mockResolvedValue({
+ query: 'needle',
+ results: [
+ {
+ session: {
+ id: 'session-draft',
+ // main 返回的 summary 仍是**原始存储值**(投影只发生在渲染这一刻)。
+ title: 'New Maker',
+ workingDir: '/repo-a',
+ workspaceKind: 'project',
+ agentKind: 'cc',
+ status: 'active',
+ userSendAt: null,
+ updatedAt: '2026-06-14T00:00:00.000Z',
+ createdAt: '2026-06-14T00:00:00.000Z',
+ _count: { messages: 2 },
+ },
+ matchKind: 'title',
+ titleMatchIndices: [],
+ titleScore: 1,
+ contentHit: null,
+ contentHits: [],
+ rankScore: 1,
+ },
+ ],
+ vectorUsed: false,
+ vectorSkipReason: null,
+ poolCapped: false,
+ });
+
+ renderSearchBox({ requestId: 1 });
+ await screen.findByTestId('conversation-search-popover');
+
+ fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), {
+ target: { value: 'needle' },
+ });
+
+ await waitFor(() => {
+ expect(searchConversations).toHaveBeenCalledWith(
+ expect.objectContaining({ unnamedLabel: 'ccAgent.common.unnamedSession' }),
+ );
+ }, { timeout: SEARCH_WAIT_TIMEOUT_MS });
+
+ // mock 的 t 对未识别 key 原样返回 key,所以兜底文案就是这个 key 串。
+ await waitFor(() => {
+ expect(screen.getAllByText('ccAgent.common.unnamedSession').length).toBeGreaterThan(0);
+ }, { timeout: SEARCH_WAIT_TIMEOUT_MS });
+ expect(screen.queryByText('New Maker')).toBeNull();
+ });
+
it('reapplies a same-project menu request when only requestId changes', async () => {
const view = renderSearchBox({ requestId: 1 });
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.ts
index 6775932e24..c1de632d8f 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.ts
@@ -2,7 +2,8 @@
* makerChatStoreAutoName.test.ts
* ---------------------------------------------------------------------------
* renderer 侧自动起名的职责边界(权威逻辑在 main 的 maker:auto-title):
- * - 本机会话:把素材与 isUserText 透传给 main,不自己读写标题;
+ * - 本机会话:把素材与 isUserText 透传给 main,**不写 DB**;标题仍是哨兵时额外在
+ * store 里做一次乐观预览(不等 IPC 往返 + 广播),与远程分支对称;
* - 远程会话:不发 IPC,只在投影层登记即时标题预览;
* - main 返回 done=true 才缓存「无需再起名」,瞬时失败必须可重试。
*/
@@ -22,7 +23,13 @@ vi.mock('@/lib/sessionService', () => ({
touchUserSend: vi.fn(async () => ({})),
}));
-vi.mock('@/lib/sessionsBus', () => ({ emitPatch: vi.fn() }));
+const emitAutoTitlePreview = vi.fn();
+const emitAutoTitlePreviewCleared = vi.fn();
+vi.mock('@/lib/sessionsBus', () => ({
+ emitPatch: vi.fn(),
+ emitAutoTitlePreview: (id: string, title: string) => emitAutoTitlePreview(id, title),
+ emitAutoTitlePreviewCleared: (id: string) => emitAutoTitlePreviewCleared(id),
+}));
vi.mock('@/lib/userPromptStore', () => ({ getUserPrompt: () => '' }));
vi.mock('@/lib/memorySettingsStore', () => ({ getMakerMemoryEnabled: () => true }));
@@ -83,6 +90,40 @@ describe('makerChatStore auto-name — 本机会话', () => {
expect(sessionService.get).not.toHaveBeenCalled();
});
+ it('发出即时标题预览:与 main 随后写入的占位是同一个串,且不碰 DB', async () => {
+ makerChatStore.autoNameSession(SESSION_ID, ' 帮我\n排查 登录失败 ', 'claude-code');
+ await flushPromises();
+
+ // 共用 normalizeAutoTitle → 权威标题回流时不跳变。
+ expect(emitAutoTitlePreview).toHaveBeenCalledWith(SESSION_ID, '帮我 排查 登录失败');
+ // 权威标题仍归 main:renderer 不写 DB。
+ expect(sessionService.update).not.toHaveBeenCalled();
+ // 「标题是否仍是哨兵」由 sessionsStore 在订阅处裁决,不在这里读会话行。
+ expect(sessionService.get).not.toHaveBeenCalled();
+ });
+
+ it('预览抛错既不打断起名 IPC,也不冒泡出去打断发送主流程', async () => {
+ // 预览纯属锦上添花:bus / 订阅方出任何问题都不能让 sendMessageCore 的入队被
+ // 异常打断(与本函数其余副作用同一条契约)。
+ emitAutoTitlePreview.mockImplementationOnce(() => {
+ throw new Error('bus down');
+ });
+
+ expect(() =>
+ makerChatStore.autoNameSession(SESSION_ID, '第一句话', 'claude-code'),
+ ).not.toThrow();
+ await flushPromises();
+
+ expect(autoTitle).toHaveBeenCalled();
+ });
+
+ it('素材为空时既不发 IPC 也不发预览', async () => {
+ makerChatStore.autoNameSession(SESSION_ID, ' ', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreview).not.toHaveBeenCalled();
+ });
+
it('合成描述带上 isUserText=false,由 main 决定不调标题模型', async () => {
makerChatStore.autoNameSession(SESSION_ID, '设计稿-v3.png', 'codex', false);
await flushPromises();
@@ -157,6 +198,105 @@ describe('makerChatStore auto-name — 本机会话', () => {
expect(autoTitle).toHaveBeenCalledTimes(1);
});
+ it('起名失败 → 撤回预览,不让会话永久顶着库里不存在的标题', async () => {
+ // 预览是「马上会有权威标题回流」的赌注;赌输了必须还原,否则叠加层永不失效。
+ autoTitle.mockRejectedValueOnce(new Error('ipc failed'));
+
+ makerChatStore.autoNameSession(SESSION_ID, '帮我排查登录失败', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreview).toHaveBeenCalledWith(SESSION_ID, '帮我排查登录失败');
+ expect(emitAutoTitlePreviewCleared).toHaveBeenCalledWith(SESSION_ID);
+ });
+
+ it('起名成功时不撤回(否则真实标题会被打回哨兵)', async () => {
+ makerChatStore.autoNameSession(SESSION_ID, '帮我排查登录失败', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreviewCleared).not.toHaveBeenCalled();
+ });
+
+ it('正常 resolve 但 applied=false(资格读失败 / 两段都没写进去)同样撤回', async () => {
+ // runSessionAutoTitle 在这类瞬时失败下是**正常 resolve** 的,只挂 .catch 会整类漏掉。
+ autoTitle.mockResolvedValue({ applied: false, done: false });
+
+ makerChatStore.autoNameSession(SESSION_ID, '帮我排查登录失败', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreviewCleared).toHaveBeenCalledWith(SESSION_ID);
+ });
+
+ it('applied=false + done=true(用户已手动改过名)也撤回,叠加层不许盖着用户标题', async () => {
+ autoTitle.mockResolvedValue({ applied: false, done: true });
+
+ makerChatStore.autoNameSession(SESSION_ID, '帮我排查登录失败', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreviewCleared).toHaveBeenCalledWith(SESSION_ID);
+ });
+
+ it('applied=true + done=false(占位已落库、智能标题还在路上)不撤回', async () => {
+ autoTitle.mockResolvedValue({ applied: true, done: false });
+
+ makerChatStore.autoNameSession(SESSION_ID, '帮我排查登录失败', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreviewCleared).not.toHaveBeenCalled();
+ });
+
+ it('IPC 同步抛错(桥接缺失)同样撤回预览', async () => {
+ const w = globalThis as unknown as { window: Record<string, unknown> };
+ w.window = {
+ electronAPI: {
+ maker: {
+ autoTitle: () => {
+ throw new Error('bridge missing');
+ },
+ },
+ },
+ };
+
+ makerChatStore.autoNameSession(SESSION_ID, '帮我排查登录失败', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreviewCleared).toHaveBeenCalledWith(SESSION_ID);
+ });
+
+ it('较早那次尝试失败时不撤回预览 —— 更晚的尝试仍在飞', async () => {
+ // 用户在首次 auto-title 返回前连发两条:两次都通过 autoNameSettled 检查各起一次尝试。
+ // 早的那次失败若按 sessionId 直接撤回,会把仍在飞的那次的预览一起revoke,标题白闪
+ // 一次「未命名对话」。
+ let failFirst: (v: { applied: boolean; done: boolean }) => void = () => {};
+ autoTitle.mockImplementationOnce(() => new Promise((resolve) => {
+ failFirst = resolve;
+ }));
+ autoTitle.mockImplementationOnce(() => new Promise(() => {
+ /* 第二次一直在飞 */
+ }));
+
+ makerChatStore.autoNameSession(SESSION_ID, '第一句', 'claude-code');
+ makerChatStore.autoNameSession(SESSION_ID, '第二句', 'claude-code');
+ await flushPromises();
+
+ // 早的那次失败(正常 resolve 但什么都没写)。
+ failFirst({ applied: false, done: false });
+ await flushPromises();
+
+ expect(emitAutoTitlePreviewCleared).not.toHaveBeenCalled();
+ });
+
+ it('最后一次尝试失败时照常撤回', async () => {
+ // 与上一条互为对照:轮次号相等 → 预览没有别的主人,该撤回。
+ autoTitle.mockResolvedValue({ applied: false, done: false });
+
+ makerChatStore.autoNameSession(SESSION_ID, '第一句', 'claude-code');
+ await flushPromises();
+ makerChatStore.autoNameSession(SESSION_ID, '第二句', 'claude-code');
+ await flushPromises();
+
+ expect(emitAutoTitlePreviewCleared).toHaveBeenCalledWith(SESSION_ID);
+ });
+
it('后续消息不是用户文字(纯附件 / 纯 @mention)时不补起名', async () => {
// 合成描述不该把已有占位换成另一个文件名,更不该被送进标题模型。
makerChatStore.__autoNameUnnamedSessionForTest(SESSION_ID, null, 'claude-code');
diff --git a/apps/desktop/src/renderer/__tests__/sessionLinkPasteTitleProjection.test.ts b/apps/desktop/src/renderer/__tests__/sessionLinkPasteTitleProjection.test.ts
new file mode 100644
index 0000000000..4ed9d92d30
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sessionLinkPasteTitleProjection.test.ts
@@ -0,0 +1,71 @@
+/**
+ * 粘贴会话深链时解析出来的标题,必须在**序列化进消息文本之前**过哨兵投影。
+ *
+ * 为什么这条洞比其它出口更硬:解析结果会被 serializeSessionChipText 写成
+ * `[标题](href)` 进入消息正文,之后对消息侧 SessionLinkChip 来说它就是
+ * `explicitLabel`(作者显式写的 label,渲染层理应原样尊重)。所以原始哨兵一旦被
+ * 序列化进去就**永久**留在消息里,渲染时的投影救不回来(PR #1031 review P1)。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+
+const UNNAMED = '未命名对话';
+
+const sessionGet = vi.fn();
+vi.mock('@/lib/sessionService', () => ({
+ get: (...args: unknown[]) => sessionGet(...args),
+}));
+
+const getMergedRemoteSessions = vi.fn(() => [] as Array<{ id: string; title: string }>);
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ remoteProjectsStore: {
+ getMergedRemoteSessions: () => getMergedRemoteSessions(),
+ },
+}));
+
+vi.mock('@/i18n', () => ({
+ i18n: {
+ t: (key: string) => (key === 'ccAgent.common.unnamedSession' ? UNNAMED : key),
+ },
+}));
+
+import { resolvePastedSessionTitle } from '../components/new-chat/sessionLinkPaste';
+
+const SESSION_ID = 'ee59672a-5591-48a7-a44d-aa97e3808c64';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getMergedRemoteSessions.mockReturnValue([]);
+});
+
+describe('resolvePastedSessionTitle — 哨兵投影', () => {
+ it('本地库返回哨兵 → 解析结果是本地化兜底文案,不是内部英文串', async () => {
+ sessionGet.mockResolvedValue({ title: DEFAULT_DRAFT_SESSION_TITLE });
+
+ await expect(resolvePastedSessionTitle(SESSION_ID)).resolves.toBe(UNNAMED);
+ });
+
+ it('普通标题原样返回', async () => {
+ sessionGet.mockResolvedValue({ title: '修复白屏' });
+
+ await expect(resolvePastedSessionTitle(SESSION_ID)).resolves.toBe('修复白屏');
+ });
+
+ it('本地库没有、走远程镜像降级时同样投影', async () => {
+ // 两条降级分支都要过投影 —— 只改一条就会在另一条上继续泄漏哨兵。
+ sessionGet.mockRejectedValue(new Error('NOT_FOUND'));
+ getMergedRemoteSessions.mockReturnValue([
+ { id: SESSION_ID, title: DEFAULT_DRAFT_SESSION_TITLE },
+ ]);
+
+ await expect(resolvePastedSessionTitle(SESSION_ID)).resolves.toBe(UNNAMED);
+ });
+
+ it('远程镜像也查不到 → 保持 null(chip 停在短 ID,序列化走裸 href)', async () => {
+ sessionGet.mockRejectedValue(new Error('NOT_FOUND'));
+
+ await expect(resolvePastedSessionTitle(SESSION_ID)).resolves.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts b/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts
new file mode 100644
index 0000000000..eceb890343
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts
@@ -0,0 +1,86 @@
+/**
+ * 桌面端「未起名会话标题」投影的出口清单。
+ *
+ * 不变量:会话标题的每个**用户可见**出口都必须过投影(`getSessionDisplayTitle` /
+ * `projectDraftSessionTitle` / `conversationSearchTitle`,三者共用
+ * `isDefaultDraftSessionTitle` 这一个判据),内部哨兵 `New Maker` 一处都不许原样渲染;
+ * 且投影只发生在渲染那一刻,不提前固化进 state / 缓存。
+ *
+ * 侧边栏行 / 卡片 / 会话头 / tab 有各自的行为测试;这里钉住那些散在大组件里、
+ * 没有独立渲染基座的出口(rail 置顶瓷砖、聊天里的会话 chip、等待横幅、通知 payload),
+ * 让「只修了一半」在测试里立刻可见 —— 本 PR 前四轮 review 反复栽在这上面。
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const RENDERER_ROOT = resolve(__dirname, '..');
+
+function read(relPath: string): string {
+ return readFileSync(resolve(RENDERER_ROOT, relPath), 'utf8');
+}
+
+const railNav = read('features/cc-agent/sidebar/RailNav.tsx');
+const linkChip = read('components/chat/SessionLinkChip.tsx');
+const waitBanner = read('components/chat/CredentialSwitchWaitBanner.tsx');
+const sidebarUpper = read('features/cc-agent/CCAgentSidebarUpper.tsx');
+const draftRoute = read('features/cc-agent/NewMakerDraftRoute.tsx');
+
+describe('desktop 会话标题投影出口', () => {
+ it('rail 置顶瓷砖、aria-label 与悬浮预览卡都用显示标题', () => {
+ expect(railNav).toContain(
+ "const displayTitle = getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'));",
+ );
+ expect(railNav).toContain('aria-label={displayTitle}');
+ expect(railNav).toContain('{pinnedTileLabel(displayTitle)}');
+ // 短标签会把 "New Maker" 截成 "New",比整串更难看出问题 —— 原始 title 不许再出现。
+ expect(railNav).not.toContain('pinnedTileLabel(session.title)');
+ expect(railNav).not.toContain('aria-label={session.title}');
+ });
+
+ it('聊天里的会话 chip 过投影', () => {
+ expect(linkChip).toContain("projectDraftSessionTitle(resolvedTitle, t('ccAgent.common.unnamedSession'))");
+ });
+
+ it('凭证等待横幅在渲染时投影,state 里仍存原始标题', () => {
+ expect(waitBanner).toContain(
+ "projectDraftSessionTitle(title, t('ccAgent.common.unnamedSession'))",
+ );
+ // 投影固化进 state 就意味着切语言后要重新拉一遍标题才会变(本 PR 第 8 条不变量)。
+ expect(waitBanner).toContain('setBlockerTitles(titles.filter(');
+ expect(waitBanner).toContain('.then((session) => session.title?.trim() || null)');
+ });
+
+ // 乐观预览必须有失败路径:交接失败(消息退回草稿 / setGoal 抛错)时权威标题永不回流,
+ // 不撤回就会永久盖着 DB 里的哨兵,会话显示一句**没发出去**的话。
+ it('新建会话的两条交接失败路径都撤回标题预览', () => {
+ // worktree 分支:所有「交接失败 → 还原草稿」的 return 都过 restoreFirstMessageDraft,
+ // 撤回放在那一处而不是各 return 前。
+ expect(draftRoute).toContain('emitAutoTitlePreviewCleared(newSession.id);');
+ const restoreFn = draftRoute.indexOf('const restoreFirstMessageDraft = () => {');
+ const clearInRestore = draftRoute.indexOf('emitAutoTitlePreviewCleared(newSession.id);', restoreFn);
+ const restoreFnEnd = draftRoute.indexOf('};', restoreFn);
+ expect(restoreFn).toBeGreaterThan(-1);
+ expect(clearInRestore).toBeGreaterThan(restoreFn);
+ expect(clearInRestore).toBeLessThan(restoreFnEnd);
+
+ // goal 分支:setGoal 抛错时撤回后照旧把异常抛给调用方。
+ expect(draftRoute).toContain('if (optimisticGoalTitle) emitAutoTitlePreviewCleared(newSession.id);');
+
+ // 普通 send 分支:rehomeDraftAttachments / setPending / navigate 在登记之后抛错时,
+ // 由外层 catch 撤回(它拿不到 newSession,靠 optimisticTitleSessionId 记住)。
+ expect(draftRoute).toContain('let optimisticTitleSessionId: string | null = null;');
+ expect(draftRoute).toContain(
+ 'if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);',
+ );
+ });
+
+ it('系统通知 / 飞书 / 手机推送的标题过投影,且语言走 ref 不被钉在首次渲染', () => {
+ expect(sidebarUpper).toContain(
+ 'const title = projectDraftSessionTitle(session?.title, unnamedLabelRef.current);',
+ );
+ expect(sidebarUpper).toContain("unnamedLabelRef.current = t('ccAgent.common.unnamedSession');");
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts b/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts
new file mode 100644
index 0000000000..20dbd23c08
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts
@@ -0,0 +1,305 @@
+// @vitest-environment jsdom
+/**
+ * sessionsStoreAutoTitlePreview.test.ts
+ * ---------------------------------------------------------------------------
+ * 自动起名的「即时标题预览」是**条件**更新,判定归 sessionsStore(它持有列表缓存):
+ * - 标题仍是「尚未起名」哨兵 → 乐观写入,不等 IPC 往返 + DB 广播;
+ * - 已起名 / 用户改过名 / fork 与合成占位 → 一律不动(覆写资格只有 main 能判);
+ * - 缓存里没有这一行 → 不动,交给权威广播回填。
+ *
+ * 发起方(makerChatStore)只 emit,不读会话行 —— 见 makerChatStoreAutoName.test.ts。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+
+import type { Session } from '@/lib/ccAgent.types';
+
+const list = vi.fn();
+vi.mock('@/lib/sessionService', () => ({
+ list: (...args: unknown[]) => list(...args),
+}));
+
+import { emitAutoTitlePreview, emitAutoTitlePreviewCleared } from '@/lib/sessionsBus';
+import { sessionsStore } from '@/lib/sessionsStore';
+
+const SESSION_ID = 's-preview';
+
+function session(over: Partial<Session> = {}): Session {
+ return {
+ id: SESSION_ID,
+ title: DEFAULT_DRAFT_SESSION_TITLE,
+ agentKind: 'cc',
+ status: 'active',
+ workingDir: null,
+ createdAt: '2026-07-30T00:00:00.000Z',
+ updatedAt: '2026-07-30T00:00:00.000Z',
+ ...over,
+ } as Session;
+}
+
+/** 把一行灌进 active 桶,让 findById 命中。 */
+async function seed(row: Session): Promise<void> {
+ list.mockResolvedValue([row]);
+ await sessionsStore.ensureByFilter('active');
+}
+
+function currentTitle(): string | undefined {
+ return sessionsStore.findById(SESSION_ID)?.title;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ sessionsStore.reset();
+});
+
+describe('sessionsStore — 自动起名的即时标题预览', () => {
+ it('标题仍是哨兵 → 乐观写入', async () => {
+ await seed(session());
+
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+
+ expect(currentTitle()).toBe('帮我排查登录失败');
+ });
+
+ it('用户已手动改过名 → 不动,否则会把他的标题在 UI 上顶掉', async () => {
+ await seed(session({ title: '我自己起的名字' }));
+
+ emitAutoTitlePreview(SESSION_ID, '这条消息不该改标题');
+
+ expect(currentTitle()).toBe('我自己起的名字');
+ });
+
+ it('fork 占位 → 不动(能否覆写由 main 的归属表裁决)', async () => {
+ await seed(session({ title: '[Fork] 源会话标题' }));
+
+ emitAutoTitlePreview(SESSION_ID, '第一句话');
+
+ expect(currentTitle()).toBe('[Fork] 源会话标题');
+ });
+
+ it('纯附件写下的合成占位 → 不动,等用户真正打字后由 main 换掉', async () => {
+ await seed(session({ title: '设计稿-v3.png' }));
+
+ emitAutoTitlePreview(SESSION_ID, '这个报错怎么修');
+
+ expect(currentTitle()).toBe('设计稿-v3.png');
+ });
+
+ it('缓存里没有这一行 → 不写入,交给权威广播回填', () => {
+ // 桶未加载:findById 拿不到,预览静默跳过(不应凭空造出一行)。
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+
+ expect(sessionsStore.findById(SESSION_ID)).toBeNull();
+ });
+
+ it('空标题不触发预览(emit 侧已挡掉)', async () => {
+ await seed(session());
+
+ emitAutoTitlePreview(SESSION_ID, '');
+
+ expect(currentTitle()).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ });
+});
+
+describe('sessionsStore — 预览必须活过全量刷新', () => {
+ it('新建会话触发的 forceRefreshAll 不会把预览冲回哨兵', async () => {
+ // 真实时序:createSession → 预览 → sessions:created push → forceRefreshAll,
+ // 而那次重拉从 DB 拿回的行**仍带哨兵**(权威标题要等 auto-title 落库)。
+ // 只写缓存会被冲掉 —— 标题先显示用户那句话、又退回「未命名对话」(review P1)。
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+ expect(currentTitle()).toBe('帮我排查登录失败');
+
+ list.mockResolvedValue([session()]); // DB 侧仍是哨兵
+ await sessionsStore.forceRefreshAll();
+
+ expect(currentTitle()).toBe('帮我排查登录失败');
+ });
+
+ it('桶未加载时先登记,首次 fetch 也能叠加上', async () => {
+ // createSession 早于列表加载完成时,findById 拿不到行,但预览不能因此丢掉。
+ emitAutoTitlePreview(SESSION_ID, '第一句话');
+
+ await seed(session());
+
+ expect(currentTitle()).toBe('第一句话');
+ });
+
+ it('权威标题落地后预览让位并回收,不再顶着真实标题', async () => {
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '占位标题');
+
+ // main 写入智能标题 → sessions:patched 回流。
+ sessionsStore.patchLocal(SESSION_ID, { title: '登录失败排查' });
+ expect(currentTitle()).toBe('登录失败排查');
+
+ // 回收后再刷新也不该把预览翻出来盖回去。
+ list.mockResolvedValue([session({ title: '登录失败排查' })]);
+ await sessionsStore.forceRefreshAll();
+
+ expect(currentTitle()).toBe('登录失败排查');
+ });
+
+ it('起名失败 → 撤回预览,标题退回哨兵(不再永久顶着库里不存在的标题)', async () => {
+ // 叠加层的失效条件是「权威标题落地」。起名 IPC 失败时那个条件永远不成立,
+ // 没有撤回路径的话会话就永久显示首条消息、重启后又变回兜底文案(review P1)。
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+ expect(currentTitle()).toBe('帮我排查登录失败');
+
+ emitAutoTitlePreviewCleared(SESSION_ID);
+
+ expect(currentTitle()).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ });
+
+ it('撤回后连叠加层一起回收:后续全量刷新不会把预览翻出来', async () => {
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+ emitAutoTitlePreviewCleared(SESSION_ID);
+
+ list.mockResolvedValue([session()]); // DB 侧仍是哨兵
+ await sessionsStore.forceRefreshAll();
+
+ expect(currentTitle()).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ });
+
+ it('迟到的撤回不许冲掉已经回流的权威标题', async () => {
+ // 「写库成功但响应丢了」的时序:main 已广播权威标题,撤回才到。
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+ sessionsStore.patchLocal(SESSION_ID, { title: '登录失败排查' });
+
+ emitAutoTitlePreviewCleared(SESSION_ID);
+
+ expect(currentTitle()).toBe('登录失败排查');
+ });
+
+ it('权威标题与预览逐字相同后再撤回 → 不许把已落库的标题打回哨兵', async () => {
+ // 最常见的时序:main 写的占位与预览本来就一样(两端共用 normalizeAutoTitle)。
+ // 若 patchLocal 在「同值」时保留叠加层,缓存里那个串就分不出是乐观值还是权威值,
+ // 随后的失败撤回会把**已经落库**的标题打回哨兵、界面与 DB 不一致(review P1)。
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+
+ // main 写完占位 → sessions:patched 回流,值与预览逐字相同。
+ sessionsStore.patchLocal(SESSION_ID, { title: '帮我排查登录失败' });
+
+ // 之后智能标题那步失败(或响应丢了)→ 撤回到达,但权威值已经落库。
+ emitAutoTitlePreviewCleared(SESSION_ID);
+
+ expect(currentTitle()).toBe('帮我排查登录失败');
+
+ // 且叠加层已回收:后续刷新按 DB 值走,不会再被撤回或预览影响。
+ list.mockResolvedValue([session({ title: '帮我排查登录失败' })]);
+ await sessionsStore.forceRefreshAll();
+ expect(currentTitle()).toBe('帮我排查登录失败');
+ });
+
+ it('没有登记过预览时撤回是 no-op(不把用户手动改的名打回哨兵)', async () => {
+ await seed(session({ title: '我自己起的名字' }));
+
+ emitAutoTitlePreviewCleared(SESSION_ID);
+
+ expect(currentTitle()).toBe('我自己起的名字');
+ });
+
+ it('权威标题晚于在飞的 list 请求写入 → 旧快照不许把它冲回哨兵', async () => {
+ // 真实时序:sessions:created push → forceRefreshAll 起飞(DB 快照里还是哨兵)
+ // → main 写完占位、sessions:patched 落进缓存 → 那个更早的请求才回来。
+ // 没有版本化 override 的话,整桶覆盖会把权威标题冲掉,界面退到「未命名对话」
+ // 直到下一次刷新;乐观预览此刻已按「权威值到达即回收」的规则让位(review P1)。
+ await seed(session());
+
+ let releaseStale: (rows: Session[]) => void = () => {};
+ list.mockImplementationOnce(() => new Promise<Session[]>((resolve) => {
+ releaseStale = resolve;
+ }));
+ const staleRefresh = sessionsStore.forceRefreshAll();
+
+ // 权威标题在旧请求回来之前到达。注意 forceRefresh 已经把桶 drop 了(见其实现),
+ // 此刻缓存里根本没有这一行 —— patchLocal 无处可合并,唯一能救回它的就是 override。
+ // 这也是「解除在飞请求的认领」救不了场的原因:桶是空的,必须让那个请求提交,
+ // 再由 override 把标题补回去。
+ expect(sessionsStore.findById(SESSION_ID)).toBeNull();
+ sessionsStore.patchLocal(SESSION_ID, { title: '帮我排查登录失败' });
+
+ // 旧请求带着 pre-write 快照回来。
+ releaseStale([session()]);
+ await staleRefresh;
+
+ expect(currentTitle()).toBe('帮我排查登录失败');
+ });
+
+ it('新请求发起于标题写入之后 → override 不再插手,DB 值说了算', async () => {
+ // override 只对「发起早于本次写入」的请求生效,否则用户之后在别处改的名会被顶回来。
+ await seed(session());
+ sessionsStore.patchLocal(SESSION_ID, { title: '帮我排查登录失败' });
+
+ list.mockResolvedValue([session({ title: '别处改的新名字' })]);
+ await sessionsStore.forceRefreshAll();
+
+ expect(currentTitle()).toBe('别处改的新名字');
+ });
+
+ it('乐观值不许经 override 层洗成「权威标题」把叠加层误回收', async () => {
+ // 时序:一个桶的刷新先起飞(快照里是哨兵),会话同时还在另一个桶的缓存里 → 预览
+ // 登记 + 乐观写入 → 那个更早的请求回来。若乐观值也登记了权威 override,它会被
+ // override 层重放成非哨兵标题,applyAutoTitlePreviews 便把自己写上去的值当成权威
+ // 标题、回收叠加层;之后又一次(仍返回哨兵的)刷新就再没人保护标题(review P1)。
+ list.mockResolvedValue([session()]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('all');
+
+ let releaseStale: (rows: Session[]) => void = () => {};
+ list.mockImplementationOnce(() => new Promise<Session[]>((resolve) => {
+ releaseStale = resolve;
+ }));
+ const staleRefresh = sessionsStore.forceRefresh('active');
+
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+ expect(currentTitle()).toBe('帮我排查登录失败');
+
+ releaseStale([session()]); // 旧请求带回 DB 里的哨兵
+ await staleRefresh;
+ expect(currentTitle()).toBe('帮我排查登录失败');
+
+ // 关键:叠加层必须还在。main 仍未落库时的下一次刷新还要靠它。
+ list.mockResolvedValue([session()]);
+ await sessionsStore.forceRefreshAll();
+ expect(currentTitle()).toBe('帮我排查登录失败');
+ });
+
+ it('用户手动把标题改成字面量哨兵 → 也算权威写入,预览必须让位', async () => {
+ // main 侧专门有 manuallyRenamed 记号支持这种同值改名,所以它是合法的用户标题。
+ // 回收判据若排除哨兵值,刷新时会先重放权威值、紧接着又被陈旧预览盖回第一句话,
+ // 用户的标题根本显示不出来(review P1)。
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+
+ // 用户改名成 "New Maker" → 经 sessions:patched 回流。
+ sessionsStore.patchLocal(SESSION_ID, { title: DEFAULT_DRAFT_SESSION_TITLE });
+ expect(currentTitle()).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+
+ // 关键:叠加层已回收,后续刷新不许把第一句话盖回来。
+ list.mockResolvedValue([session({ title: DEFAULT_DRAFT_SESSION_TITLE })]);
+ await sessionsStore.forceRefreshAll();
+ expect(currentTitle()).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ });
+
+ it('权威标题恰好等于预览时,后续刷新同样不残留叠加', async () => {
+ // 常见路径:main 写的占位与预览逐字相同(两端共用 normalizeAutoTitle)。
+ await seed(session());
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+ sessionsStore.patchLocal(SESSION_ID, { title: '帮我排查登录失败' });
+
+ list.mockResolvedValue([session({ title: '帮我排查登录失败' })]);
+ await sessionsStore.forceRefreshAll();
+ // 再改名(模拟用户手动重命名)后刷新,预览不得复活。
+ list.mockResolvedValue([session({ title: '我自己起的名字' })]);
+ await sessionsStore.forceRefreshAll();
+
+ expect(currentTitle()).toBe('我自己起的名字');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx b/apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx
index 61ba50f58c..515a28cdeb 100644
--- a/apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx
@@ -14,6 +14,7 @@
import { useEffect, useState } from 'react';
import { X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import * as sessionService from '@/lib/sessionService';
import { Spinner } from '@/components/ui/spinner';
import { cn } from '@/lib/utils';
@@ -63,20 +64,26 @@ export function CredentialSwitchWaitBanner({
};
}, [blockersKey]);
+ // 未起名会话过投影再拼进文案:横幅里原样会露出内部哨兵 "New Maker"。
+ // 刻意在**渲染这一刻**投影、state 里存原始标题:切语言后本次渲染就跟着变,
+ // 不用为了刷新文案重新拉一遍标题(本 PR 的第 8 条不变量)。
+ const displayTitles = blockerTitles.map(
+ (title) => projectDraftSessionTitle(title, t('ccAgent.common.unnamedSession')),
+ );
// 标题连接符跟随当前语言(zh/ja 顿号、en/ko 逗号等),不硬编码中文顿号。
// Intl.ListFormat 在 Electron 的 V8 下全量可用;构造失败(异常 locale)回退简单逗号。
let joinedTitles = '';
- if (blockerTitles.length > 0) {
+ if (displayTitles.length > 0) {
try {
joinedTitles = new Intl.ListFormat(i18n.language || 'en', {
style: 'narrow',
type: 'unit',
- }).format(blockerTitles);
+ }).format(displayTitles);
} catch {
- joinedTitles = blockerTitles.join(', ');
+ joinedTitles = displayTitles.join(', ');
}
}
- const message = blockerTitles.length > 0
+ const message = displayTitles.length > 0
? t('chat.credentialSwitchWait.waitingForNamed', { titles: joinedTitles })
: t('chat.credentialSwitchWait.waiting');
diff --git a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
index 1abca5c260..9744fc66d2 100644
--- a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
@@ -20,6 +20,8 @@ import { CornerDownRight } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
+
import { cn } from '@/lib/utils';
import { parseSessionDeepLinkHref } from '@/lib/deepLink';
import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
@@ -124,7 +126,13 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
);
});
};
- const display = explicitLabel ?? fetchedTitle ?? remoteTitle ?? shortSessionId(sessionId);
+ // 未起名会话过投影再显示:chip 直接摆在消息流里,原样会露出内部哨兵 "New Maker"。
+ const resolvedTitle = fetchedTitle ?? remoteTitle;
+ const display = explicitLabel
+ ?? (resolvedTitle
+ ? projectDraftSessionTitle(resolvedTitle, t('ccAgent.common.unnamedSession'))
+ : null)
+ ?? shortSessionId(sessionId);
const referenceDetails = referenceMetadata
? [
t(
diff --git a/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts b/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts
index 51143ec104..f48e8d0b73 100644
--- a/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts
+++ b/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts
@@ -20,7 +20,9 @@
*/
import type { Editor } from '@tiptap/core';
import { boundAgentReferenceText } from '@cindy/maker-shared/agent-input-projection';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
+import { i18n } from '@/i18n';
import { parseSessionDeepLinkHref } from '@/lib/deepLink';
import { shortSessionId } from '@/lib/sessionId';
@@ -94,13 +96,30 @@ export async function resolvePastedSessionTitle(sessionId: string): Promise<stri
try {
const session = await sessionService.get(sessionId);
const title = session.title?.trim();
- if (title) return title;
+ if (title) return projectResolvedChipTitle(title);
} catch {
// 本地库没有(远程 / 未知会话)→ 走远程镜像降级
}
const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');
const remote = remoteProjectsStore.getMergedRemoteSessions().find((s) => s.id === sessionId);
- return remote?.title?.trim() || null;
+ const remoteTitle = remote?.title?.trim();
+ return remoteTitle ? projectResolvedChipTitle(remoteTitle) : null;
+}
+
+/**
+ * 解析器查到的标题在**序列化进消息文本之前**先过哨兵投影。
+ *
+ * 为什么必须在这一刻、而不是渲染时:这个串会被 `serializeSessionChipText` 写成
+ * `[标题](href)` 进入**消息正文**,之后对消息侧 `SessionLinkChip` 来说它就是
+ * `explicitLabel`(作者显式写下的 label,渲染层理应原样尊重、不做投影)。所以原始
+ * 哨兵一旦被序列化进去就**永久**留在消息里,渲染时的投影救不回来
+ * (PR #1031 review P1)。
+ *
+ * 只投影**自动解析出来的**标题;用户自己在 markdown 里写的 label 走
+ * `titled=true` 分支,压根不经过本函数,不受影响。
+ */
+function projectResolvedChipTitle(title: string): string {
+ return projectDraftSessionTitle(title, i18n.t('ccAgent.common.unnamedSession'));
}
const pendingMessageResolutions = new WeakMap<Editor, Map<string, Promise<void>>>();
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index f076cc5753..e0535af103 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -23,6 +23,7 @@ import { createPortal } from 'react-dom';
import { Archive, ChevronRight, CirclePlus, Folder, Plug, SquarePen, Timer, Trash2, X } from 'lucide-react';
import { useNavigate, useMatch } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
@@ -110,6 +111,7 @@ import {
import { ProjectsSection } from './sidebar/sections/ProjectsSection';
import { DateGroupedSessionsSection } from './sidebar/sections/DateGroupedSessionsSection';
import { isAutomationGeneratedSession } from './lib/scheduledSessionGrouping';
+import { toStoredSessionTitle } from './lib/sessionDisplayTitle';
import {
getVisibleSidebarSessionIds,
pickSessionIdAfterRemoval,
@@ -779,6 +781,10 @@ function ExpandedView({
// 也要标记当前 session 需要关注;真正的 toast / 飞书仍然服从各自开关。
const sessionsRef = useRef(sessions);
sessionsRef.current = sessions;
+ // 通知文案里的「尚未起名」兜底。走 ref 与 sessionsRef 同款:fireSessionNotification
+ // 是 `[]` 依赖的稳定回调,直接闭包 t 会钉住首次渲染的语言。
+ const unnamedLabelRef = useRef('');
+ unnamedLabelRef.current = t('ccAgent.common.unnamedSession');
const fireSessionNotification = useCallback((sessionId: string, kind: 'done' | 'error' | 'needs-reply') => {
// 灵动岛启用时,完成提示由灵动岛承载,不再走系统 toast,避免同一事件双重打扰;
// 灵动岛未启用(或平台不支持)时,继续用系统通知。飞书是独立外发通道,不受影响。
@@ -793,7 +799,10 @@ function ExpandedView({
// 查看,而非跳到 worker 实现细节;与 effectiveRunningSessionIds 的角色聚合口径一致。
if (session && isOrcaWorkerSession(session)) return;
void window.electronAPI.notificationMarkSessionAttention(sessionId);
- const title = session?.title ?? '';
+ // 哨兵过投影:toast / 飞书 / 手机推送里都不能出现内部哨兵 "New Maker"。
+ // (手机推送用的是**桌面侧**语言 —— 标题在 wire payload 里是字面量,让手机按自己
+ // locale 投影要改协议,超出本 PR 范围;但无论如何都比露出哨兵好。)
+ const title = projectDraftSessionTitle(session?.title, unnamedLabelRef.current);
// mobile 通道恒开:桌面侧不设第二个开关,是否收到由手机端注册/注销推送 token
// 决定;发送侧防打扰(远程正在看该会话 / 去重 / relay 能力)在 main 收口。
// 因此桌面/飞书都关时也要 invoke(不再提前 return)。
@@ -1655,12 +1664,16 @@ function ExpandedView({
/* ---- Rename handler ---- */
const handleRename = useCallback(
- async (sessionId: string, newTitle: string) => {
+ async (sessionId: string, editedTitle: string) => {
const session = sessionsByIdRef.current.get(sessionId);
if (isRemoteSessionWriteBlocked(session)) {
toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
return;
}
+ // SessionItem / SessionCard 的重命名输入框预填的是**显示标题**(legacy automation
+ // 会话已剥掉 `[Schedule] ` 前缀),直接落库会让它从 automation 分组里消失。提交前
+ // 把前缀还原回去(PR #1031 review P1)。
+ const newTitle = session ? toStoredSessionTitle(session, editedTitle) : editedTitle;
// 取旧值用于失败回滚,乐观先 patch(不刷整列表,列表顺序保持稳定)
// 保持读 sessions(而非 sessionsById):后者含 remoteProjectSessions,换源会连带
// 改变远程会话的回滚行为,不在本次修复范围内。
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index f0b49978f0..6757c84712 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -101,6 +101,7 @@ import { showWorktreeError } from '@/lib/worktreeToast';
import type { CreateWorktreeResp } from '@/lib/worktree.types';
import * as sessionService from '@/lib/sessionService';
import { sessionsStore } from '@/lib/sessionsStore';
+import { emitAutoTitlePreview, emitAutoTitlePreviewCleared } from '@/lib/sessionsBus';
import { NewGoalDialog } from '@/components/new-chat/NewGoalDialog';
import type { GoalLimitValues } from '@/components/new-chat/GoalAdvancedLimits';
import { makerChatStore } from '@/lib/makerChatStore';
@@ -131,6 +132,10 @@ import {
} from '@/lib/fileTypes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
+import {
+ DEFAULT_DRAFT_SESSION_TITLE,
+ normalizeAutoTitle,
+} from '@cindy/maker-shared/session-title';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import { InvisibleWindowDragStrip } from '@/components/layout/windowDrag';
@@ -222,6 +227,42 @@ export { NEW_MAKER_DRAFT_KEY };
/** 草稿命名空间图片缓存 URL 前缀(浏览器页面评论截图等草稿期缓存落这里)。 */
const DRAFT_IMAGE_URL_PREFIX = `xdt-image://${NEW_MAKER_DRAFT_KEY}/`;
+/**
+ * 「创建即发送」路径的乐观标题 —— 让侧边栏 / 会话头 / tab 从第一帧就显示用户刚写下的
+ * 那句话,而不是先亮一下建会话时的默认占位。
+ *
+ * 背景:权威标题在发送链路的**后段**才写(createSession → navigate → SessionView
+ * mount → sendMessage → `maker:auto-title` IPC → 写库 → 广播回 renderer)。这中间会话
+ * 行已经出现在侧边栏上,标题却还是建会话时的默认值,用户明明已经按下回车却看着一个
+ * 占位。device-link 远程路径早就为此做了即时预览
+ * (`remoteProjectsStore.setPendingTitlePreview`,免得干等一次隧道往返),本机路径缺的
+ * 是对称的这一半。
+ *
+ * 预览经 `emitAutoTitlePreview` 交给 sessionsStore:那边把它记进叠加层,既能活过新建
+ * 会话触发的 `forceRefreshAll`(否则会被仍带哨兵的 DB 快照冲掉),又统一持有「标题是否
+ * 仍是哨兵」这唯一一份判据。不写 DB —— 权威标题仍由 main 落库并广播回来,那个串与这里
+ * 算的是同一个(共用 `normalizeAutoTitle`),回流时不跳变。
+ *
+ * **只对能证明一致的纯文本消息放行**。带 @mention / 附件 / 会话引用时,权威占位由
+ * `deriveAutoTitleSeed` 另行推导(剔除 mention 的 wire token、拿文件名合成描述),这里
+ * 算不出同一个串 —— 预览会先显示 A 再跳成 B,比短暂显示占位更糟。这类消息交给显示层的
+ * 「未命名对话」兜底,等权威标题回流。
+ *
+ * 纯文本时两侧一致是可证明的:无 reference / 未编码引用标记时 `projectLiteralUserText`
+ * 退化为 `text.trim()`,无 mention 时 `stripMentionTokens` 同样只做 trim,而
+ * `normalizeAutoTitle` 本身已含 trim。
+ */
+function optimisticFirstMessageTitle(
+ message: string,
+ files: AttachedFile[] | undefined,
+ mentions: MentionedResource[] | undefined,
+ opts: { quotesEncoded?: boolean; agentReferences?: AgentInputReference[] } | undefined,
+): string | null {
+ if (files?.length || mentions?.length) return null;
+ if (opts?.agentReferences?.length || opts?.quotesEncoded) return null;
+ return normalizeAutoTitle(message) || null;
+}
+
/**
* 由 draft.collab 拼出 createSession 后 enableOrca 的入参:与会话内 requestEnableCollab 同口径。
* 有 workerConfig(用户在「开启协同」弹窗配过 role/model/…)则透传全量;否则只带 workerAgent 回退默认。
@@ -1945,6 +1986,11 @@ export function NewMakerDraftRoute() {
const selectedWorkingDir = effectiveWorkingDir?.trim() || undefined;
markSendInFlight(true);
+ // 已登记乐观标题预览的会话 id。交接链路(rehomeDraftAttachments / setPending /
+ // navigate)在登记之后抛错时,消息没被交出去、权威标题永不回流,预览必须在下面的
+ // catch 里撤回,否则空会话会跨列表刷新一直显示一句**没发出去**的话
+ // (PR #1031 review P1;worktree 与 goal 两条路径各有自己的撤回点)。
+ let optimisticTitleSessionId: string | null = null;
void (async () => {
try {
// device-link:远程草稿就绪态以被控端为准(传 deviceId 走隧道查被控端 maker:agent:status);
@@ -2178,6 +2224,11 @@ export function NewMakerDraftRoute() {
userSendAt: sendAt.toISOString(),
updatedAt: sendAt.toISOString(),
});
+ // 标题即时预览,理由同普通 send 分支(见 optimisticFirstMessageTitle)。
+ {
+ const optimisticTitle = optimisticFirstMessageTitle(message, files, mentions, opts);
+ if (optimisticTitle) emitAutoTitlePreview(newSession.id, optimisticTitle);
+ }
sessionService.touchUserSend(newSession.id, sendAt.getTime()).catch((err) => {
log.warn('[draft worktree send] touchUserSend failed', err);
});
@@ -2218,6 +2269,11 @@ export function NewMakerDraftRoute() {
text: preNavDraftDoc ?? plainTextToTiptapDoc(message),
attachments: rehomedFiles ?? [],
});
+ // 第一条消息退回草稿 = 它没被交出去,也就永远不会有权威标题回流。
+ // 不撤回的话标题预览会一直盖着 DB 里的哨兵(每次全量刷新后重新盖上),
+ // 会话永久显示一句**没发出去**的话(PR #1031 review P1)。
+ // 放在这里而不是各 return 前:所有「交接失败 → 还原草稿」的分支都过这一处。
+ emitAutoTitlePreviewCleared(newSession.id);
};
try {
rehomedFiles = await rehomeDraftAttachments(files, newSession.id);
@@ -2375,9 +2431,17 @@ export function NewMakerDraftRoute() {
// (userSendAt==null && messages==0 → unclassified),否则新会话会先在
// Projects 顶层闪一帧再跳到 workdir 分组下。真实 userSendAt 会通过
// sendMessage 链路里的 emitPatch 再覆盖一次,值差几百 ms 无所谓。
+ //
+ // 标题同理需要即时预览(见 optimisticFirstMessageTitle):否则侧边栏 / 会话头会
+ // 在整个发送链路走完前一直显示建会话时的默认占位。
{
const iso = new Date().toISOString();
sessionsStore.patchLocal(newSession.id, { userSendAt: iso, updatedAt: iso });
+ const optimisticTitle = optimisticFirstMessageTitle(message, files, mentions, opts);
+ if (optimisticTitle) {
+ emitAutoTitlePreview(newSession.id, optimisticTitle);
+ optimisticTitleSessionId = newSession.id;
+ }
}
// F-COLLAB: draft 阶段开了协同 toggle → createSession 之后立刻 enableOrca
@@ -2435,6 +2499,8 @@ export function NewMakerDraftRoute() {
});
} catch (err) {
log.error('[draft send]', err);
+ // 交接失败 → 撤回乐观标题预览(理由见上面 optimisticTitleSessionId 的注释)。
+ if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);
toast.error(
getRemoteWorkingDirErrorMessage(err, t) ?? t('ccAgent.draft.createSessionFailed'),
);
@@ -2622,8 +2688,11 @@ export function NewMakerDraftRoute() {
// maker:generate-title 没有空消息防线,LLM 会把"请提供内容"当标题。
if (!placeholderTitle) return;
// 覆写守卫:仅当远端标题仍是默认占位时才自动起名(user rename wins,
- // PR #296 review)。刚 create-session 建出的会话标题必为 'New Maker',
+ // PR #296 review)。刚 create-session 建出的会话标题必为默认哨兵,
// 此检查防御极端 race;读取失败时按默认占位继续,不中断起名。
+ //
+ // 比对用跨端共享常量:这串由**被控端**(可能是另一个版本的客户端)写入,
+ // 必须逐字一致,不能本地化。
try {
const preCheck = (await window.electronAPI.deviceLink.invoke(
deviceId,
@@ -2631,7 +2700,7 @@ export function NewMakerDraftRoute() {
[remoteSessionId],
)) as { title?: string | null } | null;
const preTitle = preCheck?.title?.trim();
- if (preTitle && preTitle !== 'New Maker') return;
+ if (preTitle && preTitle !== DEFAULT_DRAFT_SESSION_TITLE) return;
} catch {
// 读不到当前标题时按"仍是默认占位"继续。
}
@@ -2662,11 +2731,11 @@ export function NewMakerDraftRoute() {
[remoteSessionId],
)) as { title?: string | null } | null;
const existingTitle = current?.title?.trim();
- // 占位标题与 'New Maker'(maker:create-session 的默认占位符)都允许覆写;
+ // 占位标题与默认哨兵(maker:create-session 的默认占位符)都允许覆写;
// 用户已手动改过的真实标题则保留(user rename wins)。
if (
existingTitle &&
- existingTitle !== 'New Maker' &&
+ existingTitle !== DEFAULT_DRAFT_SESSION_TITLE &&
existingTitle !== placeholderTitle
) {
return;
@@ -2701,9 +2770,13 @@ export function NewMakerDraftRoute() {
if (!newSession) {
throw new Error(t('ccAgent.draft.createSessionFailed'));
}
+ // 目标文案是纯文本(goal 对话框没有附件 / mention 入口),直接即时预览 ——
+ // 与下面 autoNameSession(objective) 最终写入的占位是同一个串。
+ const optimisticGoalTitle = normalizeAutoTitle(objective);
{
const iso = new Date().toISOString();
sessionsStore.patchLocal(newSession.id, { userSendAt: iso, updatedAt: iso });
+ if (optimisticGoalTitle) emitAutoTitlePreview(newSession.id, optimisticGoalTitle);
}
// 草稿开了协同 → 新建目标路径也要拉起 Worker(与 Send 路径同口径);否则用户开了协同
// 却走「新建目标」会得到一个没有 Worker 的 lead session(codex P2)。失败 toast + 降级
@@ -2725,7 +2798,15 @@ export function NewMakerDraftRoute() {
}
}
// setGoal 内部 ensureSession(拉起 agent)+ 发首轮(带目标指令)。
- await window.electronAPI.maker.setGoal({ sessionId: newSession.id, objective, limits });
+ try {
+ await window.electronAPI.maker.setGoal({ sessionId: newSession.id, objective, limits });
+ } catch (err) {
+ // 首轮没发出去 → 下面的 autoNameSession 也不会跑,权威标题永不回流。
+ // 不撤回的话标题预览会永久盖着 DB 里的哨兵(理由同 worktree 分支的
+ // restoreFirstMessageDraft)。异常照旧抛给调用方展示。
+ if (optimisticGoalTitle) emitAutoTitlePreviewCleared(newSession.id);
+ throw err;
+ }
// 自动起名:/goal 新建的会话不经普通发送路径,scheduleAutoName 漏触发 → 标题会停在默认。
// 这里用目标文案补一次,与普通会话同款(立即占位 + 智能标题后台覆盖 + 不覆盖手动改名)。
makerChatStore.autoNameSession(newSession.id, objective, capabilityAgentKind);
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index f0f1e96e40..30e4700bfd 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -52,7 +52,11 @@ import { WINDOW_NO_DRAG_STYLE, useManualWindowDrag } from '@/components/layout/w
import { recentWorkdirsStore } from '@/lib/recentWorkdirsStore';
import { useRegisterContentHeader } from '../feature-context';
import { useSessionLifecycleActions } from './hooks/useSessionLifecycleActions';
-import { getAutomationSessionDisplayTitle } from './lib/scheduledSessionGrouping';
+import {
+ getSessionDisplayTitle,
+ isEmptyDraftSession,
+ toStoredSessionTitle,
+} from './lib/sessionDisplayTitle';
import {
getVisibleSidebarSessionIds,
pickSessionIdAfterRemoval,
@@ -140,8 +144,8 @@ export function SessionContentHeader({
const isPinned = session.pinnedAt != null;
const isArchived = session.status === 'archived';
- // Draft 判定与 SessionItem 同口径:未改名的 New Maker 且无消息。
- const isEmpty = session.title === 'New Maker' && (session._count?.messages ?? 0) === 0;
+ // Draft 判定与 SessionItem 同口径:标题仍是默认哨兵且无消息。
+ const isEmpty = isEmptyDraftSession(session);
const remoteWritesBlocked =
remoteSessionUnavailable || isRemoteSessionWriteBlocked(session);
// 「移动到项目」/「导出会话…」可见性与 SessionItem 同条件。
@@ -153,7 +157,8 @@ export function SessionContentHeader({
// heartbeat schedule 绑定标识,与 SessionItem 同源数据;删除/过期后自动消失。
const boundSchedules = useSessionBoundSchedules(session.id);
const displayTitle =
- getAutomationSessionDisplayTitle(session)?.trim() || t('ccAgent.sessionHeader.untitled');
+ getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'))?.trim() ||
+ t('ccAgent.sessionHeader.untitled');
const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null;
const remoteIconConnectionStatus = session.deviceLinkDeviceId
? session.deviceLinkConnectionStatus ?? 'connected'
@@ -175,15 +180,13 @@ export function SessionContentHeader({
showRemoteWriteBlockedToast();
return;
}
- setEditValue(session.title?.trim() || displayTitle);
+ // 预填用 displayTitle,不是原始 session.title —— 后者在未起名的会话上是英文
+ // 哨兵,会把 "New Maker" 填进重命名输入框。commitTitle 的 `unchanged` 判据同步
+ // 把 displayTitle 也算作「没改」,否则原样回车会把兜底文案写进库冲掉哨兵。
+ setEditValue(displayTitle);
committedRef.current = false;
setIsEditing(true);
- }, [
- displayTitle,
- remoteWritesBlocked,
- session.title,
- showRemoteWriteBlockedToast,
- ]);
+ }, [displayTitle, remoteWritesBlocked, showRemoteWriteBlockedToast]);
// 标题文字是 no-drag(否则 onDoubleClick 收不到,见 span 处注释),
// 拖窗习惯由手动拖拽补回:按住标题移动超过死区即拖动窗口。
@@ -196,17 +199,26 @@ export function SessionContentHeader({
committedRef.current = true;
const trimmed = raw.trim();
setIsEditing(false);
+ // 「没改」= 与原始标题相同,**或**与预填的显示标题相同。后者不可省:未起名的
+ // 会话预填的是本地化兜底文案(「未命名对话」),它不等于库里的英文哨兵 —— 只比
+ // session.title 的话,用户双击后原样回车就会把兜底文案写进库、把哨兵冲掉,
+ // 自动起名从此永久跳过这个会话(标题永远停在「未命名对话」)。
+ const unchanged = !trimmed || trimmed === session.title || trimmed === displayTitle;
if (remoteWritesBlocked) {
- if (trimmed && trimmed !== session.title) showRemoteWriteBlockedToast();
+ if (!unchanged) showRemoteWriteBlockedToast();
return;
}
- if (!trimmed || trimmed === session.title) return;
+ if (unchanged) return;
+ // 预填是**显示标题**(legacy automation 会话已剥掉 `[Schedule] ` 前缀),落库前还原,
+ // 否则 isAutomationGeneratedSession 认不出它、会话从 automation 分组消失
+ // (PR #1031 review P1)。
+ const stored = toStoredSessionTitle(session, trimmed);
const oldTitle = session.title;
- patchLocal(session.id, { title: trimmed });
+ patchLocal(session.id, { title: stored });
try {
// 远程会话:patch-meta 经隧道写被控端 → 广播 sessions:patched → applyPatch 更新远程分片
// (纯镜像,无需重拉);本机会话 patchLocal 已乐观反映。
- await sessionService.patchMeta(session.id, { title: trimmed });
+ await sessionService.patchMeta(session.id, { title: stored });
} catch (err) {
log.error('[session rename]', err);
toast.error(t('ccAgent.sidebar.renameFailed'));
@@ -214,6 +226,7 @@ export function SessionContentHeader({
}
},
[
+ displayTitle,
remoteWritesBlocked,
session.id,
session.title,
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionDisplayTitle.test.ts b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionDisplayTitle.test.ts
new file mode 100644
index 0000000000..ecc2db3194
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionDisplayTitle.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect } from 'vitest';
+
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+
+import type { Session } from '@/lib/ccAgent.types';
+
+import {
+ canHighlightSessionDisplayTitle,
+ getSessionDisplayTitle,
+ isEmptyDraftSession,
+ toStoredSessionTitle,
+} from '../sessionDisplayTitle';
+
+const UNNAMED = '未命名对话';
+
+function session(over: Partial<Session> = {}): Session {
+ return {
+ id: 's1',
+ title: DEFAULT_DRAFT_SESSION_TITLE,
+ agentKind: 'cc',
+ status: 'active',
+ workingDir: null,
+ createdAt: '2026-07-30T00:00:00.000Z',
+ updatedAt: '2026-07-30T00:00:00.000Z',
+ ...over,
+ } as Session;
+}
+
+describe('getSessionDisplayTitle', () => {
+ it('哨兵标题换成本地化兜底文案', () => {
+ expect(getSessionDisplayTitle(session(), UNNAMED)).toBe(UNNAMED);
+ });
+
+ it('已起名的会话原样返回', () => {
+ expect(getSessionDisplayTitle(session({ title: '帮我排查登录失败' }), UNNAMED)).toBe(
+ '帮我排查登录失败',
+ );
+ });
+
+ it('哨兵 + 已有消息也兜底 —— 判定口径比 isEmptyDraftSession 宽', () => {
+ // 自动起名失败(离线 / 模型不可用)时会话有消息但标题仍停在哨兵上,
+ // 那种情况同样不能把英文哨兵漏给用户看。
+ //
+ // 已知代价(明确取舍,见 getSessionDisplayTitle 的文档):用户手动把标题改成
+ // 字面量 "New Maker" 时也会显示成兜底文案 —— 要区分得给标题带 provenance,
+ // 而 main 的 manuallyRenamed 是进程内存态、不落库、不过 device-link。
+ // 这条断言就是那个取舍本身,改它之前先读那段文档(PR #1031 review 第 11 轮)。
+ const s = session({ _count: { messages: 3 } } as Partial<Session>);
+ expect(isEmptyDraftSession(s)).toBe(false);
+ expect(getSessionDisplayTitle(s, UNNAMED)).toBe(UNNAMED);
+ });
+
+ it('automation 会话仍然剥掉 [Schedule] 前缀', () => {
+ expect(getSessionDisplayTitle(session({ title: '[Schedule] nightly-build' }), UNNAMED)).toBe(
+ 'nightly-build',
+ );
+ });
+});
+
+describe('isEmptyDraftSession', () => {
+ it('哨兵 + 零消息 = 空草稿', () => {
+ expect(isEmptyDraftSession(session())).toBe(true);
+ expect(isEmptyDraftSession(session({ _count: { messages: 0 } } as Partial<Session>))).toBe(true);
+ });
+
+ it('有消息或已起名都不算空草稿', () => {
+ expect(isEmptyDraftSession(session({ _count: { messages: 1 } } as Partial<Session>))).toBe(false);
+ expect(isEmptyDraftSession(session({ title: '已起名' }))).toBe(false);
+ });
+});
+
+describe('toStoredSessionTitle — 显示投影必须还原成存储值', () => {
+ it('legacy automation 会话补回 [Schedule] 前缀', () => {
+ // 预填给用户的是剥掉前缀的 'nightly'。若原样落库,isAutomationGeneratedSession
+ // (legacy 数据只靠前缀识别)再也认不出它,会话从 automation 分组消失。
+ const s = session({ title: '[Schedule] nightly' });
+ expect(getSessionDisplayTitle(s, UNNAMED)).toBe('nightly');
+ expect(toStoredSessionTitle(s, '每晚构建')).toBe('[Schedule] 每晚构建');
+ });
+
+ it('用户自己把前缀打回来时不重复叠加', () => {
+ expect(toStoredSessionTitle(session({ title: '[Schedule] nightly' }), '[Schedule] x')).toBe(
+ '[Schedule] x',
+ );
+ });
+
+ it('普通会话原样返回', () => {
+ expect(toStoredSessionTitle(session({ title: '帮我排查登录失败' }), '新名字')).toBe('新名字');
+ });
+
+ it('新数据(source=scheduler,无前缀)不被塞前缀', () => {
+ // 新数据靠 source 字段识别,标题里不该出现内部前缀。
+ const s = session({ title: 'nightly', source: 'scheduler' } as Partial<Session>);
+ expect(toStoredSessionTitle(s, '每晚构建')).toBe('每晚构建');
+ });
+
+ it('哨兵会话原样返回 —— 兜底文案由调用方的「没改」判据挡住', () => {
+ expect(toStoredSessionTitle(session(), '真的改名了')).toBe('真的改名了');
+ });
+});
+
+describe('canHighlightSessionDisplayTitle', () => {
+ it('显示串等于原始 title 时才允许高亮', () => {
+ expect(canHighlightSessionDisplayTitle(session({ title: '帮我排查登录失败' }))).toBe(true);
+ });
+
+ it('哨兵标题关掉高亮 —— matchIndices 是按原始 title 算的,会错位', () => {
+ expect(canHighlightSessionDisplayTitle(session())).toBe(false);
+ });
+
+ it('[Schedule] 前缀被剥离时同样关掉高亮(既有 case)', () => {
+ expect(canHighlightSessionDisplayTitle(session({ title: '[Schedule] nightly' }))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/scheduledSessionGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/scheduledSessionGrouping.ts
index cc5e81bd35..42520a40d3 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/scheduledSessionGrouping.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/scheduledSessionGrouping.ts
@@ -12,7 +12,13 @@ import type { Session, AgentKind } from '@/lib/ccAgent.types';
import { extractDisplayName, normalizeWorkingDir } from './projectGrouping';
-const SCHED_PREFIX = '[Schedule] ';
+/**
+ * legacy automation 会话的标题前缀。**非 i18n 串**:它是旧数据唯一的来源标记
+ * (新数据走 `source='scheduler'`),既用于识别也用于展示时剥离。重命名落库前要靠它
+ * 把前缀补回去,否则 legacy 会话会从 automation 分组里消失 —— 故对外导出。
+ */
+export const SCHEDULE_TITLE_PREFIX = '[Schedule] ';
+const SCHED_PREFIX = SCHEDULE_TITLE_PREFIX;
export function isScheduledSession(s: Session): boolean {
if (typeof s.title !== 'string') return false;
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionDisplayTitle.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionDisplayTitle.ts
new file mode 100644
index 0000000000..e235536813
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionDisplayTitle.ts
@@ -0,0 +1,92 @@
+/**
+ * sessionDisplayTitle —— 会话标题「存储值 → 显示值」的单一来源。
+ *
+ * 会话的 `title` 列身兼两职:既是用户可见标题,又是「尚未起名」的哨兵
+ * (`DEFAULT_DRAFT_SESSION_TITLE`)。哨兵必须保持 locale-independent 的英文字面量
+ * (跨设备 / 跨语言逐字比对 + 条件写的期望值,详见 `@cindy/maker-shared/session-title`),
+ * 所以**本地化只能发生在显示层** —— 也就是这里。
+ *
+ * 显示层此前散落着三份 `session.title === 'New Maker' && messages === 0` 的硬编码
+ * 判定(侧边栏行 / 卡片 / 会话头),既容易漏,也让英文哨兵直接漏到界面上。
+ */
+
+import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';
+
+import type { Session } from '@/lib/ccAgent.types';
+
+import {
+ getAutomationSessionDisplayTitle,
+ isScheduledSession,
+ SCHEDULE_TITLE_PREFIX,
+} from './scheduledSessionGrouping';
+
+/**
+ * 「空草稿会话」—— 标题仍是哨兵且一条消息都没有。
+ *
+ * 用于操作菜单收窄成 Draft 变体(Rename / Copy ID / Delete):没有内容的会话谈不上
+ * 归档、导出、分享。**刻意要求零消息**,与显示兜底的判定口径不同(见
+ * {@link getSessionDisplayTitle} 的说明)。
+ */
+export function isEmptyDraftSession(session: Session): boolean {
+ return isDefaultDraftSessionTitle(session.title) && (session._count?.messages ?? 0) === 0;
+}
+
+/**
+ * 会话在侧边栏 / 卡片 / 会话头 / tab 上应该显示的标题。
+ *
+ * `unnamedLabel` 传已解析的 i18n 文案(`ccAgent.common.unnamedSession`)——与
+ * `autoTitleFallbackLabels()` 同款:纯函数不碰 i18n 实例,好测也好复用。
+ *
+ * 兜底条件**只看标题是不是哨兵、不看消息数**,比 {@link isEmptyDraftSession} 更宽:
+ * 自动起名失败(离线 / 模型不可用)或纯附件首条消息连描述都合成不出来时,会话有消息
+ * 但标题仍停在哨兵上。那种情况照样不能把英文哨兵漏给用户看。
+ *
+ * **已知代价(明确取舍,不是漏判)**:用户如果手动把标题改成字面量 `New Maker`,这里
+ * 也会显示成兜底文案。要区分「用户写的这个串」与「建会话时的哨兵」,只能给标题带上
+ * provenance —— 而 main 的 `manuallyRenamed` 是进程内存态、不落库、不过 device-link,
+ * renderer 无从得知。真要支持得先持久化一个 `titleSource` 位,再把它透到桌面 / 共享列表 /
+ * 搜索 / mobile 四处投影,并进跨端 wire protocol。换来的只是「有人刻意把对话命名为内部
+ * 英文占位、且在意它逐字显示」这一种情形;而放宽条件换掉的是自动起名失败时英文哨兵
+ * 直接漏给用户看 —— 那是本 PR 存在的理由。故按现状取舍(PR #1031 review,第 11 轮)。
+ */
+export function getSessionDisplayTitle(session: Session, unnamedLabel: string): string {
+ if (isDefaultDraftSessionTitle(session.title)) return unnamedLabel;
+ return getAutomationSessionDisplayTitle(session);
+}
+
+/**
+ * 把用户在重命名输入框里编辑的结果还原成**可落库的存储标题**。
+ *
+ * 存在的理由:`getSessionDisplayTitle` 是**只读投影** —— 它对 legacy automation 会话
+ * 剥掉了 `[Schedule] ` 前缀、对未起名会话把哨兵换成了兜底文案。重命名预填用的是这个
+ * 投影值(否则输入框里会出现内部前缀或英文哨兵),因此提交时必须把变换还原回去,否则
+ * 写进 DB 的是**投影后**的串:
+ *
+ * - legacy automation 会话(只靠 `[Schedule] ` 前缀识别、没有 `source='scheduler'`)
+ * 一旦被存成无前缀标题,`isAutomationGeneratedSession` 再也认不出它,会话就从
+ * automation 分组和相关 UI 里消失(PR #1031 review P1)。
+ * - 哨兵会话若被存成兜底文案,自动起名的哨兵匹配失效、永久跳过该会话。后者由调用方
+ * 的「没改就不落库」判据挡住(编辑结果等于预填值时直接 return),这里只负责前缀。
+ *
+ * 新数据带 `source='scheduler'`,不依赖前缀,所以只需给仍带前缀的行补回去。
+ */
+export function toStoredSessionTitle(session: Session, editedTitle: string): string {
+ if (!isScheduledSession(session)) return editedTitle;
+ // 用户手动把前缀打回来了(或压根没删)→ 不重复叠加。
+ if (editedTitle.startsWith(SCHEDULE_TITLE_PREFIX)) return editedTitle;
+ return `${SCHEDULE_TITLE_PREFIX}${editedTitle}`;
+}
+
+/**
+ * 模糊搜索命中高亮能否直接套在显示标题上。
+ *
+ * `matchIndices` 是搜索在**原始** `session.title` 上算出的下标
+ * (见 `lib/sessionSearch.ts` 的 `fuzzyFilterAndRank`),显示串一旦与原串不同,下标
+ * 就会错位、把高亮画到别的字上。两种情况必须关掉高亮:
+ *
+ * - `[Schedule] xxx` 前缀被剥掉(既有 case);
+ * - 哨兵标题被换成本地化的「未命名对话」(本次新增,同一个坑)。
+ */
+export function canHighlightSessionDisplayTitle(session: Session): boolean {
+ return !isScheduledSession(session) && !isDefaultDraftSessionTitle(session.title);
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
index 91ff8dd946..10252a8d51 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
@@ -49,6 +49,7 @@ import type {
ConversationSearchSortBy,
ConversationSearchStatusFilter,
} from '../../../../shared/conversationSearch';
+import { conversationSearchTitle } from '../../../../shared/conversationSearch';
import { highlightSegments } from '../lib/highlightSegments';
import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import type { ProjectNode as ProjectNodeData } from '../lib/projectGrouping';
@@ -152,6 +153,11 @@ export function useConversationSearch({
onProgrammaticOpen,
onResultChosen,
}: UseConversationSearchParams) {
+ const { t } = useTranslation();
+ // 「尚未起名」会话的显示文案。main 拿它算标题匹配与命中下标、结果行拿它渲染
+ // (两侧都过 conversationSearchTitle),所以它必须进请求 **和** effect 依赖:
+ // 切语言后要重发一次搜索,否则下标还按旧语言的串算、高亮会错位。
+ const unnamedLabel = t('ccAgent.common.unnamedSession');
const [query, setQuery] = useState('');
// 排序订阅共享偏好 store(持久化 + 跨实例同步),其余筛选每次回到默认
// ——取舍与「为什么不是各自 useState」见 conversationSearchPrefs 的文件头。
@@ -229,6 +235,7 @@ export function useConversationSearch({
query: trimmed,
limit: SEARCH_LIMIT,
sortBy,
+ unnamedLabel,
filters: {
status: statusFilter,
agentKind: agentFilter,
@@ -282,6 +289,7 @@ export function useConversationSearch({
sortBy,
statusFilter,
trimmed,
+ unnamedLabel,
]);
/**
@@ -894,6 +902,9 @@ function SearchResultRow({
}) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
+ // 与 main 的匹配串同源:未起名会话在结果行里也不能露出英文哨兵,且 titleMatchIndices
+ // 就是按这个串算出来的,换成原始 title 会让高亮下标错位。
+ const displayTitle = conversationSearchTitle(item.session.title, t('ccAgent.common.unnamedSession'));
const primaryHit = item.contentHit;
const allHits = item.contentHits ?? (primaryHit ? [primaryHit] : []);
const visibleHits = expanded ? allHits : allHits.slice(0, MAX_VISIBLE_HITS_PER_RESULT);
@@ -911,7 +922,7 @@ function SearchResultRow({
].filter(Boolean).join(' · ');
const tooltip = (
<div className="space-y-2">
- <div className="font-medium leading-snug">{item.session.title}</div>
+ <div className="font-medium leading-snug">{displayTitle}</div>
{primaryHit?.preview && (
<div className="border-t border-[var(--cmd-palette-border)] pt-2 text-[12px] leading-snug text-[var(--tooltip-text)]">
{renderSnippet(primaryHit.snippet, query) ?? renderKeywordHighlights(primaryHit.preview, query)}
@@ -938,7 +949,7 @@ function SearchResultRow({
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[13px] font-medium text-[var(--text-primary)]">
- {highlightSegments(item.session.title, item.titleMatchIndices)}
+ {highlightSegments(displayTitle, item.titleMatchIndices)}
</span>
<Tip text={sourceText} side="top" delay={150}>
<span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-1.5 py-0.5 text-[10px] leading-none text-[var(--text-tertiary)]">
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
index 8334e1e12b..419d30c3fe 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
@@ -32,6 +32,7 @@ import { SortableList } from '@/components/sidebar/SortableList';
import { useReducedMotion } from '@/hooks/useReducedMotion';
import { isOrcaWorkerSession, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { projectIdentityKeyForSession } from '../lib/projectGrouping';
+import { getSessionDisplayTitle } from '../lib/sessionDisplayTitle';
import { SessionStatusIcon } from './SessionStatusIcon';
import { formatSidebarTime } from '../lib/formatSidebarTime';
import { railPanelStore, type RailPanelSection } from './railPanelStore';
@@ -154,7 +155,7 @@ function SessionPreviewCard({ preview }: { preview: PreviewState }) {
isRunning ? 'text-[var(--cmd-palette-item-meta)]' : 'text-foreground',
)}
>
- {session.title}
+ {getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'))}
</div>
{body && (
<div
@@ -322,10 +323,13 @@ export function RailNav({
const remoteLamp = remoteLampOf(session.id);
const isRunning = runningSessionIds.has(session.id) || remoteLamp?.running === true;
const hasUnread = notifications.has(session.id) || remoteLamp?.tone != null;
+ // 瓷砖短标签、aria-label、悬浮预览卡都用同一个显示标题:置顶一条刚建的会话时
+ // 原始标题是内部哨兵,原样用会让 rail 上出现 "New Maker"(短标签甚至会截成 "New")。
+ const displayTitle = getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'));
return (
<button
key={session.id}
- aria-label={session.title}
+ aria-label={displayTitle}
aria-current={isActive ? 'page' : undefined}
onClick={() => void handlePinnedClick(session.id)}
onMouseEnter={(e) => {
@@ -375,7 +379,7 @@ export function RailNav({
: 'text-[var(--text-secondary)] group-hover/pin:text-foreground',
)}
>
- {pinnedTileLabel(session.title)}
+ {pinnedTileLabel(displayTitle)}
</span>
</button>
);
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index d658a92ca6..c98155dfaf 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -57,11 +57,12 @@ import { createLogger } from '@/lib/logger';
import { formatSidebarTime, formatSidebarTimeAbsolute } from '../lib/formatSidebarTime';
import { highlightSegments } from '../lib/highlightSegments';
import { scrollIntoNearestView } from '../lib/scrollIntoNearestView';
+import { isAutomationGeneratedSession } from '../lib/scheduledSessionGrouping';
import {
- getAutomationSessionDisplayTitle,
- isAutomationGeneratedSession,
- isScheduledSession,
-} from '../lib/scheduledSessionGrouping';
+ canHighlightSessionDisplayTitle,
+ getSessionDisplayTitle,
+ isEmptyDraftSession,
+} from '../lib/sessionDisplayTitle';
import { SessionProjectMoveSubmenu } from './SessionProjectMoveSubmenu';
import { SessionRenameInput } from '../SessionRenameInput';
import type { SessionItemProps } from './SessionItem';
@@ -129,7 +130,7 @@ export function SessionCard({
// 灵动岛同源的 per-session 实时活动(执行中逐步活动 + 等待交互态)。
const islandActivity = useAgentIslandActivity(session.id);
const isPinned = session.pinnedAt != null;
- const isEmpty = session.title === 'New Maker' && (session._count?.messages ?? 0) === 0;
+ const isEmpty = isEmptyDraftSession(session);
const activityIso = session.updatedAt;
const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null;
const remoteIconConnectionStatus = session.deviceLinkDeviceId
@@ -140,8 +141,8 @@ export function SessionCard({
const boundSchedules = useSessionBoundSchedules(session.id);
const showScheduleBindingBadge = boundSchedules.length > 0;
const showAutomationTimer = !showScheduleBindingBadge && isAutomationGenerated;
- const displayTitle = getAutomationSessionDisplayTitle(session);
- const canHighlightDisplayTitle = !isScheduledSession(session);
+ const displayTitle = getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'));
+ const canHighlightDisplayTitle = canHighlightSessionDisplayTitle(session);
const isArchived = session.status === 'archived';
const canQuickArchive = !isArchived && !isEmpty && !remoteWritesBlocked;
// 卡片/列表的正文固定给预览区域。list 保留 main 既有实时执行文案;
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index 3bbec6b01d..fbbe2fc7ed 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -66,11 +66,12 @@ import { createLogger } from '@/lib/logger';
import { formatSidebarTime, formatSidebarTimeAbsolute } from '../lib/formatSidebarTime';
import { highlightSegments } from '../lib/highlightSegments';
import { scrollIntoNearestView } from '../lib/scrollIntoNearestView';
+import { isAutomationGeneratedSession } from '../lib/scheduledSessionGrouping';
import {
- getAutomationSessionDisplayTitle,
- isAutomationGeneratedSession,
- isScheduledSession,
-} from '../lib/scheduledSessionGrouping';
+ canHighlightSessionDisplayTitle,
+ getSessionDisplayTitle,
+ isEmptyDraftSession,
+} from '../lib/sessionDisplayTitle';
import { useSessionBoundSchedules } from '@/features/scheduler/lib/scheduleSessionBinding';
import { loadScheduleSidebarIndexRuns, type ScheduleSidebarIndexRun } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
import { useSchedulesSnapshot } from '@/features/scheduler/lib/schedulesStore';
@@ -195,7 +196,7 @@ export const SessionItem = memo(function SessionItem({
const { t } = useTranslation();
const prRefs = usePrRefsForSession(session.id);
const isPinned = session.pinnedAt != null;
- const isEmpty = session.title === 'New Maker' && (session._count?.messages ?? 0) === 0;
+ const isEmpty = isEmptyDraftSession(session);
// 取 userSendAt 与 updatedAt 中较新的值,兼容存量 DB 行(旧版只写 userSendAt),
// 与 projectGrouping/dateSessionGrouping 的排序时间轴保持一致。
const activityIso =
@@ -325,8 +326,8 @@ export const SessionItem = memo(function SessionItem({
);
}
}, [effectiveScheduleId, t]);
- const displayTitle = getAutomationSessionDisplayTitle(session);
- const canHighlightDisplayTitle = !isScheduledSession(session);
+ const displayTitle = getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'));
+ const canHighlightDisplayTitle = canHighlightSessionDisplayTitle(session);
// F-PJ-10:archived 视图下的 session 走特殊视觉/菜单分支
// - 左侧 status icon 由 CircleDashed 换成 Archive
// - 右侧 ⋮ 菜单只显示 Rename + Unarchive(屏蔽 Pin/Delete/Archive 等无意义项)
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx
index a3b26e15e2..1939a547b4 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx
@@ -11,11 +11,11 @@
*
* 实现注意:草稿样式与普通 SessionItem 差异较大(italic + 灰色 + 不同 padding),
* 不复用 SessionItem 而是另起一份小行内组件。重命名/删除功能本期保持现有
- * SessionItem 在 New Maker 行的能力——草稿同样可走 SessionItem,只是套上"看起来像
+ * SessionItem 在未起名草稿行上的能力——草稿同样可走 SessionItem,只是套上"看起来像
* 未绑定"的视觉壳。这里的实现:直接复用 SessionItem,让交互一致;外层不再叠加
- * Draft 样式,因为 New Maker 的视觉与设计稿一致(普通 32px 行)。设计稿 italic
- * 的灰字仅用于纯文字提示态——本期所有 unclassified 都是真实 Session(包括 New
- * CCS 草稿),照普通行渲染即可,文字本身已是 "New Maker"。
+ * Draft 样式,因为未起名草稿的视觉与设计稿一致(普通 32px 行)。设计稿 italic
+ * 的灰字仅用于纯文字提示态——本期所有 unclassified 都是真实 Session(包括未起名
+ * 草稿),照普通行渲染即可,标题由 `lib/sessionDisplayTitle` 兜底成「未命名对话」。
*/
import { SessionEntryList } from '../SessionEntryList';
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx
index 33c1df5964..674b9ee701 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx
@@ -44,6 +44,7 @@ import {
} from '@/components/ui/dropdown-menu';
import type { AgentKind, Session } from '@/lib/ccAgent.types';
import { makerChatStore } from '@/lib/makerChatStore';
+import { getSessionDisplayTitle, toStoredSessionTitle } from '../lib/sessionDisplayTitle';
export interface SessionTabsBarProps {
/** 当前 URL :sessionId 指向的 session;null 表示无 active(极少出现)。 */
@@ -86,6 +87,7 @@ export function SessionTabsBar({
onRename,
}: SessionTabsBarProps) {
const { t } = useTranslation();
+ const unnamedLabel = t('ccAgent.common.unnamedSession');
// 订阅 running session map —— 与 sidebar SessionItem 同源(都来自
// makerChatStore),保证 doc 模式 tab 上的 vendor icon 呼吸态与项目侧
// session 行的呼吸完全同步出现/消失。多个订阅者 useSyncExternalStore
@@ -124,9 +126,17 @@ export function SessionTabsBar({
setRenamingId(null);
if (!id) return;
const trimmed = editValue.trim();
- const original = sessions.find((s) => s.id === id)?.title ?? '';
- if (trimmed && trimmed !== original) onRename(id, trimmed);
- }, [renamingId, editValue, sessions, onRename]);
+ const target = sessions.find((s) => s.id === id);
+ const original = target?.title ?? '';
+ // 显示标题也算「没改」(与 SessionContentHeader 同口径):未起名的会话 tab 上
+ // 预填的是本地化兜底文案,它不等于库里的英文哨兵 —— 只比原始 title 的话,
+ // 用户双击后原样回车会把兜底文案写进库、冲掉哨兵,自动起名从此跳过这个会话。
+ const displayed = target ? getSessionDisplayTitle(target, unnamedLabel) : '';
+ if (!trimmed || trimmed === original || trimmed === displayed) return;
+ // 预填是显示标题(legacy automation 会话已剥掉 `[Schedule] ` 前缀),落库前还原,
+ // 否则会话会从 automation 分组里消失(PR #1031 review P1)。
+ onRename(id, target ? toStoredSessionTitle(target, trimmed) : trimmed);
+ }, [renamingId, editValue, sessions, onRename, unnamedLabel]);
// 进编辑态后自动 focus + 全选 input。
useEffect(() => {
@@ -238,7 +248,7 @@ export function SessionTabsBar({
>
{sessions.map((session) => {
const sessionId = session.id;
- const title = session.title?.trim() || t('ccAgent.common.unnamedSession');
+ const title = getSessionDisplayTitle(session, unnamedLabel).trim() || unnamedLabel;
const vendor = session.agentKind;
const isActive = sessionId === activeSessionId;
const isRunning = runningMap.has(sessionId);
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx
index f0f6110240..4064c2e9d3 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx
@@ -5,7 +5,7 @@
* Layout matches the design稿 (skillhub Market sidebar pattern):
*
* ┌──────────────────────────────────┐
- * │ ← Back to Projects │ ← h-9 rounded-full (slot of New Maker)
+ * │ ← Back to Projects │ ← h-9 rounded-full (slot of New Chat)
* ├──────────────────────────────────┤
* │ <workdir name> [⇡⇣] [↻]│ ← collapse all / refresh
* ├──────────────────────────────────┤
@@ -633,7 +633,7 @@ export function WorkdirBrowseSidebar({
return (
<div className="flex h-full w-full min-h-0 flex-col">
- {/* Top slot — same geometry as the "New Maker" button (h-9 rounded-full,
+ {/* Top slot — same geometry as the "New Chat" button (h-9 rounded-full,
pt-4 pr-3 pb-3.5 pl-3 + gap-0.5). Matches skillhub MarketCell when
on /skillhub/market. */}
<div className="flex flex-col gap-0.5 pt-4 pr-3 pb-3.5 pl-3">
diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
index 899e477946..3d877fc0fe 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
@@ -27,6 +27,7 @@
*/
import { useSyncExternalStore } from 'react';
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
import type { DeviceLinkConnectionStatus, Session } from '@/lib/ccAgent.types';
/** 单台被控设备的内存分片。 */
@@ -127,8 +128,13 @@ function sameDeviceList(a: RemoteDeviceSummary[], b: RemoteDeviceSummary[]): boo
return true;
}
-/** 被控端建会话时的默认标题;权威标题仍等于它 = 还没起过名。 */
-const DEFAULT_REMOTE_SESSION_TITLE = 'New Maker';
+/**
+ * 被控端建会话时的默认标题;权威标题仍等于它 = 还没起过名。
+ *
+ * 复用跨端共享常量:这串要与**被控端**(可能是另一个版本的客户端)写进 DB 的默认值
+ * 逐字一致,不能本地化、也不能与 main 侧各写一份。
+ */
+const DEFAULT_REMOTE_SESSION_TITLE = DEFAULT_DRAFT_SESSION_TITLE;
/**
* fork 会话的占位标题前缀("[Fork] …" / "[Fork·已剥离] …",非 i18n 串)。
* 与被控端 `localDb/ipc/sessions.ts` 的 FORK_PLACEHOLDER_TITLE_PREFIX 同源;两边
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5311cd58d5..94bbf48cb4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -52,7 +52,7 @@
},
"agentIsland": {
"native": {
- "newConversationTitle": "New Maker",
+ "newConversationTitle": "New Chat",
"newConversationHint": "Start a new conversation",
"muteSound": "Mute Agent Island",
"enableSound": "Enable Agent Island sound",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index edae36ec00..f77fab7224 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -28,6 +28,7 @@ import {
normalizeWorkflowProgressEntries,
type WorkflowProgressEntry,
} from '@cindy/maker-shared/agent-task';
+import { normalizeAutoTitle } from '@cindy/maker-shared/session-title';
import type { MessageRole, Message, MessageAutomationOrigin } from '@/lib/ccAgent.types';
import type { AttachedFile, MentionedResource, SerializedAttachedFile } from '@/lib/fileTypes';
import type {
@@ -87,7 +88,11 @@ import {
import { setMirrorEffort, setMirrorFast } from '@/state/deviceLinkModelMirror';
import type { AgentKind } from '@/hooks/useAgentCapabilities';
import type { Effort } from '@/lib/userPreferences.types';
-import { emitPatch } from '@/lib/sessionsBus';
+import {
+ emitAutoTitlePreview,
+ emitAutoTitlePreviewCleared,
+ emitPatch,
+} from '@/lib/sessionsBus';
import { createLogger } from '@/lib/logger';
import { getUserPrompt } from '@/lib/userPromptStore';
import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';
@@ -6701,6 +6706,16 @@ function updateQueueItem(sessionId: string, clientId: string, newText: string):
*/
const autoNameSettled = new Set<string>();
+/**
+ * 每个会话最近一次起名尝试的轮次号(sessionId → attempt)。
+ *
+ * 用户在首次 `maker:auto-title` 返回前连着发两条文字时,两次都会通过 `autoNameSettled`
+ * 检查、各起一次尝试。若**较早**那次失败,它的撤回不能动预览 —— 更晚的尝试仍在飞,
+ * 预览还有主人,撤回会让标题白闪一次「未命名对话」(PR #1031 review P1)。
+ * 与 SessionMenuSheet 的 `renameSeqRef`、搜索框的 `requestSeqRef` 同款守卫。
+ */
+const autoNameAttempts = new Map<string, number>();
+
/** 纯附件消息合成占位标题时的类别兜底词(拿不到任何文件名时才用)。 */
function autoTitleFallbackLabels(): AutoTitleFallbackLabels {
return {
@@ -6729,8 +6744,8 @@ function scheduleAutoName(
agentKind: 'claude-code' | 'codex',
isUserText = true,
): void {
- // 与 main 的 normalizeAutoTitle 同一套规则,两端算出的占位串一致,回流时不跳变。
- const fallbackTitle = text.replace(/\s+/g, ' ').trim().slice(0, 40).trimEnd();
+ // 与 main 共用 normalizeAutoTitle,两端算出的占位串逐字一致,回流时不跳变。
+ const fallbackTitle = normalizeAutoTitle(text);
// 连描述都合成不出来(既无文字也无可命名附件):保留默认标题,留给下一条消息。
if (!fallbackTitle) return;
if (isRemoteSession(sessionId)) {
@@ -6740,20 +6755,79 @@ function scheduleAutoName(
return;
}
if (autoNameSettled.has(sessionId)) return;
+ // 本机会话的即时标题预览 —— 与上面远程分支的 setPendingTitlePreview 对称。
+ //
+ // 没有这一步,标题要等「IPC 往返 → main 读库 → 写占位 → 广播 sessions:patched」
+ // 整条链路走完才更新:用户明明已经按下回车,侧边栏 / 会话头却还显示着建会话时的
+ // 默认占位。main 随后写入的就是这里的 fallbackTitle(同一套 deriveAutoTitleSeed
+ // 素材 + 同一个 normalizeAutoTitle),所以回流时不跳变。
+ //
+ // 「标题是否仍是哨兵」的判定在 sessionsStore 的订阅处(它持有列表缓存);本函数
+ // 也被「补起名」路径调用(每条带文字的消息都来一次),无条件写会把用户手动改过的
+ // 名在 UI 上顶掉。走 bus 而不是直接 import sessionsStore:后者会把它的模块级
+ // 订阅副作用拉进所有 import 本模块的加载链。
+ //
+ // 单独 try:预览纯属锦上添花,它失败既不能打断下面的起名 IPC,更不能把异常抛回
+ // sendMessageCore 打断消息入队(与本函数其余副作用同一条契约)。
+ try {
+ emitAutoTitlePreview(sessionId, fallbackTitle);
+ } catch (err) {
+ log.warn('Failed to emit auto-title preview:', err);
+ }
+ // 一次起名尝试的**唯一**收尾:三种结束方式(正常 resolve / IPC reject / 同步抛错)
+ // 都走这里,判据只有一条 —— **main 没确认写入(`applied` 不为 true)就撤回预览**。
+ //
+ // reject 与同步抛错建模成「没有结果」,与 `{ applied: false }` 落在同一分支:
+ // `runSessionAutoTitle` 在「资格读失败 / 占位与智能标题两段都没写进去」时是
+ // **正常 resolve** 出 `applied: false` 的,只挂 `.catch` 会漏掉这一整类
+ // (PR #1031 review P1)。把收尾收敛成一个函数,是为了不再出现第四条漏掉的路径。
+ //
+ // `applied: false, done: true`(用户已手动改过名)同样撤回:DB 里是用户的标题,
+ // 叠加层不该继续盖着;store 那边的守卫会发现缓存里已不是这次预览而自动让位。
+ const attempt = (autoNameAttempts.get(sessionId) ?? 0) + 1;
+ autoNameAttempts.set(sessionId, attempt);
+ const settleAutoName = (result?: { applied?: boolean; done?: boolean }): void => {
+ if (result?.done) autoNameSettled.add(sessionId);
+ if (result?.applied) return;
+ // 更晚的尝试已经起飞 → 预览归它,本次失败不撤回(否则标题白闪一次兜底文案)。
+ if (autoNameAttempts.get(sessionId) !== attempt) return;
+ clearAutoTitlePreviewSafely(sessionId);
+ };
// 整条链路对发送主流程必须是无副作用的:起名失败(桥接缺失 / IPC 抛错)只记日志,
// 绝不能把异常抛回 sendMessageCore 打断消息入队。
try {
void window.electronAPI.maker
.autoTitle({ sessionId, text, agentKind, isUserText })
- .then((result) => {
- if (result?.done) autoNameSettled.add(sessionId);
- })
+ .then(settleAutoName)
.catch((err) => {
// 不登记 settled —— 下一条带文字的消息会重试。
log.warn('Failed to auto-name session:', err);
+ settleAutoName();
});
} catch (err) {
log.warn('Failed to invoke auto-title IPC:', err);
+ settleAutoName();
+ }
+}
+
+/**
+ * main 没确认写入 → 撤回上面那次乐观预览。
+ *
+ * 预览是「马上会有权威标题回流」的赌注,它的失效条件是权威标题落地。起名没写成时
+ * 那个条件永远不成立:叠加层会在每次全量刷新后继续顶着 DB 里的哨兵,会话永久显示一个
+ * **库里并不存在**的标题(重启后又变回「未命名对话」,同一会话两种标题)。宁可退回可
+ * 解释的兜底文案 —— 而且没登记 `autoNameSettled`,下一条带文字的消息会重试起名。
+ *
+ * 万一 IPC 是「写库成功、响应丢了」,撤回也不会造成错误状态:main 已经广播过
+ * `sessions:patched`,store 那边的迟到撤回守卫(比对缓存里是否仍是这次预览)会让位。
+ *
+ * 同上契约:撤回自身失败只记日志,绝不外抛打断发送主流程。
+ */
+function clearAutoTitlePreviewSafely(sessionId: string): void {
+ try {
+ emitAutoTitlePreviewCleared(sessionId);
+ } catch (err) {
+ log.warn('Failed to clear auto-title preview:', err);
}
}
@@ -8872,6 +8946,7 @@ export const makerChatStore = {
/** Exposed for tests only: 清空「已确认无需起名」缓存,隔离用例间状态。 */
__resetAutoNameStateForTest: (): void => {
autoNameSettled.clear();
+ autoNameAttempts.clear();
},
/** Exposed for tests only: 把 stream event 打进真实 store(驱动 getRunningSnapshot 等)。 */
__applyStreamEventForTest: (sessionId: string, event: CCAgentStreamEvent): void =>
diff --git a/apps/desktop/src/renderer/lib/sessionsBus.ts b/apps/desktop/src/renderer/lib/sessionsBus.ts
index dd761494e7..a772b2777d 100644
--- a/apps/desktop/src/renderer/lib/sessionsBus.ts
+++ b/apps/desktop/src/renderer/lib/sessionsBus.ts
@@ -11,19 +11,38 @@
* 都走这条:rename / pin / title 生成 / updatedAt
* 更新 / workingDir / model / effort / clearSession 等。
*
- * useCCSessions 通过 onRefresh / onPatch 订阅,是唯一的消费者。
+ * emitAutoTitlePreview(id, title)
+ * 自动起名的即时标题预览。与 emitPatch 的区别是它**带
+ * 条件**:只有标题仍是「尚未起名」哨兵时才生效,由持有
+ * 缓存的 sessionsStore 自己裁决(见其订阅处)。
+ *
+ * emitAutoTitlePreviewCleared(id)
+ * 起名彻底失败、权威标题不会再回流时撤回上面那次预览。
+ * 预览是「马上会有权威值」的赌注,赌输了必须还原。
+ *
+ * sessionsStore 通过 onRefresh / onPatch / onAutoTitlePreview /
+ * onAutoTitlePreviewCleared 订阅,是列表数据的权威
+ * 消费者;个别 UI 另有自己的局部订阅(如 CCAgentSidebarUpper 用 onPatch 做项目自动
+ * 展开),所以 emit 的副作用不止于 store 缓存。
*/
import type { Session } from '@/lib/ccAgent.types';
const REFRESH_EVENT = 'cc-sessions-refresh';
const PATCH_EVENT = 'cc-session-patch';
+const AUTO_TITLE_PREVIEW_EVENT = 'cc-session-auto-title-preview';
+const AUTO_TITLE_PREVIEW_CLEARED_EVENT = 'cc-session-auto-title-preview-cleared';
interface PatchDetail {
sessionId: string;
patch: Partial<Session>;
}
+interface AutoTitlePreviewDetail {
+ sessionId: string;
+ title: string;
+}
+
export function emitRefresh(): void {
window.dispatchEvent(new Event(REFRESH_EVENT));
}
@@ -35,6 +54,42 @@ export function emitPatch(sessionId: string, patch: Partial<Session>): void {
);
}
+/**
+ * 自动起名的即时标题预览:让侧边栏 / 会话头立刻显示用户刚写下的话,不等
+ * `maker:auto-title` 的 IPC 往返 + DB 广播回流。
+ *
+ * 刻意与 `emitPatch` 分开:这是**条件**更新 —— 只有标题仍是「尚未起名」的哨兵时才
+ * 该生效,否则会把用户手动改过的名在 UI 上顶掉。判定交给持有列表缓存的
+ * sessionsStore,发起方(makerChatStore)不必也不该去读会话行。
+ *
+ * 不写 DB:权威标题仍由 main 落库并经 sessions:patched 广播回来。
+ */
+export function emitAutoTitlePreview(sessionId: string, title: string): void {
+ if (!sessionId || !title) return;
+ window.dispatchEvent(
+ new CustomEvent<AutoTitlePreviewDetail>(AUTO_TITLE_PREVIEW_EVENT, {
+ detail: { sessionId, title },
+ }),
+ );
+}
+
+/**
+ * 撤回上一次的即时标题预览 —— 起名 IPC 失败、权威标题不会再回流时调用。
+ *
+ * 为什么必须有这条:预览是叠加层,它的失效条件是「权威标题落地」。起名彻底失败时那个
+ * 条件永远不成立,叠加层会在每次全量刷新后继续顶着 DB 里的哨兵,会话就永久显示一个
+ * **库里并不存在**的标题(重启后又变回「未命名对话」)。宁可退回可解释的兜底文案:
+ * 下一条带文字的消息会重试起名(`autoNameSettled` 未登记)。
+ */
+export function emitAutoTitlePreviewCleared(sessionId: string): void {
+ if (!sessionId) return;
+ window.dispatchEvent(
+ new CustomEvent<{ sessionId: string }>(AUTO_TITLE_PREVIEW_CLEARED_EVENT, {
+ detail: { sessionId },
+ }),
+ );
+}
+
export function onRefresh(handler: () => void): () => void {
window.addEventListener(REFRESH_EVENT, handler);
return () => window.removeEventListener(REFRESH_EVENT, handler);
@@ -51,3 +106,27 @@ export function onPatch(
window.addEventListener(PATCH_EVENT, wrapped);
return () => window.removeEventListener(PATCH_EVENT, wrapped);
}
+
+export function onAutoTitlePreview(
+ handler: (sessionId: string, title: string) => void,
+): () => void {
+ const wrapped = (ev: Event) => {
+ const detail = (ev as CustomEvent<AutoTitlePreviewDetail>).detail;
+ if (!detail || !detail.sessionId || !detail.title) return;
+ handler(detail.sessionId, detail.title);
+ };
+ window.addEventListener(AUTO_TITLE_PREVIEW_EVENT, wrapped);
+ return () => window.removeEventListener(AUTO_TITLE_PREVIEW_EVENT, wrapped);
+}
+
+export function onAutoTitlePreviewCleared(
+ handler: (sessionId: string) => void,
+): () => void {
+ const wrapped = (ev: Event) => {
+ const detail = (ev as CustomEvent<{ sessionId: string }>).detail;
+ if (!detail || !detail.sessionId) return;
+ handler(detail.sessionId);
+ };
+ window.addEventListener(AUTO_TITLE_PREVIEW_CLEARED_EVENT, wrapped);
+ return () => window.removeEventListener(AUTO_TITLE_PREVIEW_CLEARED_EVENT, wrapped);
+}
diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.ts
index b4ce61c6bc..b89165e94c 100644
--- a/apps/desktop/src/renderer/lib/sessionsStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts
@@ -45,7 +45,17 @@
import type { Session } from '@/lib/ccAgent.types';
import * as sessionService from '@/lib/sessionService';
import type { ListStatusFilter } from '@/lib/sessionService';
-import { onPatch, onRefresh } from '@/lib/sessionsBus';
+import {
+ DEFAULT_DRAFT_SESSION_TITLE,
+ isDefaultDraftSessionTitle,
+} from '@cindy/maker-shared/session-title';
+
+import {
+ onAutoTitlePreview,
+ onAutoTitlePreviewCleared,
+ onPatch,
+ onRefresh,
+} from '@/lib/sessionsBus';
// V1.7:取消 16 条上限,全量拉取由 Sidebar 中部滚动条承载。
// 后端硬上限 1000,覆盖几乎所有真实用户的 Session 总数。
@@ -96,6 +106,85 @@ function mergeSession(prev: Session, patch: Partial<Session>): Session {
return next;
}
+/**
+ * 自动起名的「即时标题预览」叠加层(sessionId → 预览标题)。
+ *
+ * 为什么必须是叠加层、而不是一次性 patchLocal:新建会话的 `sessions:created` push 会
+ * 触发 `forceRefreshAll`,那次重拉从 DB 拿回的行**仍带默认哨兵**(权威标题要等
+ * `maker:auto-title` 落库才有),会把只写进缓存的乐观标题冲掉 —— 表现为标题先显示
+ * 用户那句话、又退回「未命名对话」,直到 IPC 回来(PR #1031 review P1)。
+ *
+ * 语义与 device-link 远程侧的 `remoteProjectsStore.pendingTitlePreview` 对称:只在
+ * **权威标题仍是哨兵**时顶替显示,权威标题一到就自动让位并回收条目,不需要显式失效。
+ */
+const autoTitlePreviews = new Map<string, string>();
+
+/**
+ * 把预览叠加到「权威标题仍是哨兵」的行上;已经拿到权威标题的行顺手回收条目。
+ *
+ * 与 {@link applySessionSpendOverrides} 同构:都在 fetch 结果回填进缓存前跑一遍,
+ * 让本地 override 活过全量刷新。
+ *
+ * **前置条件**:传进来的 list 里只能有「DB 值」与「权威 override 重放的值」——
+ * 乐观值绝不能出现在这里,否则下面那条「非哨兵 → 回收」会把自己写上去的乐观值当成
+ * 权威标题、把叠加层误回收(PR #1031 review P1)。这条前置由「乐观写入走
+ * {@link applyOptimisticTitle}、不进 patchLocal」保证。
+ */
+function applyAutoTitlePreviews(list: Session[]): Session[] {
+ if (autoTitlePreviews.size === 0) return list;
+ let changed = false;
+ const next = list.map((session) => {
+ const preview = autoTitlePreviews.get(session.id);
+ if (!preview) return session;
+ // 权威标题已落地(不再是哨兵)→ 预览让位并回收,避免长期顶着真实标题。
+ if (!isDefaultDraftSessionTitle(session.title)) {
+ autoTitlePreviews.delete(session.id);
+ return session;
+ }
+ if (session.title === preview) return session;
+ changed = true;
+ return mergeSession(session, { title: preview });
+ });
+ return changed ? next : list;
+}
+
+/**
+ * 权威标题的「防旧快照」叠加层(sessionId → 标题 + 本地事件版本)。
+ *
+ * 与 {@link sessionSpendOverrides} 同一套机制、同一个理由:进行中的 `sessions:list`
+ * 请求发起于这次标题变更**之前**,它的快照里还是旧标题,回来会 `cache.set` 整桶覆盖,
+ * 把刚 patch 进去的权威标题冲掉。
+ *
+ * 典型时序(新建会话):`sessions:created` push → `forceRefreshAll()` 起飞(快照里是
+ * 哨兵)→ main 写完占位 → `sessions:patched` 落进缓存 → 那个更早的请求才回来,把哨兵
+ * 写回去,界面退到「未命名对话」直到下一次刷新。乐观预览叠加层此刻已按权威值到达的
+ * 规则回收,没人再替它顶回来(PR #1031 review P1)。
+ *
+ * 方向与 {@link autoTitlePreviews} 互补:那一层管「请求发起于乐观写入**之后**、DB 里还
+ * 没有值」,这一层管「请求发起于权威写入**之前**、快照里还是旧值」。
+ */
+interface SessionTitleOverride {
+ revision: number;
+ title: string;
+}
+
+const sessionTitleOverrides = new Map<string, SessionTitleOverride>();
+let sessionTitleRevision = 0;
+
+/** 仅重放请求启动后到达的标题事件,避免旧事件覆盖未来数据库刷新。 */
+function applySessionTitleOverrides(list: Session[], afterRevision: number): Session[] {
+ if (sessionTitleOverrides.size === 0) return list;
+ let changed = false;
+ const next = list.map((session) => {
+ const override = sessionTitleOverrides.get(session.id);
+ if (!override || override.revision <= afterRevision) return session;
+ if (override.title === session.title) return session;
+ changed = true;
+ return mergeSession(session, { title: override.title });
+ });
+ return changed ? next : list;
+}
+
/** 仅重放请求启动后到达的费用事件,避免旧事件覆盖未来数据库刷新。 */
function applySessionSpendOverrides(list: Session[], afterRevision: number): Session[] {
let changed = false;
@@ -119,12 +208,50 @@ function applySessionSpendOverrides(list: Session[], afterRevision: number): Ses
return changed ? next : list;
}
+/**
+ * **乐观标题的唯一写入口**:只把标题合并进各桶,什么簿记都不做。
+ *
+ * 与 `patchLocal`(权威写入口)刻意分开 —— 这是本 PR 反复栽的那个坑的结构性修法:
+ * 两者共用一个门时,缓存里的串就分不出「乐观值」还是「权威值」,于是
+ *
+ * - `patchLocal` 会给乐观值也登记 {@link sessionTitleOverrides},那层重放出来的乐观值
+ * 又被 {@link applyAutoTitlePreviews} 当成权威标题、把叠加层误回收,后一次仍返回
+ * 哨兵的刷新就再没人保护标题(PR #1031 review P1);
+ * - 反过来「权威值与乐观值同值」时也分不出来,失败撤回会把已落库的标题打回哨兵。
+ *
+ * 分门之后两层各自的判据都重新成立:override 里只有 main 说过的值,叠加层只对 DB 值
+ * 让位。也因此不再需要「先 patch 后登记」那种依赖调用顺序的写法。
+ */
+function applyOptimisticTitle(id: string, title: string): void {
+ let touched = false;
+ for (const [filter, list] of cache) {
+ const idx = list.findIndex((s) => s.id === id);
+ if (idx === -1) continue;
+ if (list[idx].title === title) continue;
+ cache.set(filter, [
+ ...list.slice(0, idx),
+ mergeSession(list[idx], { title }),
+ ...list.slice(idx + 1),
+ ]);
+ touched = true;
+ }
+ if (touched) notify();
+}
+
async function fetchFilter(filter: ListStatusFilter): Promise<Session[]> {
// chat-data-localization round-5:IPC 'all'/undefined 与 HTTP 旧默认行为
// 不一致,必须把 filter 原样透传,由 IPC handler 决定过滤语义。
const spendRevisionAtStart = sessionSpendRevision;
+ const titleRevisionAtStart = sessionTitleRevision;
const sessions = await sessionService.list(DEFAULT_LIMIT, filter);
- return applySessionSpendOverrides(sessions, spendRevisionAtStart);
+ // 顺序:先把「请求发起之后到达的权威标题」补回去,再叠乐观预览。反过来的话预览会先
+ // 盖在旧标题上、随后又被权威值挤掉,中间多一次跳变。
+ return applyAutoTitlePreviews(
+ applySessionTitleOverrides(
+ applySessionSpendOverrides(sessions, spendRevisionAtStart),
+ titleRevisionAtStart,
+ ),
+ );
}
export const sessionsStore = {
@@ -140,6 +267,22 @@ export const sessionsStore = {
return cache.get(filter) ?? null;
},
+ /**
+ * 跨桶按 id 取当前缓存行;未加载 / 不在任何桶里时返回 null。
+ *
+ * 只读快照,给"下笔前先看一眼当前值"的乐观更新用(例如自动起名的即时标题预览
+ * 要先确认标题仍是系统占位,别把用户手动改的名在 UI 上顶掉)。不触发拉取——
+ * 拿不到就不做乐观更新,交给权威广播回填。
+ */
+ findById(id: string): Session | null {
+ if (!id) return null;
+ for (const bucket of cache.values()) {
+ const hit = bucket.find((s) => s.id === id);
+ if (hit) return hit;
+ }
+ return null;
+ },
+
/**
* 确保指定桶已加载(命中即 noop,dedupe 并发请求)。
* 失败时 throw 原始错误,由调用方决定如何展示。
@@ -212,7 +355,36 @@ export const sessionsStore = {
*/
patchLocal(id: string, patch: Partial<Session>): void {
if (!id || !patch) return;
+ // 权威标题落地(main 写完占位 / 智能标题后经 sessions:patched 回流,或用户手动改名)
+ // → 无条件回收预览条目。留着它会在下一次全量刷新时把真实标题又顶掉。
+ //
+ // **包括「权威标题与预览逐字相同」的常见情形**(两端共用 normalizeAutoTitle,占位本来
+ // 就该一样)。曾经在这里放过 `preview !== patch.title` 的例外,结果是缓存里那个串到底
+ // 是「叠加上去的乐观值」还是「已落库的权威值」再也分不出来 —— 随后的失败撤回会把
+ // **已经落库**的标题打回哨兵、界面退到「未命名对话」并与 DB 不一致(PR #1031 review P1)。
+ // 语义上也该无条件回收:DB 已经有值,叠加层的唯一用途(盖住仍是哨兵的行)已经消失。
+ //
+ // 乐观预览不走这个门(见 {@link applyOptimisticTitle}),所以这里见到的标题一律是
+ // main 说过的权威值 —— 判据不必、也无法再去分辨来源。
+ //
+ // **不看值、只看「是不是权威写入」**:用户完全可以手动把标题改成字面量 "New Maker"
+ // (main 侧专门有 manuallyRenamed 记号处理这种同值改名),那也是一次权威写入。曾经
+ // 在这里排除过哨兵值,结果是那种改名之后预览还留着,下一次刷新先重放权威值、紧接着
+ // 又被陈旧预览盖回第一句话,用户的标题显示不出来(PR #1031 review P1)。
+ if (typeof patch.title === 'string') {
+ autoTitlePreviews.delete(id);
+ }
+ // 每一次**权威**标题写入(占位 / 智能标题回流、用户改名)都登记版本化 override:
+ // 发起于本次写入之前的 list 请求回来时,快照里还是旧标题,必须被这一层挡住,
+ // 否则整桶覆盖会把刚写进缓存的标题冲掉(见 sessionTitleOverrides 的说明)。
+ // 每次写入都登记 = 最新一次写入总是最高版本,先后顺序天然正确。
+ if (typeof patch.title === 'string') {
+ sessionTitleRevision += 1;
+ sessionTitleOverrides.set(id, { revision: sessionTitleRevision, title: patch.title });
+ }
if (patch.status === 'deleted') {
+ autoTitlePreviews.delete(id);
+ sessionTitleOverrides.delete(id);
sessionSpendOverrides.delete(id);
// 删除前发出的请求可能仍会返回包含该 session 的旧快照。先解除这些
// request 对桶的认领,再为对应桶发起替代请求,避免旧响应重新写回。
@@ -323,6 +495,8 @@ export const sessionsStore = {
cache.clear();
inflight.clear();
sessionSpendOverrides.clear();
+ autoTitlePreviews.clear();
+ sessionTitleOverrides.clear();
notify('reset');
},
};
@@ -337,6 +511,44 @@ if (typeof window !== 'undefined') {
void sessionsStore.forceRefreshAll();
});
+ // 自动起名的即时标题预览 —— 条件更新,判定放在这里是因为**本模块持有列表缓存**:
+ //
+ // - 标题仍是「尚未起名」哨兵 → 乐观写入,侧边栏 / 会话头 / tab 立刻显示用户刚写
+ // 的话,不必干等 `maker:auto-title` 的 IPC 往返 + DB 广播回流;
+ // - 已经起过名 / 用户手动改过名 / fork 与纯附件的合成占位 → 一律不动。能否覆写
+ // 那几类占位由 main 的归属表裁决,这里猜错会把用户的标题在 UI 上顶掉。
+ //
+ // 先记进 autoTitlePreviews 叠加层再 patch:光 patch 缓存会被随后的 forceRefreshAll
+ // (新建会话的 sessions:created push 触发)用仍带哨兵的 DB 快照冲掉。**登记不看当前
+ // 缓存**——桶未加载时 findById 拿不到行,但那之后的首次 fetch 同样需要叠加。
+ //
+ // 只改本地缓存、不写 DB:权威标题仍由 main 落库后经 sessions:patched 广播回来,
+ // 那个串与这里预览的是同一个(共用 normalizeAutoTitle),所以回流时不跳变。
+ onAutoTitlePreview((sessionId, title) => {
+ const current = sessionsStore.findById(sessionId);
+ // 已有权威标题(非哨兵)→ 连叠加层都不登记,免得之后顶掉它。
+ if (current && !isDefaultDraftSessionTitle(current.title)) return;
+ // 乐观写入走专门的门:不登记权威 override、不回收叠加层,顺序无所谓。
+ autoTitlePreviews.set(sessionId, title);
+ if (current) applyOptimisticTitle(sessionId, title);
+ });
+
+ // 起名彻底失败 → 撤回预览。叠加层的失效条件是「权威标题落地」,失败时那个条件永远
+ // 不成立,预览会在每次全量刷新后继续顶着 DB 里的哨兵,会话永久显示一个库里不存在的
+ // 标题(重启后又变回兜底文案)。见 sessionsBus.emitAutoTitlePreviewCleared。
+ onAutoTitlePreviewCleared((sessionId) => {
+ const preview = autoTitlePreviews.get(sessionId);
+ if (preview === undefined) return;
+ autoTitlePreviews.delete(sessionId);
+ // 只在缓存里那行仍显示着**这次**预览时才还原:权威标题已经回流(或用户手动改名)
+ // 时缓存里是别的串,迟到的撤回不许把它冲掉。
+ const current = sessionsStore.findById(sessionId);
+ if (current?.title !== preview) return;
+ // 撤回是**本地回滚**(把乐观值抹掉、露出 DB 里的哨兵),不是权威写入:同样走乐观门,
+ // 免得往 override 层里塞一个 main 从没说过的值。
+ applyOptimisticTitle(sessionId, DEFAULT_DRAFT_SESSION_TITLE);
+ });
+
window.electronAPI?.onUsageSessionSpendChanged?.(
({ sessionId, totalMoney, totalCostUsd }) => {
sessionsStore.patchLocal(sessionId, {
diff --git a/apps/desktop/src/shared/__tests__/conversationSearchTitle.test.ts b/apps/desktop/src/shared/__tests__/conversationSearchTitle.test.ts
new file mode 100644
index 0000000000..bc5cd1f1c2
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/conversationSearchTitle.test.ts
@@ -0,0 +1,35 @@
+/**
+ * conversationSearchTitle —— 会话搜索「匹配串 = 渲染串」的唯一出口。
+ *
+ * main 用它算 titleMatchIndices、renderer 用它渲染结果行,两端必须逐字一致,
+ * 否则未起名会话的高亮下标会落在别的字上。这里锁住那份契约。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+
+import { conversationSearchTitle } from '../conversationSearch';
+
+describe('conversationSearchTitle', () => {
+ it('哨兵标题换成调用方给的本地化文案', () => {
+ expect(conversationSearchTitle(DEFAULT_DRAFT_SESSION_TITLE, '未命名对话')).toBe('未命名对话');
+ });
+
+ it('普通标题原样返回(不受 label 影响)', () => {
+ expect(conversationSearchTitle('修 Orca 心跳', '未命名对话')).toBe('修 Orca 心跳');
+ });
+
+ it('没传 label(旧 renderer 构建)时退回原始标题,不静默变成空串', () => {
+ expect(conversationSearchTitle(DEFAULT_DRAFT_SESSION_TITLE)).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ expect(conversationSearchTitle(DEFAULT_DRAFT_SESSION_TITLE, null)).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ });
+
+ it('投影结果与哨兵长度无关:高亮下标按返回串算,两端调同一函数即对齐', () => {
+ const label = 'Untitled session';
+ const projected = conversationSearchTitle(DEFAULT_DRAFT_SESSION_TITLE, label);
+ expect(projected).toBe(label);
+ // 原始哨兵长度 9、label 长度 16 —— 若一端用原串一端用投影串,下标必然越界/错位。
+ expect(DEFAULT_DRAFT_SESSION_TITLE.length).not.toBe(projected.length);
+ });
+});
diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.ts
index 8877ade592..bef38a32a4 100644
--- a/apps/desktop/src/shared/agentIsland.ts
+++ b/apps/desktop/src/shared/agentIsland.ts
@@ -426,7 +426,7 @@ export interface AgentIslandStrings {
export const DEFAULT_AGENT_ISLAND_STRINGS: AgentIslandStrings = {
appName: BRAND_NAME,
- newConversationTitle: 'New Maker',
+ newConversationTitle: 'New Chat',
newConversationHint: 'Start a new conversation',
muteSound: 'Mute Agent Island',
enableSound: 'Enable Agent Island sound',
diff --git a/apps/desktop/src/shared/conversationSearch.ts b/apps/desktop/src/shared/conversationSearch.ts
index d39dc4785e..40e4836e4c 100644
--- a/apps/desktop/src/shared/conversationSearch.ts
+++ b/apps/desktop/src/shared/conversationSearch.ts
@@ -1,3 +1,5 @@
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
+
import type { SessionSource } from './sessionSource';
export type ConversationSearchAgentKind = 'cc' | 'codex';
@@ -24,6 +26,12 @@ export interface ConversationSearchRequest {
* the previous active-only / active+archived behavior.
*/
includeArchived?: boolean;
+ /**
+ * 「尚未起名」会话的显示文案(renderer 已解析的 i18n 值)。main 只拿它做标题匹配与
+ * 命中下标 —— 结果里的 `session.title` 始终是原始存储值,投影只发生在渲染那一刻。
+ * 不传则退回按原始哨兵匹配(旧 renderer 构建)。
+ */
+ unnamedLabel?: string;
}
export type ConversationSearchSortBy = 'relevance' | 'activityDesc' | 'activityAsc';
@@ -85,6 +93,20 @@ export interface ConversationSearchResultItem {
rankScore: number;
}
+/**
+ * 会话搜索里「参与匹配 / 被渲染」的标题串 —— **main 与 renderer 共用同一函数**。
+ *
+ * main 用它算 `titleMatchIndices`,renderer 用它渲染结果行;两端必须逐字得到同一个串,
+ * 否则高亮下标会画到别的字上。共用一个纯函数就是这个保证本身(同 `normalizeAutoTitle`
+ * 收敛掉两份复制实现的理由)。
+ *
+ * 注意投影只发生在「匹配 / 渲染」这一刻:`ConversationSearchSessionSummary.title` 仍是
+ * 原始存储值,不把某次请求时的 locale 固化进返回数据。
+ */
+export function conversationSearchTitle(title: string, unnamedLabel?: string | null): string {
+ return projectDraftSessionTitle(title, unnamedLabel);
+}
+
export interface ConversationSearchResponse {
query: string;
results: ConversationSearchResultItem[];
diff --git a/apps/mobile/app/automations/[deviceId].tsx b/apps/mobile/app/automations/[deviceId].tsx
index 82c0d6a18e..9d50d1d57f 100644
--- a/apps/mobile/app/automations/[deviceId].tsx
+++ b/apps/mobile/app/automations/[deviceId].tsx
@@ -55,6 +55,7 @@ import {
summarizeSchedule,
} from '@/scheduler/scheduleModel';
import { shouldRefreshRunsForSchedule } from '@cindy/maker-shared/schedule-events';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import {
applyMobileTemplateParams,
applyTemplateToMobileScheduleDraft,
@@ -1160,7 +1161,9 @@ function ScheduleFormCard({
<View style={styles.boundSessionOptions} testID="automations.form.boundSessionOptions">
{boundSessionOptions.map((session) => (
<MainWindowRowButton
- accessibilityLabel={t('devices.automations.form.boundSessionA11y', { name: session.title || session.id })}
+ accessibilityLabel={t('devices.automations.form.boundSessionA11y', {
+ name: projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle')) || session.id,
+ })}
accessibilityRole="radio"
accessibilityState={{ checked: session.id === boundSessionInputValue.trim() }}
disabled={busy}
@@ -1172,7 +1175,9 @@ function ScheduleFormCard({
>
<View style={styles.boundSessionOptionText}>
<Text style={styles.boundSessionTitle} numberOfLines={1}>
- {session.title || session.workingDir || session.id}
+ {/* 哨兵过投影:绑定会话选择器同样不能露出内部哨兵。 */}
+ {projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle'))
+ || session.workingDir || session.id}
</Text>
<Text style={styles.boundSessionMeta} numberOfLines={1}>
{formatSessionOptionMeta(session)}
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index dbe46cf49f..1884f0cca0 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -270,11 +270,13 @@ export default function DeviceDetailScreen() {
// 自动化任务作用域页无筛选 UI 且承诺"全部 N 次运行",statusFilter 固定 'all'
// (本页 statusFilter state 停留在初值 'active',若沿用会把归档 run 滤掉)。
statusFilter: automationScopeKey ? 'all' : statusFilter,
+ // 未起名会话的显示文案:共享层不兜中文串,由这里给已解析的 i18n 值。
+ unnamedLabel: t('session.menu.unnamedTitle'),
// 项目作用域精简页与完整设备详情页都折叠自动化组(HomeSessionRow / SessionRow 均支持组行
// 展开,与首页交互一致);自动化任务作用域页本身就是"某任务的全部运行",必须平铺不折叠。
groupAutomations: !automationScopeKey,
}),
- [automationScopeKey, groupMode, messagePreviewIndex, pendingInteractionIndex, scheduleIndex, searchQuery, sessions, statusFilter],
+ [automationScopeKey, groupMode, messagePreviewIndex, pendingInteractionIndex, scheduleIndex, searchQuery, sessions, statusFilter, t],
);
const listContext = useMemo(
() => buildRemoteSessionListContext({
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 4468e1e25f..505e0d6537 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -20,6 +20,7 @@ import {
} from 'react-native';
import { Text, TextInput } from '@/components/AppText';
import { DeviceLinkError, type DeviceView, type PresenceSnapshot } from '@cindy/device-link';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import {
Archive,
Check,
@@ -798,8 +799,10 @@ export default function HomeScreen() {
selectedDeviceId,
sessions: homeSessions,
statusFilter,
+ // 未起名会话的显示文案:共享层不兜中文串,由这里给已解析的 i18n 值。
+ unnamedLabel: t('session.menu.unnamedTitle'),
}),
- [deviceModels, liveActivityIndex, messagePreviewIndex, pendingInteractionIndex, scheduleIndex, selectedDeviceId, homeSessions, statusFilter],
+ [deviceModels, liveActivityIndex, messagePreviewIndex, pendingInteractionIndex, scheduleIndex, selectedDeviceId, homeSessions, statusFilter, t],
);
const sections = useMemo(
() => buildHomeSections(home, groupByProject, pinnedCollapsed),
@@ -1042,7 +1045,10 @@ export default function HomeScreen() {
if (!session) return;
if (action === 'delete') {
// 菜单不再展示会话标题(2026-07-07 产品反馈),删除确认在这里带上标题作上下文。
- const title = session.title?.trim() || t('devices.list.untitled');
+ // 哨兵先过投影,与列表行显示同一个串:否则确认框里写着 "New Maker",用户在列表上
+ // 看到的却是「未命名对话」,对不上自己要删的是哪条。
+ const title = projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle')).trim()
+ || t('devices.list.untitled');
Alert.alert(t('devices.list.alert.deleteTitle'), t('devices.list.alert.deleteMessage', { title }), [
{ style: 'cancel', text: t('devices.common.cancel') },
{ onPress: () => runSwipeAction(session, 'delete'), style: 'destructive', text: t('devices.common.delete') },
@@ -1051,7 +1057,9 @@ export default function HomeScreen() {
}
if (action === 'rename') {
pendingSheetActionRef.current = () => {
- setRenameSessionDraft(session.title ?? '');
+ // 预填也走投影:输入框里不能出现内部哨兵。用户不改直接确定时,
+ // confirmRenameSession 的「没改就不落库」判据会把它挡掉(见那里的注释)。
+ setRenameSessionDraft(projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle')));
setRenameSessionTarget(session);
};
return;
@@ -1075,7 +1083,10 @@ export default function HomeScreen() {
const title = renameSessionDraft.trim();
if (!target || !title) return;
setRenameSessionTarget(null);
+ // 「没改就不落库」要同时比原始标题**和**预填的投影值:未起名会话预填的是本地化兜底
+ // 文案,只比原始标题会把这个文案写进 DB,哨兵被毁 → 自动起名永久跳过该会话。
if (title === (target.title ?? '')) return;
+ if (title === projectDraftSessionTitle(target.title, t('session.menu.unnamedTitle'))) return;
void patchHomeSession(target, { title }).catch((err: unknown) => {
Alert.alert(t('devices.list.alert.renameFailed'), humanizeRemoteError(err));
});
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index a61c6bc4ce..d4a4a3b5bb 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -210,6 +210,7 @@ import {
import { QuoteCapsule } from '@/session/QuoteCapsule';
import { formatQuotesForSend } from '@cindy/maker-shared/chat-quotes';
import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { confirmFullAccessChange } from '@/session/fullAccessConfirmation';
import { confirmMobileSessionAgentSwitch } from '@/session/sessionAgentSwitchConfirmation';
import {
@@ -6587,7 +6588,10 @@ export default function SessionScreen() {
searchOpen={searchOpen}
title={isDeviceAccessRevoked
? t('session.screen.accessRevokedShort')
- : currentSession?.title || currentSession?.workingDir
+ // 哨兵先过投影再进兜底链:会话头是发出第一句话后停留最久的位置,
+ // 原样显示会把内部哨兵 "New Maker" 摆在标题栏上。
+ : projectDraftSessionTitle(currentSession?.title, t('session.menu.unnamedTitle'))
+ || currentSession?.workingDir
|| (connectionError ? t('session.screen.sessionNotSynced') : (deviceName || t('session.screen.conversationFallback')))}
/>
diff --git a/apps/mobile/src/__tests__/sessionMenu.test.ts b/apps/mobile/src/__tests__/sessionMenu.test.ts
index 8eab95bc2d..db3541976c 100644
--- a/apps/mobile/src/__tests__/sessionMenu.test.ts
+++ b/apps/mobile/src/__tests__/sessionMenu.test.ts
@@ -62,6 +62,12 @@ describe('sessionMenu header', () => {
expect(buildSessionMenuHeader(session({ title: '', workingDir: null }), {}).title).toBe('远程对话');
});
+ it('未起名会话显示本地化兜底,不回落工作目录名', () => {
+ // 哨兵若按「无标题」处理会回落 workspaceName 显示目录名,与 desktop 的
+ // 「未命名对话」不一致(PR #1031 review P1)。
+ expect(buildSessionMenuHeader(session({ title: 'New Maker' }), {}).title).toBe('未命名对话');
+ });
+
it('prefers the worktree name in the meta line', () => {
const header = buildSessionMenuHeader(session({
agentKind: 'codex',
diff --git a/apps/mobile/src/__tests__/sessionTitleProjection.test.ts b/apps/mobile/src/__tests__/sessionTitleProjection.test.ts
new file mode 100644
index 0000000000..d1ccc72b8e
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionTitleProjection.test.ts
@@ -0,0 +1,66 @@
+/**
+ * 手机端「未起名会话标题」投影的出口清单。
+ *
+ * 不变量:用户能看到的每个会话标题出口都必须过 projectDraftSessionTitle,内部哨兵
+ * `New Maker` 一处都不许原样渲染;而重命名输入框预填投影值后,**必须**有一条
+ * 「没改就不落库」的判据同时比原始标题与投影值 —— 否则用户双击后原样确定就会把兜底
+ * 文案写进 DB,哨兵被毁、自动起名永久跳过该会话(PR #1031)。
+ *
+ * 这些出口散在大型屏幕组件里(RN 组件在本仓没有渲染测试基座),用源码不变量钉住:
+ * 定位精确、不依赖 UI 基座,后续谁改动这几行都会在这里失败。
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const APP_ROOT = resolve(__dirname, '..', '..');
+
+function read(relPath: string): string {
+ return readFileSync(resolve(APP_ROOT, relPath), 'utf8');
+}
+
+const sessionScreen = read('app/sessions/[sessionId].tsx');
+const homeScreen = read('app/devices/index.tsx');
+const automationsScreen = read('app/automations/[deviceId].tsx');
+const menuSheet = read('src/session/SessionMenuSheet.tsx');
+
+describe('mobile 会话标题投影出口', () => {
+ it('会话页标题栏过投影', () => {
+ expect(sessionScreen).toContain(
+ "projectDraftSessionTitle(currentSession?.title, t('session.menu.unnamedTitle'))",
+ );
+ });
+
+ it('首页删除确认里的标题过投影', () => {
+ expect(homeScreen).toContain(
+ "projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle')).trim()",
+ );
+ });
+
+ it('自动化绑定会话选择器过投影', () => {
+ expect(automationsScreen).toContain(
+ "projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle'))",
+ );
+ });
+
+ it('两个重命名入口都用投影值预填', () => {
+ expect(homeScreen).toContain(
+ "setRenameSessionDraft(projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle')))",
+ );
+ expect(menuSheet).toContain(
+ "const renamePrefill = projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle'));",
+ );
+ // 预填一旦是投影值,输入框里就不能再出现原始哨兵。
+ expect(menuSheet).not.toContain("setTitleDraft(session.title ?? '')");
+ });
+
+ it('两个重命名入口的「没改就不落库」判据都覆盖投影值', () => {
+ // 只比原始标题 → 兜底文案被写进 DB,哨兵被毁。
+ expect(homeScreen).toContain(
+ "if (title === projectDraftSessionTitle(target.title, t('session.menu.unnamedTitle'))) return;",
+ );
+ expect(menuSheet).toContain('if (!next || next === session.title || next === renamePrefill) {');
+ });
+});
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index dc87c57058..429389c1f7 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -160,6 +160,7 @@
"chipArchived": "Archived",
"chipReadOnly": "Read-only",
"titleFallback": "Remote session",
+ "unnamedTitle": "Untitled session",
"renameAction": "Rename Chat",
"copyLinkAction": "Copy Chat Link",
"unpin": "Unpin",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 45f7a6b255..4cca49a5dc 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -160,6 +160,7 @@
"chipArchived": "アーカイブ済み",
"chipReadOnly": "読み取り専用",
"titleFallback": "リモートセッション",
+ "unnamedTitle": "名称未設定の会話",
"renameAction": "会話の名前を変更",
"copyLinkAction": "会話リンクをコピー",
"unpin": "ピン留めを解除",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 97b5f8be4f..00e1f95d2e 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -160,6 +160,7 @@
"chipArchived": "보관됨",
"chipReadOnly": "읽기 전용",
"titleFallback": "원격 세션",
+ "unnamedTitle": "이름 없는 대화",
"renameAction": "대화 이름 변경",
"copyLinkAction": "대화 링크 복사",
"unpin": "고정 해제",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 97a9009981..96f4abe93a 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -160,6 +160,7 @@
"chipArchived": "已归档",
"chipReadOnly": "只读",
"titleFallback": "远程对话",
+ "unnamedTitle": "未命名对话",
"renameAction": "重命名对话",
"copyLinkAction": "复制对话链接",
"unpin": "取消置顶",
diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsx
index 330d79ea4c..ce8672bdab 100644
--- a/apps/mobile/src/session/SessionMenuSheet.tsx
+++ b/apps/mobile/src/session/SessionMenuSheet.tsx
@@ -44,6 +44,7 @@ import { Text, TextInput } from '@/components/AppText';
import { MainWindowActionGroup } from '@/components/MobilePrimitives';
import type { RemoteDirectoryEntry } from '@/device-link/mobileMakerTransport';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';
import { writeClipboardText } from '@/session/messageActions';
import { normalizeExtraDirs } from '@/session/newSession';
@@ -169,7 +170,11 @@ export function SessionMenuSheet({
const [renaming, setRenaming] = useState(false);
const [renameGenerating, setRenameGenerating] = useState(false);
const [renameError, setRenameError] = useState<string | null>(null);
- const [titleDraft, setTitleDraft] = useState(session.title ?? '');
+ // 重命名输入框的预填值:哨兵先过投影,输入框里不能出现内部哨兵 "New Maker"
+ // (与桌面 SessionContentHeader 的预填同款)。用户不改直接确定时由 submitRename
+ // 的「没改就不落库」判据挡住,详见那里的注释。
+ const renamePrefill = projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle'));
+ const [titleDraft, setTitleDraft] = useState(renamePrefill);
const [copiedKey, setCopiedKey] = useState<string | null>(null);
const [extraDirsNotice, setExtraDirsNotice] = useState<string | null>(null);
// 编辑轮次号:提交 / 取消 / 关闭都会 +1,自动起名的迟到结果据此丢弃(手动操作优先,
@@ -216,11 +221,11 @@ export function SessionMenuSheet({
// 会话切换 / 远端改名后同步标题草稿,并退出编辑态。
useEffect(() => {
renameSeqRef.current += 1;
- setTitleDraft(session.title ?? '');
+ setTitleDraft(renamePrefill);
setRenaming(false);
setRenameGenerating(false);
setRenameError(null);
- }, [session.id, session.title]);
+ }, [session.id, renamePrefill]);
useEffect(() => () => {
if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
@@ -314,20 +319,22 @@ export function SessionMenuSheet({
setRenaming(false);
setRenameGenerating(false);
setRenameError(null);
- if (!next || next === session.title) {
- setTitleDraft(session.title ?? '');
+ // 「没改就不落库」要同时比原始标题**和**预填的投影值:未起名会话预填的是本地化
+ // 兜底文案,只比原始标题会把这个文案写进 DB,哨兵被毁 → 自动起名永久跳过该会话。
+ if (!next || next === session.title || next === renamePrefill) {
+ setTitleDraft(renamePrefill);
return;
}
onRename(next);
- }, [onRename, session.title, titleDraft]);
+ }, [onRename, renamePrefill, session.title, titleDraft]);
const cancelRename = useCallback(() => {
renameSeqRef.current += 1;
setRenaming(false);
setRenameGenerating(false);
setRenameError(null);
- setTitleDraft(session.title ?? '');
- }, [session.title]);
+ setTitleDraft(renamePrefill);
+ }, [renamePrefill]);
// 自动起名:生成结果只回填输入框,停留在编辑态等用户按「确定」提交(2026-07-06
// 产品确认,与桌面「生成即提交」刻意不同);生成期间用户手动提交 / 取消 →
@@ -374,7 +381,7 @@ export function SessionMenuSheet({
if (action.disabled) return;
switch (action.id) {
case 'rename':
- setTitleDraft(session.title ?? '');
+ setTitleDraft(renamePrefill);
setRenameError(null);
setRenaming(true);
return;
@@ -396,7 +403,7 @@ export function SessionMenuSheet({
default:
return;
}
- }, [confirmDelete, copyValue, onArchive, onClose, onRestore, onTogglePinned, session]);
+ }, [confirmDelete, copyValue, onArchive, onClose, onRestore, onTogglePinned, renamePrefill, session]);
const currentExtraDirs = normalizeExtraDirs(session.extraDirs ?? undefined);
const addExtraDir = useCallback((path: string) => {
diff --git a/apps/mobile/src/session/sessionMenu.ts b/apps/mobile/src/session/sessionMenu.ts
index d52c7363f7..dd1d475dc9 100644
--- a/apps/mobile/src/session/sessionMenu.ts
+++ b/apps/mobile/src/session/sessionMenu.ts
@@ -5,6 +5,8 @@
* 置顶 / 归档 / 删除)+「会话信息」二级入口;二级 = 用量 / 工作目录 / 附加引用目录 / 标识。
* 全部为纯函数,不碰 IO;交互副作用(clipboard / Alert / 远端写)由组件层承担。
*/
+import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';
+
import { i18n } from '@/i18n';
import { sessionCollaborationLabel } from '@/session/collaboration';
import { normalizeExtraDirs } from '@/session/newSession';
@@ -56,7 +58,12 @@ export function buildSessionMenuHeader(
if (collabLabel) chips.push({ id: 'collab', label: collabLabel });
return {
- title: session.title || workspaceName(session) || i18n.t('session.menu.titleFallback'),
+ // 哨兵(尚未起名)直接给本地化兜底,**不回落 workspaceName** —— 回落会把目录名当标题,
+ // 与 desktop 的「未命名对话」不一致(PR #1031 review P1)。文案走 i18n:本模块四语言
+ // 都在用 i18n.t,不能塞硬编码中文(mobile 支持 en / ja / ko)。
+ title: isDefaultDraftSessionTitle(session.title)
+ ? i18n.t('session.menu.unnamedTitle')
+ : session.title || workspaceName(session) || i18n.t('session.menu.titleFallback'),
chips,
metaLine: buildSessionMenuMetaLine(session),
usageSummary: buildSessionMenuUsageSummary(session),
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 2ad8e53d64..1d12c65d9d 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -15,6 +15,8 @@
* - 业务 token 管理、飞书业务态
*/
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+
import type { AgentKind } from './types/common.js';
import type { Capabilities } from './types/capabilities.js';
import type { ForkSdkSessionOptions, ForkSdkSessionResult } from './types/events.js';
@@ -314,7 +316,7 @@ export class Maker {
id,
agentKind: opts.agentKind,
workDir: opts.workingDir,
- title: opts.title ?? 'New Maker',
+ title: opts.title ?? DEFAULT_DRAFT_SESSION_TITLE,
model: opts.model,
workspaceKind: opts.workspaceKind,
effort: opts.effort,
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index 4a915f5f94..c7e7c196fa 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -51,6 +51,7 @@
"./session-list-collapse": "./src/sessionListCollapse.ts",
"./session-operation": "./src/sessionOperation.ts",
"./session-selection": "./src/sessionSelection.ts",
+ "./session-title": "./src/sessionTitle.ts",
"./synthetic-trigger": "./src/syntheticTrigger.ts",
"./system-card": "./src/systemCard.ts",
"./thinking-text": "./src/thinkingText.ts",
diff --git a/packages/maker-shared/src/__tests__/mobileHome.test.ts b/packages/maker-shared/src/__tests__/mobileHome.test.ts
index 8aa9eb548f..5169a5f48f 100644
--- a/packages/maker-shared/src/__tests__/mobileHome.test.ts
+++ b/packages/maker-shared/src/__tests__/mobileHome.test.ts
@@ -439,6 +439,27 @@ describe('mobileHome', () => {
expect(home.chats.map((item) => item.session.id)).toEqual(['chat-1']);
});
+ // 首页与设备详情页两条列表管线是对称的:任何一侧只改展示不改 haystack,
+ // 都会留下「搜得到的 ≠ 看得到的」(PR #1031 review P1)。
+ it('搜索按行上显示的标题匹配,内部哨兵不进 haystack', () => {
+ const sessions = [
+ session('s-sentinel', { title: 'New Maker', workspaceKind: 'dialogue', workingDir: null }),
+ session('s-named', { title: 'Fix New Maker draft route', workspaceKind: 'dialogue', workingDir: null }),
+ ];
+
+ expect(buildMobileHomePresentation({
+ searchQuery: 'Untitled',
+ sessions,
+ unnamedLabel: 'Untitled session',
+ }).chats.map((item) => item.session.id)).toEqual(['s-sentinel']);
+
+ expect(buildMobileHomePresentation({
+ searchQuery: 'new maker',
+ sessions,
+ unnamedLabel: 'Untitled session',
+ }).chats.map((item) => item.session.id)).toEqual(['s-named']);
+ });
+
it('collapses runs of the same schedule into one automation group row inside the project', () => {
const scheduleInfo = (latestRunAt: number, running = false) => ({
scheduleId: 'sched-1',
diff --git a/packages/maker-shared/src/__tests__/sessionList.test.ts b/packages/maker-shared/src/__tests__/sessionList.test.ts
index 9cd739708f..9dbea3b956 100644
--- a/packages/maker-shared/src/__tests__/sessionList.test.ts
+++ b/packages/maker-shared/src/__tests__/sessionList.test.ts
@@ -108,6 +108,87 @@ describe('sessionList', () => {
expect(sections[0].data[0].worktreeLabel).toBe('Worktree serene-lovelace');
});
+ it('未起名会话用调用方给的本地化文案,不回落工作目录路径', () => {
+ // 哨兵若按「无标题」处理,会回落 workingDir 把完整路径当标题显示,与 desktop 的
+ // 「未命名对话」不一致(PR #1031 review P1)。文案由调用方按当前 locale 传入 ——
+ // 共享层不能兜中文串,mobile 还支持 en / ja / ko。
+ const now = new Date('2026-01-01T00:10:00.000Z').getTime();
+ const sentinel = session('s-sentinel', {
+ title: 'New Maker',
+ workingDir: '/Users/dash/Code/Cindy/cindy',
+ });
+
+ expect(
+ toRemoteSessionListItem(sentinel, now, undefined, 0, null, null, '未命名对话').title,
+ ).toBe('未命名对话');
+ // 同一条会话换 locale → 换文案(锁住「不在共享层写死中文」)。
+ expect(
+ toRemoteSessionListItem(sentinel, now, undefined, 0, null, null, 'Untitled session').title,
+ ).toBe('Untitled session');
+ // 调用方没给文案时回落既有链(workingDir),而不是悄悄显示中文。
+ expect(toRemoteSessionListItem(sentinel, now).title).toBe('/Users/dash/Code/Cindy/cindy');
+
+ // 空标题(非哨兵)不受影响,仍走既有兜底链。
+ const emptyTitle = toRemoteSessionListItem(
+ session('s-empty', { title: '', workingDir: '/Users/dash/Code/Cindy/cindy' }),
+ now,
+ undefined,
+ 0,
+ null,
+ null,
+ '未命名对话',
+ );
+ expect(emptyTitle.title).toBe('/Users/dash/Code/Cindy/cindy');
+ });
+
+ it('buildRemoteSessionSections 把 unnamedLabel 透传到列表行', () => {
+ // 设备详情页与首页都经 options 传 locale 文案;漏传就会在 en/ja/ko 下露出中文或路径。
+ const [section] = buildRemoteSessionSections(
+ [session('s-sentinel', { title: 'New Maker', workingDir: '/repo' })],
+ new Date('2026-01-01T00:10:00.000Z').getTime(),
+ { unnamedLabel: 'Untitled session' },
+ );
+ expect(section.data[0].title).toBe('Untitled session');
+ });
+
+ // 搜索 haystack 与行上显示的串必须同源(PR #1031 review P1)。两条断言方向相反,
+ // 缺哪一条都会留下一半的错位:只补 label 会让内部哨兵继续可搜,只删哨兵会让
+ // 界面上看得见的文案搜不到。
+ it('未起名会话能按行上显示的兜底文案搜到', () => {
+ const sections = buildRemoteSessionSections(
+ [
+ session('s-sentinel', { title: 'New Maker', workingDir: '/repo' }),
+ session('s-named', { title: '修 Orca 心跳', workingDir: '/other' }),
+ ],
+ new Date('2026-01-01T00:10:00.000Z').getTime(),
+ { searchQuery: 'Untitled', unnamedLabel: 'Untitled session' },
+ );
+ expect(sections.flatMap((s) => s.data).map((item) => item.session.id)).toEqual(['s-sentinel']);
+ });
+
+ it('内部哨兵不进 haystack:搜 "New Maker" 只命中标题里真有这个词的会话', () => {
+ const sections = buildRemoteSessionSections(
+ [
+ session('s-sentinel', { title: 'New Maker', workingDir: '/repo' }),
+ session('s-named', { title: 'Fix New Maker draft route', workingDir: '/other' }),
+ ],
+ new Date('2026-01-01T00:10:00.000Z').getTime(),
+ { searchQuery: 'new maker', unnamedLabel: 'Untitled session' },
+ );
+ expect(sections.flatMap((s) => s.data).map((item) => item.session.id)).toEqual(['s-named']);
+ });
+
+ it('automation 会话按剥掉前缀后的可见标题可搜', () => {
+ // 投影替掉的是原始 title 那一项;`[Schedule] ` 前缀本来就不显示,剥掉后的串
+ // 由 haystack 里的 automationDisplayTitle 继续覆盖。
+ const sections = buildRemoteSessionSections(
+ [session('s-auto', { title: '[Schedule] 每日巡检', workingDir: '/repo' })],
+ new Date('2026-01-01T00:10:00.000Z').getTime(),
+ { searchQuery: '每日巡检', unnamedLabel: 'Untitled session' },
+ );
+ expect(sections.flatMap((s) => s.data).map((item) => item.session.id)).toEqual(['s-auto']);
+ });
+
it('builds compact display metadata for a session row', () => {
const item = toRemoteSessionListItem(session('s1', {
title: '',
diff --git a/packages/maker-shared/src/__tests__/sessionTitle.test.ts b/packages/maker-shared/src/__tests__/sessionTitle.test.ts
new file mode 100644
index 0000000000..7b439678f6
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/sessionTitle.test.ts
@@ -0,0 +1,85 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ DEFAULT_DRAFT_SESSION_TITLE,
+ isDefaultDraftSessionTitle,
+ normalizeAutoTitle,
+ projectDraftSessionTitle,
+} from '../sessionTitle.js';
+
+describe('normalizeAutoTitle', () => {
+ it('折叠空白 → trim → 截断 40 字(先 trim 再截断)', () => {
+ expect(normalizeAutoTitle(' 帮我\n排查 登录失败 ')).toBe('帮我 排查 登录失败');
+ expect(normalizeAutoTitle(`\n${' '.repeat(50)}real text`)).toBe('real text');
+ expect(normalizeAutoTitle('排'.repeat(60))).toBe('排'.repeat(40));
+ expect(normalizeAutoTitle(' ')).toBe('');
+ });
+
+ it('幂等:对已归一化的串再跑一次结果不变', () => {
+ // renderer 的乐观预览与 main 的权威占位都跑这个函数,两次结果必须逐字一致 ——
+ // 否则回流时侧边栏标题会跳变一次。
+ const once = normalizeAutoTitle(' 帮我\n排查 登录失败 ');
+ expect(normalizeAutoTitle(once)).toBe(once);
+ });
+
+ it('先 trim 的串与原串算出同一个结果', () => {
+ // 权威路径会先经 projectLiteralUserText / stripMentionTokens(两者都只 trim),
+ // 乐观预览直接拿原文;两条输入必须收敛到同一个标题。
+ const raw = ' 帮我排查登录失败 ';
+ expect(normalizeAutoTitle(raw.trim())).toBe(normalizeAutoTitle(raw));
+ });
+});
+
+describe('isDefaultDraftSessionTitle', () => {
+ it('只认建会话时的裸默认哨兵', () => {
+ expect(isDefaultDraftSessionTitle(DEFAULT_DRAFT_SESSION_TITLE)).toBe(true);
+ expect(isDefaultDraftSessionTitle('帮我排查登录失败')).toBe(false);
+ expect(isDefaultDraftSessionTitle('')).toBe(false);
+ expect(isDefaultDraftSessionTitle(null)).toBe(false);
+ expect(isDefaultDraftSessionTitle(undefined)).toBe(false);
+ });
+
+ it('不做大小写 / 空白归一 —— 用户改成近似串是合法自定义标题', () => {
+ // 归一化比较会把用户手动改的名误判成系统占位,进而被自动起名覆盖掉。
+ expect(isDefaultDraftSessionTitle('new maker')).toBe(false);
+ expect(isDefaultDraftSessionTitle('NEW MAKER')).toBe(false);
+ expect(isDefaultDraftSessionTitle(' New Maker ')).toBe(false);
+ });
+
+ it('哨兵值保持 locale-independent 字面量', () => {
+ // 它是 SQLite 列默认值,又要跨设备 / 跨语言逐字比对,还是条件写的期望值。
+ // 本地化会让哨兵匹配失效、自动起名永久跳过。
+ expect(DEFAULT_DRAFT_SESSION_TITLE).toBe('New Maker');
+ });
+});
+
+describe('projectDraftSessionTitle', () => {
+ it('哨兵 + 已解析文案 → 换成那个文案', () => {
+ expect(projectDraftSessionTitle(DEFAULT_DRAFT_SESSION_TITLE, '未命名对话')).toBe('未命名对话');
+ expect(projectDraftSessionTitle(DEFAULT_DRAFT_SESSION_TITLE, 'Untitled session')).toBe('Untitled session');
+ });
+
+ it('非哨兵标题原样返回,不被 label 顶掉', () => {
+ expect(projectDraftSessionTitle('修 Orca 心跳', '未命名对话')).toBe('修 Orca 心跳');
+ // 用户手动改成近似串仍是合法自定义标题(判据不做归一,见上)。
+ expect(projectDraftSessionTitle('new maker', '未命名对话')).toBe('new maker');
+ });
+
+ it('没给 label 时退回原串,由调用方自己接兜底链', () => {
+ // 共享层刻意不兜任何具体文案:写死中文会让 en / ja / ko 端悄悄显示中文。
+ expect(projectDraftSessionTitle(DEFAULT_DRAFT_SESSION_TITLE, undefined)).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ expect(projectDraftSessionTitle(DEFAULT_DRAFT_SESSION_TITLE, '')).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ });
+
+ it('空标题归一成空串,方便调用方直接接 `||` 兜底', () => {
+ expect(projectDraftSessionTitle(null, '未命名对话')).toBe('');
+ expect(projectDraftSessionTitle(undefined, '未命名对话')).toBe('');
+ expect(projectDraftSessionTitle('', '未命名对话')).toBe('');
+ });
+
+ it('幂等:对投影结果再投影一次不变', () => {
+ // 渲染与搜索 haystack 各自调一次,两次都必须收敛到同一个串。
+ const once = projectDraftSessionTitle(DEFAULT_DRAFT_SESSION_TITLE, '未命名对话');
+ expect(projectDraftSessionTitle(once, '未命名对话')).toBe(once);
+ });
+});
diff --git a/packages/maker-shared/src/mobileHome.ts b/packages/maker-shared/src/mobileHome.ts
index aa337c8e44..9beb2b9763 100644
--- a/packages/maker-shared/src/mobileHome.ts
+++ b/packages/maker-shared/src/mobileHome.ts
@@ -1,5 +1,6 @@
import {
groupAutomationListItems,
+ remoteSessionDisplayTitle,
sessionRowMessagePreview,
toRemoteSessionListItem,
type RemoteSessionLiveActivity,
@@ -116,6 +117,11 @@ export interface MobileHomeOptions {
selectedDeviceId?: string | null;
sessions: readonly MobileHomeSessionLike[];
statusFilter?: RemoteSessionStatusFilter;
+ /**
+ * 「尚未起名」会话的显示文案(已解析的 i18n 值)。不传则回落 workingDir → 「未命名会话」;
+ * 共享层刻意不兜中文串,见 sessionList 的 remoteSessionDisplayTitle。
+ */
+ unnamedLabel?: string;
}
export function buildMobileHomePresentation({
@@ -129,6 +135,7 @@ export function buildMobileHomePresentation({
selectedDeviceId = null,
sessions,
statusFilter = 'active',
+ unnamedLabel,
}: MobileHomeOptions): MobileHomePresentation {
// 设备身份归一化在管线源头对每个会话算出 canonicalDeviceId(写入字段,不改 deviceLinkDeviceId):
// 后续设备筛选统计、matchesSelectedDevice 过滤、项目分组、概览、卡片 deviceId 全部按 canonicalDeviceId
@@ -152,6 +159,7 @@ export function buildMobileHomePresentation({
liveActivityIndex,
pendingInteractionIndex,
scheduleIndex,
+ unnamedLabel,
))
.sort(compareSessionsByStatusThenActivityDesc);
const items = filteredSessions.map((session) => toRemoteSessionListItem(
@@ -163,6 +171,7 @@ export function buildMobileHomePresentation({
// (sessionRowMessagePreview 读取),与 buildRemoteSessionSections 同一套兜底。
messagePreviewIndex?.get(session.id) ?? sessionRowMessagePreview(session),
liveActivityIndex?.get(session.id) ?? null,
+ unnamedLabel,
));
const pinned = items.filter((item) => !!item.session.pinnedAt);
const rest = items.filter((item) => !item.session.pinnedAt);
@@ -503,11 +512,15 @@ function matchesSearchQuery(
liveActivityIndex: ReadonlyMap<string, RemoteSessionLiveActivity> | undefined,
pendingInteractionIndex: ReadonlyMap<string, number> | undefined,
scheduleIndex: ReadonlyMap<string, RemoteSessionScheduleInfo> | undefined,
+ unnamedLabel: string | undefined,
): boolean {
if (!query) return true;
const scheduleInfo = scheduleIndex?.get(session.id) ?? fallbackScheduleInfo(session);
const haystack = [
- session.title,
+ // 与首页行展示同源到函数级(同 sessionList 的 matchesSearchQuery):行上显示的就是
+ // remoteSessionDisplayTitle 的结果,haystack 直接调同一个函数。放原始哨兵会让
+ // 「搜得到的」与「看得到的」错位 —— 两个方向都错(见 sessionList 那条注释)。
+ remoteSessionDisplayTitle(session, unnamedLabel),
session.workingDir,
session.model,
session.agentKind,
diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.ts
index 6eec6e5ed2..93c00d4693 100644
--- a/packages/maker-shared/src/sessionList.ts
+++ b/packages/maker-shared/src/sessionList.ts
@@ -4,6 +4,7 @@ import { isSyntheticTriggerText } from './syntheticTrigger.js';
import type { RemoteSchedule, RemoteScheduleRun, RemoteScheduleRunStatus } from './scheduleTypes.js';
import { toMillis } from './scheduleModel.js';
import { sessionCollaborationLabel, sessionWorktreeLabel } from './sessionIdentity.js';
+import { isDefaultDraftSessionTitle } from './sessionTitle.js';
import { getSessionListCollapseView } from './sessionListCollapse.js';
import { collapseWorktreeDirForGrouping } from './worktreePaths.js';
@@ -157,6 +158,11 @@ export interface RemoteSessionListOptions {
* 折叠会让被计入「查看全部 N 条」的其余 run 无法点开,故那里传 false 让每个 run 各自成行。
*/
groupAutomations?: boolean;
+ /**
+ * 「尚未起名」会话的显示文案(已解析的 i18n 值)。不传则回落 workingDir → 「未命名会话」;
+ * 共享层刻意不兜中文串,见 {@link remoteSessionDisplayTitle}。
+ */
+ unnamedLabel?: string;
}
export function buildRemoteSessionSections(
@@ -175,6 +181,7 @@ export function buildRemoteSessionSections(
liveActivityIndex: options.liveActivityIndex,
pendingInteractionIndex: options.pendingInteractionIndex,
scheduleIndex: options.scheduleIndex,
+ unnamedLabel: options.unnamedLabel,
}))
.sort(compareSessions)
.map((session) => toRemoteSessionListItem(
@@ -184,6 +191,7 @@ export function buildRemoteSessionSections(
options.pendingInteractionIndex?.get(session.id) ?? 0,
options.messagePreviewIndex?.get(session.id) ?? sessionRowMessagePreview(session),
options.liveActivityIndex?.get(session.id) ?? null,
+ options.unnamedLabel,
));
const pinned = items.filter((item) => !!item.session.pinnedAt);
@@ -414,6 +422,31 @@ function buildDateSections(
.filter((section) => section.data.length > 0);
}
+/**
+ * 远程会话在列表 / 菜单上应显示的标题。
+ *
+ * 「尚未起名」的哨兵**直接用调用方给的本地化兜底、不回落 workingDir**:回落会把完整
+ * 工作目录路径当标题显示,与 desktop 侧的「未命名对话」不一致(PR #1031 review P1)。
+ * 哨兵本身是 locale-independent 的英文字面量(见 ./sessionTitle.ts),原样显示会露出
+ * "New Maker"。
+ *
+ * `unnamedLabel` 由调用方传入已解析的 i18n 文案(mobile 支持 en / ja / ko,本模块不能
+ * 导出中文 UI 串),与 desktop 的 `getSessionDisplayTitle(session, unnamedLabel)` 同款
+ * 签名。
+ *
+ * 空标题(非哨兵)保持既有兜底链 workingDir → 「未命名会话」不变。
+ */
+export function remoteSessionDisplayTitle(session: RemoteSession, unnamedLabel?: string): string {
+ if (isDefaultDraftSessionTitle(session.title)) {
+ // 调用方给了**已解析的 i18n 文案**就用它;没给则按「无标题」走既有兜底链
+ // (workingDir → '未命名会话'),即本 PR 之前的行为 —— 但无论如何都不把英文哨兵
+ // 原样显示出去。刻意不在共享层兜一个中文串:mobile 支持 en / ja / ko,那会让未接
+ // i18n 的调用方悄悄显示中文(PR #1031 review P1)。
+ return unnamedLabel || session.workingDir || '未命名会话';
+ }
+ return automationDisplayTitle(session) || session.workingDir || '未命名会话';
+}
+
export function toRemoteSessionListItem(
session: RemoteSession,
now = Date.now(),
@@ -421,13 +454,15 @@ export function toRemoteSessionListItem(
pendingInteractionCount = 0,
messagePreview: string | null = null,
liveActivity: RemoteSessionLiveActivity | null = null,
+ /** 「尚未起名」会话的显示文案,由调用方传已解析的 i18n 值(见 remoteSessionDisplayTitle)。 */
+ unnamedLabel?: string,
): RemoteSessionListItem {
const lastActivityAt = session.userSendAt ?? session.updatedAt ?? session.createdAt;
const scheduleInfo = scheduleIndex?.get(session.id) ?? fallbackScheduleInfo(session);
const worktreeLabel = sessionWorktreeLabel(session);
return {
session,
- title: automationDisplayTitle(session) || session.workingDir || '未命名会话',
+ title: remoteSessionDisplayTitle(session, unnamedLabel),
subtitle: [
sessionCollaborationLabel(session),
worktreeLabel,
@@ -655,12 +690,18 @@ function matchesSearchQuery(
liveActivityIndex?: ReadonlyMap<string, RemoteSessionLiveActivity>;
pendingInteractionIndex?: ReadonlyMap<string, number>;
scheduleIndex?: ReadonlyMap<string, RemoteSessionScheduleInfo>;
+ unnamedLabel?: string;
} = {},
): boolean {
if (!query) return true;
const scheduleInfo = options.scheduleIndex?.get(session.id) ?? fallbackScheduleInfo(session);
const haystack = [
- session.title,
+ // 与列表展示**同源到函数级**:行上显示的就是 remoteSessionDisplayTitle 的结果
+ // (见 toRemoteSessionListItem),haystack 直接调同一个函数。放原始 title 会两头错位
+ // —— 搜界面上看得见的兜底文案一条都搜不到,搜内部哨兵 "New Maker" 反而命中一堆
+ // 不显示这个词的行(PR #1031 review P1)。副作用:`[Schedule] ` 这个**不显示**的
+ // 内部前缀不再可搜,自动化任务名另有 scheduleInfo.scheduleName 那条覆盖。
+ remoteSessionDisplayTitle(session, options.unnamedLabel),
session.workingDir,
session.model,
session.agentKind,
@@ -669,7 +710,8 @@ function matchesSearchQuery(
session.worktreePath,
sessionWorktreeLabel(session),
scheduleInfo?.scheduleName,
- automationDisplayTitle(session),
+ // automationDisplayTitle 不单列:非自动化会话它就等于原始 title(哨兵会从这条漏回
+ // haystack),自动化会话的剥前缀标题已由上面的 remoteSessionDisplayTitle 覆盖。
sessionCollaborationLabel(session),
(options.pendingInteractionIndex?.get(session.id) ?? 0) > 0 ? '等待处理 waiting attention pending' : null,
sessionRowMessagePreview(session),
diff --git a/packages/maker-shared/src/sessionTitle.ts b/packages/maker-shared/src/sessionTitle.ts
new file mode 100644
index 0000000000..85742fb1a2
--- /dev/null
+++ b/packages/maker-shared/src/sessionTitle.ts
@@ -0,0 +1,63 @@
+/**
+ * sessionTitle —— 会话标题占位与哨兵的**跨端单一来源**。
+ *
+ * 为什么必须共享:自动起名分两步落库(先用用户原话截断写占位,再用模型生成的智能
+ * 标题覆盖),而 renderer 在建会话那一刻还会先做一次乐观预览、main 随后才写权威
+ * 值。两侧算出的串必须**逐字相同**,否则侧边栏会在「预览」与「回流」之间跳变一
+ * 次。此前 main 与 renderer 各持一份复制实现、只靠注释约束一致;新增第三个使用
+ * 点(乐观预览)之前先收敛到这里。
+ */
+
+/**
+ * 建会话时的默认标题,同时充当「尚未起名」的哨兵值。
+ *
+ * **刻意保持英文字面量、不做 i18n**:它既是 SQLite 列默认值,又要跨设备
+ * (device-link 控制端读被控端标题)、跨语言(用户随时切 locale)做逐字比对,还是
+ * 条件写 `WHERE title = 期望值` 里的期望值。把它本地化会让哨兵匹配失效、自动起名
+ * 永久跳过 —— 标题会永远钉死在占位上。
+ *
+ * 面向用户的显示层另有本地化兜底(见各端的 display title 推导),**不要**把这个
+ * 常量直接拿去显示。
+ */
+export const DEFAULT_DRAFT_SESSION_TITLE = 'New Maker';
+
+/**
+ * 自动标题的统一归一化:折叠空白 → trim → 截断 40 字。先 trim 再截断,避免前导
+ * 大量空白吃满长度后得到空标题。
+ *
+ * 落库出口、占位覆写方与 renderer 的乐观预览都用它算出同一个串。
+ */
+export function normalizeAutoTitle(text: string): string {
+ return text.replace(/\s+/g, ' ').trim().slice(0, 40).trimEnd();
+}
+
+/**
+ * 标题是否仍是建会话时的裸默认哨兵 —— 即「既没被自动起名、也没被用户改名」。
+ *
+ * 精确比较,不做大小写归一:用户手动把标题改成 `new maker` 是一个合法的自定义
+ * 标题,不该被当成系统占位覆盖掉。
+ */
+export function isDefaultDraftSessionTitle(title: string | null | undefined): boolean {
+ return title === DEFAULT_DRAFT_SESSION_TITLE;
+}
+
+/**
+ * 哨兵 → 兜底文案的**最小投影**:所有「渲染 / 搜索匹配 / 重命名预填」路径共用的
+ * 唯一判据出口。
+ *
+ * 只做一件事:标题是哨兵且调用方给了已解析的 i18n 文案时换成那个文案,其余原样返回
+ * (`null` / `undefined` 归一成空串,由调用方自己接后续兜底链,例如 workingDir)。
+ * 刻意不在这里兜任何具体文案:共享层不知道调用方的 locale,写死中文串会让 en / ja /
+ * ko 端悄悄显示中文(PR #1031 review P1)。
+ *
+ * 为什么必须共享:同一条会话的「显示串」被三类路径消费 —— 渲染、搜索 haystack /
+ * 命中下标、重命名输入框预填。任何一处用原始 `title`、另一处用投影值,就会错位:
+ * 搜界面上看得见的文案搜不到、搜不可见的内部哨兵反而命中,或者高亮画到别的字上。
+ */
+export function projectDraftSessionTitle(
+ title: string | null | undefined,
+ unnamedLabel: string | null | undefined,
+): string {
+ if (isDefaultDraftSessionTitle(title) && unnamedLabel) return unnamedLabel;
+ return title ?? '';
+}