Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(session): 新建任务第一帧用用户原文当标题 (#2868)
Dash135bf59f33eb
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.tsindex 76a9b1d613..8e4f1fe694 100644--- a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts@@ -699,6 +699,13 @@ describe('remoteProjectsStore pending title preview', () => {expect(remoteProjectsStore.getMergedRemoteSessions()[0]?.title).toBe('我自己起的名字');});+ it('can explicitly drop a preview when first-message handoff fails', () => {+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1', { title: 'New Maker' })]);+ remoteProjectsStore.setPendingTitlePreview('s1', '帮我排查登录失败');+ remoteProjectsStore.clearPendingTitlePreview('s1');+ expect(remoteProjectsStore.getMergedRemoteSessions()[0]?.title).toBe('New Maker');+ });+it('survives a snapshot rebuild while the authoritative title stays default', () => {remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1', { title: 'New Maker' })]);remoteProjectsStore.setPendingTitlePreview('s1', '帮我排查登录失败');diff --git a/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts b/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.tsindex eceb890343..52be29f987 100644--- a/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionTitleProjectionOutlets.test.ts@@ -19,7 +19,7 @@ import { describe, expect, it } from 'vitest';const RENDERER_ROOT = resolve(__dirname, '..');function read(relPath: string): string {- return readFileSync(resolve(RENDERER_ROOT, relPath), 'utf8');+ return readFileSync(resolve(RENDERER_ROOT, relPath), 'utf8').replace(/\r\n/g, '\n');}const railNav = read('features/cc-agent/sidebar/RailNav.tsx');@@ -75,6 +75,44 @@ describe('desktop 会话标题投影出口', () => {expect(draftRoute).toContain('if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);',);+ expect(draftRoute).toContain('let remoteOptimisticTitleSessionId: string | null = null;');+ expect(draftRoute).toContain(+ 'remoteProjectsStore.clearPendingTitlePreview(remoteOptimisticTitleSessionId);',+ );+ // 远程归属切换会提前 return,撤回必须排在它前面,否则空会话会一直顶着没发出去的原文。+ const remotePreviewClear = draftRoute.indexOf(+ 'remoteProjectsStore.clearPendingTitlePreview(remoteOptimisticTitleSessionId);',+ );+ const ownerChangedReturn = draftRoute.indexOf(+ 'if (isRemotePrecreatedWorktreeOwnerChangedError(err)) return;',+ remotePreviewClear,+ );+ expect(remotePreviewClear).toBeGreaterThan(-1);+ expect(ownerChangedReturn).toBeGreaterThan(remotePreviewClear);+ // createSession 返回 null 是 return,不进外层 catch,必须就地撤回。+ expect(draftRoute).toContain(+ 'if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);\n toastCreateSessionFailed();',+ );+ expect(draftRoute).toContain(+ 'if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);\n toastCreateSessionFailed();',+ );+ expect(draftRoute).toContain(+ 'if (optimisticGoalTitle) emitAutoTitlePreviewCleared(goalSessionId);',+ );+ const goalCatch = draftRoute.indexOf('} catch (error) {\n // 预览在 createSession 之前登记。');+ expect(goalCatch).toBeGreaterThan(-1);+ expect(draftRoute.indexOf(+ 'if (goalSessionId && optimisticGoalTitle) emitAutoTitlePreviewCleared(goalSessionId);',+ goalCatch,+ )).toBeGreaterThan(goalCatch);+ // 预览必须在本机发送路径的 createSession 之前登记,否则 sessions:created+ // 刷新会先画出「未命名任务」。文件前段还有 SSH / 远程建会话,不能拿第一处 create。+ const previewBeforeCreate = draftRoute.indexOf('emitAutoTitlePreview(sessionId, optimisticTitle)');+ const sendCreate = draftRoute.indexOf('const newSession = await createSession({', previewBeforeCreate);+ expect(previewBeforeCreate).toBeGreaterThan(-1);+ expect(sendCreate).toBeGreaterThan(previewBeforeCreate);+ // 纯附件远程预览必须登记成系统合成标题,否则后续第一句文字无法即时覆盖。+ expect(draftRoute).toContain('Boolean(normalizeAutoTitle(message))');});it('系统通知 / 飞书 / 手机推送的标题过投影,且语言走 ref 不被钉在首次渲染', () => {diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts b/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.tsindex 41e382c239..cbadd9de15 100644--- a/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts@@ -94,6 +94,14 @@ describe('sessionsStore — 自动起名的即时标题预览', () => {expect(sessionsStore.findById(SESSION_ID)).toBeNull();});+ it('预览先于 prependCreated 登记 → 插入第一帧就是用户原文', async () => {+ list.mockResolvedValue([]);+ await sessionsStore.ensureByFilter('active');+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');+ sessionsStore.prependCreated(session());+ expect(currentTitle()).toBe('帮我排查登录失败');+ });+it('空标题不触发预览(emit 侧已挡掉)', async () => {await seed(session());diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex 1cae85f35d..9bd07460bc 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -63,6 +63,7 @@ import { InheritedSubscriptionNotice } from '@/components/onboarding/InheritedSuimport { PromotionalGrantNotice } from '@/components/onboarding/PromotionalGrantNotice';import { resolveDeviceLinkSubmission } from './deviceLinkCreateArgs';import { commitRemoteSessionHandoff } from './remoteSessionHandoff';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';import {dbToMakerAgentKind,normalizeDbAgentKind,@@ -167,7 +168,11 @@ 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 {+ DEFAULT_DRAFT_SESSION_TITLE,+ deriveOptimisticSessionTitle,+ normalizeAutoTitle,+} from '@cindy/maker-shared/session-title';import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';import { InvisibleWindowDragStrip } from '@/components/layout/windowDrag';@@ -349,29 +354,33 @@ const DRAFT_IMAGE_URL_PREFIX = `xdt-image://${NEW_MAKER_DRAFT_KEY}/`;* (`remoteProjectsStore.setPendingTitlePreview`,免得干等一次隧道往返),本机路径缺的* 是对称的这一半。*- * 预览经 `emitAutoTitlePreview` 交给 sessionsStore:那边把它记进叠加层,既能活过新建- * 会话触发的 `forceRefreshAll`(否则会被仍带哨兵的 DB 快照冲掉),又统一持有「标题是否- * 仍是哨兵」这唯一一份判据。不写 DB —— 权威标题仍由 main 落库并广播回来,那个串与这里- * 算的是同一个(共用 `normalizeAutoTitle`),回流时不跳变。- *- * **只对能证明一致的纯文本消息放行**。带 @mention / 附件 / 会话引用时,权威占位由- * `deriveAutoTitleSeed` 另行推导(剔除 mention 的 wire token、拿文件名合成描述),这里- * 算不出同一个串 —— 预览会先显示 A 再跳成 B,比短暂显示占位更糟。这类消息交给显示层的- * 「未命名任务」兜底,等权威标题回流。+ * 预览必须在 `createSession` **之前**登记:main 一插入就广播 `sessions:created`,+ * renderer 立刻 `forceRefreshAll`,那次重拉仍带哨兵。预览晚一步,用户就会先看到+ * 「未命名任务」。sessionsStore.prependCreated 也会叠同一层,第一帧才不会露哨兵。*- * 纯文本时两侧一致是可证明的:无 reference / 未编码引用标记时 `projectLiteralUserText`- * 退化为 `text.trim()`,无 mention 时 `stripMentionTokens` 同样只做 trim,而- * `normalizeAutoTitle` 本身已含 trim。+ * 有字用字;没字再用附件名 / 类别词。带 @mention / 编码引用时权威占位由+ * `deriveAutoTitleSeed` 另行剔除 wire token,这里算不出同一个串,仍不预览。*/function optimisticFirstMessageTitle(message: string,files: AttachedFile[] | undefined,mentions: MentionedResource[] | undefined,opts: { quotesEncoded?: boolean; agentReferences?: AgentInputReference[] } | undefined,+ labels: { image: string; file: string },): string | null {- if (files?.length || mentions?.length) return null;- if (opts?.agentReferences?.length || opts?.quotesEncoded) return null;- return normalizeAutoTitle(message) || null;+ if (mentions?.length || opts?.agentReferences?.length || opts?.quotesEncoded) return null;+ const first = files?.[0];+ const title = deriveOptimisticSessionTitle({+ text: message,+ fileNames: (files ?? [])+ .filter((file) => !file.path?.startsWith('clipboard://'))+ .map((file) => file.originalName || file.name)+ .filter(Boolean),+ imageLabel: labels.image,+ fileLabel: labels.file,+ firstFileIsImage: first?.category === 'image',+ });+ return title || null;}/**@@ -3299,6 +3308,11 @@ export function NewMakerDraftRoute() {// catch 里撤回,否则空会话会跨列表刷新一直显示一句**没发出去**的话// (PR #1031 review P1;worktree 与 goal 两条路径各有自己的撤回点)。let optimisticTitleSessionId: string | null = null;+ let remoteOptimisticTitleSessionId: string | null = null;+ const autoTitleLabels = {+ image: t('ccAgent.autoTitle.image'),+ file: t('ccAgent.autoTitle.file'),+ };void (async () => {try {if (isDeviceLinkDraft && !isCurrentDataOwner()) return;@@ -3524,6 +3538,23 @@ export function NewMakerDraftRoute() {if (!isCurrentDataOwner()) {throw new RemotePrecreatedWorktreeOwnerChangedError();}+ {+ const optimisticTitle = optimisticFirstMessageTitle(+ message,+ files,+ mentions,+ opts,+ autoTitleLabels,+ );+ if (optimisticTitle) {+ remoteProjectsStore.setPendingTitlePreview(+ remoteSessionId,+ optimisticTitle,+ Boolean(normalizeAutoTitle(message)),+ );+ remoteOptimisticTitleSessionId = remoteSessionId;+ }+ }// remoteSessionId 到手就是**提交点**:对端会话已经建出来了。此后任何一步都不许再把它// 退化成「创建失败」—— 用户会照着提示重试,于是对端多出第二个会话,第一个空着永久滞留。// 钉归属 → 补临时行 → 触发回流这三条不变量、以及各自被 review 抓出来的理由,都在@@ -3619,6 +3650,17 @@ export function NewMakerDraftRoute() {// 拉起 Worker (见下方 "F-COLLAB: draft 阶段开了协同模式" 段)。const sessionId = makeDraftSessionId();+ const optimisticTitle = optimisticFirstMessageTitle(+ message,+ files,+ mentions,+ opts,+ autoTitleLabels,+ );+ if (optimisticTitle) {+ emitAutoTitlePreview(sessionId, optimisticTitle);+ optimisticTitleSessionId = sessionId;+ }const workingDir = selectedWorkingDir;const wt = selectedWorktree;// 生效条件 = 勾选 && baseRepo 已就绪。上面的发送门已阻止不完整状态;@@ -3649,6 +3691,7 @@ export function NewMakerDraftRoute() {providerId,});if (!newSession) {+ if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);toastCreateSessionFailed();return;}@@ -3662,11 +3705,6 @@ 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);});@@ -3892,6 +3930,7 @@ export function NewMakerDraftRoute() {providerId,});if (!newSession) {+ if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);toastCreateSessionFailed();return;}@@ -3917,11 +3956,6 @@ export function NewMakerDraftRoute() {{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 阶段开了协同模式 → createSession 之后立刻 enableOrca@@ -3992,10 +4026,14 @@ export function NewMakerDraftRoute() {: undefined,});} catch (err) {- if (isRemotePrecreatedWorktreeOwnerChangedError(err)) return;- log.error('[draft send]', err);// 交接失败 → 撤回乐观标题预览(理由见上面 optimisticTitleSessionId 的注释)。+ // 归属切换也会提前 return,必须先撤;否则已建、未发出首条的空会话会一直顶着原文。if (optimisticTitleSessionId) emitAutoTitlePreviewCleared(optimisticTitleSessionId);+ if (remoteOptimisticTitleSessionId) {+ remoteProjectsStore.clearPendingTitlePreview(remoteOptimisticTitleSessionId);+ }+ if (isRemotePrecreatedWorktreeOwnerChangedError(err)) return;+ log.error('[draft send]', err);toast.error(isRemotePrecreatedWorktreeCleanupPendingError(err)? t('ccAgent.draft.remoteWorktreeCleanupPending')@@ -4081,6 +4119,8 @@ export function NewMakerDraftRoute() {throw new Error(t('goal.newGoalDialog.busy'));}markSendInFlight(true);+ let goalSessionId: string | null = null;+ let optimisticGoalTitle: string | null = null;try {const selectedWorkingDir = effectiveWorkingDir?.trim() || undefined;const selectedWorktree = { ...wtRef.current };@@ -4319,6 +4359,12 @@ export function NewMakerDraftRoute() {if (!remoteSessionId) {throw new Error(t('ccAgent.draft.createSessionFailed'));}+ {+ const optimisticGoalTitle = normalizeAutoTitle(objective);+ if (optimisticGoalTitle) {+ remoteProjectsStore.setPendingTitlePreview(remoteSessionId, optimisticGoalTitle, true);+ }+ }// 与发送路径共用同一段交接收尾(钉归属 → 补临时行 → 触发回流)。三条不变量对目标路径// 同样成立,只是后果换了个形状:goalApiFor 也按归属路由,漏了钉子它就把 setGoal 发给本机// maker、对端刚建好的会话永远拿不到目标;而它不抛这条在这里更要紧 —— 抛出去 NewGoalDialog@@ -4449,7 +4495,9 @@ export function NewMakerDraftRoute() {&& selectedWorktree.enabled&& selectedWorktree.confirmedIneligible !== true,);- const goalSessionId = makeDraftSessionId();+ goalSessionId = makeDraftSessionId();+ optimisticGoalTitle = normalizeAutoTitle(objective);+ if (optimisticGoalTitle) emitAutoTitlePreview(goalSessionId, optimisticGoalTitle);let goalWorkingDir = selectedWorkingDir;let goalWorktreeName = '';let goalWorktreeBranchName = '';@@ -4483,6 +4531,7 @@ export function NewMakerDraftRoute() {providerId: chatInitialProviderId ?? null,});if (!newSession) {+ if (optimisticGoalTitle) emitAutoTitlePreviewCleared(goalSessionId);throw new Error(t('ccAgent.draft.createSessionFailed'));}if (useLocalGoalWorktree) {@@ -4511,13 +4560,9 @@ export function NewMakerDraftRoute() {});await refreshWorktrees();}- // 目标文案是纯文本(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 + 降级@@ -4581,6 +4626,9 @@ export function NewMakerDraftRoute() {state: orcaWorkersRevealState ? { orcaWorkersReveal: orcaWorkersRevealState } : undefined,});} catch (error) {+ // 预览在 createSession 之前登记。worktree 建议名 / 建树 / 回滚失败都走这里,+ // 不撤回会让空会话或未建成的 goalSessionId 一直顶着目标原文。+ if (goalSessionId && optimisticGoalTitle) emitAutoTitlePreviewCleared(goalSessionId);if (isLocalGoalWorktreeCleanupPendingError(error)) {log.error('[draft goal] incomplete local worktree session cleanup failed', {setupError: error.setupError,diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.tsindex d152806399..c2185bc697 100644--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts@@ -795,6 +795,16 @@ const actions = {recompute();},+ /**+ * 撤回一次远程标题预览。远端会话已建、但首条消息没交出去时调用 —— 权威标题+ * 仍是哨兵,叠加层会一直把没发出去的话顶在空会话上。+ */+ clearPendingTitlePreview(sessionId: string): void {+ if (!sessionId || !pendingTitlePreview.has(sessionId)) return;+ dropTitleOverlay(sessionId);+ recompute();+ },+/** 测试专用:清空标题预览叠加层。 */__resetPendingTitlePreviewForTest(): void {pendingTitlePreview.clear();diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.tsindex 3f16e3a398..72c4c985bd 100644--- a/apps/desktop/src/renderer/lib/sessionsStore.ts+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts@@ -498,11 +498,14 @@ export const sessionsStore = {*/prependCreated(session: Session): void {if (!session?.id) return;+ // 插入前叠乐观预览:createSession 往往先于 sessions:created 刷新返回,但预览+ // 必须在入库前就登记。若不在这里叠,第一帧仍是哨兵,用户会先看到「未命名任务」。+ const [withPreview] = applyAutoTitlePreviews([session]);let touched = false;for (const [k, list] of cache) {if (k === 'archived') continue;if (list.some((s) => s.id === session.id)) continue;- cache.set(k, [session, ...list]);+ cache.set(k, [withPreview, ...list]);touched = true;}if (touched) notify();diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 33de6d0bf5..9bb0b2f2e8 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -165,6 +165,7 @@ import {type NewSessionDeviceOption,type NewSessionStoredPreferences,} from '@/session/newSession';+import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';import { newSessionText } from '@/session/newSessionMessages';import { i18n } from '@/i18n';import {@@ -5047,10 +5048,23 @@ export default function NewRemoteSessionScreen() {if (!isCurrentOwner() || !ensureDeviceAlive()) return;} catch {if (!isCurrentOwner() || !ensureDeviceAlive()) return;- session = sessionFromCreateResult(result, finalDraft);+ session = sessionFromCreateResult(result, {+ ...finalDraft,+ firstMessage: input.objective,+ });+ }+ if (isDefaultDraftSessionTitle(session.title)) {+ const titled = sessionFromCreateResult(result, {+ ...finalDraft,+ firstMessage: input.objective,+ });+ session = { ...session, title: titled.title };}if (!isCurrentOwner() || !ensureDeviceAlive()) return;remoteSessionStore.upsertDeviceSession(selectedDeviceId, selectedDeviceName, session);+ if (session.title && !isDefaultDraftSessionTitle(session.title)) {+ remoteSessionStore.setPendingTitlePreview(result.sessionId, session.title);+ }if (!isCurrentOwner() || !ensureDeviceAlive()) return;// 目标流不带 composer 附件(与桌面一致),跳转即丢引用:已上传的中转对象在此// best-effort 回收,否则成为 OSS 孤儿直到桶生命周期清理(codex review #504)。diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex 1a69564dbb..a2db09cdac 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -1437,8 +1437,10 @@ describe('new session model', () => {permissionMode: 'acceptEdits',fastMode: false,providerId: null,+ firstMessage: '帮我排查登录失败',}, new Date('2026-06-16T10:00:00.000Z'))).toMatchObject({id: 's-new',+ title: '帮我排查登录失败',workingDir: '/repo',workspaceKind: 'project',agentKind: 'cc',@@ -1481,6 +1483,7 @@ describe('new session model', () => {providerId: 'deepseek',});expect(session.providerId).toBe('deepseek');+ expect(session.title).toBe('New Maker');// 未绑定来源的草稿 → null(默认路由),与真实会话同形expect(sessionFromCreateResult({ sessionId: 's-n' }, {agentKind: 'claude-code',@@ -2332,6 +2335,18 @@ describe('submit guard catalog wiring (source locks)', () => {expect(lastCheck).toBeGreaterThan(0);expect(settleSlice.slice(lastCheck)).not.toMatch(/await /);});++ it('goal settle 只登记本机预览,不把目标文案写成用户改名', () => {+ const goalSlice = newSource.slice(newSource.indexOf('const createGoalSession = useCallback'));+ const settleSlice = goalSlice.slice(+ goalSlice.indexOf('── settle 段'),+ goalSlice.indexOf('router.replace({'),+ );+ expect(settleSlice).toContain('remoteSessionStore.setPendingTitlePreview(result.sessionId, session.title)');+ expect(settleSlice).not.toContain('persistRemoteGoalSessionTitle');+ expect(settleSlice).not.toContain('patchSessionMeta');+ expect(settleSlice).not.toContain('generateSessionTitle');+ });});describe('fast memory restore wiring (source locks)', () => {diff --git a/apps/mobile/src/__tests__/newSessionCreation.test.ts b/apps/mobile/src/__tests__/newSessionCreation.test.tsindex 0bc4362022..1ad5c08d41 100644--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts@@ -173,6 +173,7 @@ describe('newSessionCreation pipeline', () => {const row = remoteSessionStore.getSessions().find((s) => s.id === 's1');expect(row?.pendingLocalCreation).toBe(true);expect(row?.workingDir).toBe('/repo');+ expect(row?.title).toBe('hello world');const projection = remoteSessionStore.getInputProjection('s1');expect(projection.pendingQueue).toHaveLength(1);expect(projection.pendingQueue[0]?.text).toBe('hello world');@@ -196,6 +197,15 @@ describe('newSessionCreation pipeline', () => {// fresh getSession 失败(makeMaker 默认抛 NOT_FOUND)时权威覆盖没发生,管线// 收口前必须主动清 pendingLocalCreation 禁发标(codex P2)。expect(remoteSessionStore.getSessions().find((s) => s.id === 's2')?.pendingLocalCreation).toBe(false);+ // 入队成功只解禁,标题预览要等到权威标题离开哨兵才让位。+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ sessionFromCreateResult({ sessionId: 's2' }, { ...DRAFT, firstMessage: '' }),+ ]);+ expect(remoteSessionStore.getSessions().find((s) => s.id === 's2')?.title).toBe('hello world');+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ { ...sessionFromCreateResult({ sessionId: 's2' }, DRAFT), title: '登录失败排查' },+ ]);+ expect(remoteSessionStore.getSessions().find((s) => s.id === 's2')?.title).toBe('登录失败排查');});it('首条消息 enqueue 前应用手机控制端准备的可信引用快照', async () => {@@ -518,6 +528,7 @@ describe('newSessionCreation pipeline', () => {// 禁发标同步清除:用户要用 composer 重发回填草稿,不能被 pendingLocalCreation// 卡到 load 成功才解禁(codex P2)。expect(remoteSessionStore.getSessions().find((s) => s.id === 's5')?.pendingLocalCreation).toBe(false);+ expect(remoteSessionStore.getSessions().find((s) => s.id === 's5')?.title).toBe('New Maker');});it('enqueue 回执丢失但队列里已有该 clientId → 按成功收敛,不打扰用户', async () => {diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 2bc8669fd6..99d754193c 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -437,6 +437,69 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.getSessions()[0].agentSwitchIntent).toBeNull();});+ it('does not let a draft sentinel snapshot replace an optimistic first-message title', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: '帮我排查登录失败' }),+ ]);+ remoteSessionStore.setPendingTitlePreview('s1', '帮我排查登录失败');+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: 'New Maker' }),+ ]);+ expect(remoteSessionStore.getSessions()[0]?.title).toBe('帮我排查登录失败');++ remoteSessionStore.applySessionPatch('dev-1', 's1', { title: 'New Maker' });+ expect(remoteSessionStore.getSessions()[0]?.title).toBe('帮我排查登录失败');++ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: '登录失败排查' }),+ ]);+ expect(remoteSessionStore.getSessions()[0]?.title).toBe('登录失败排查');+ });++ it('keeps the first-message preview after pendingLocalCreation settles', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: '帮我排查登录失败', pendingLocalCreation: true }),+ ]);+ remoteSessionStore.setPendingTitlePreview('s1', '帮我排查登录失败');+ remoteSessionStore.applySessionPatch('dev-1', 's1', { pendingLocalCreation: false });+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: 'New Maker' }),+ ]);+ expect(remoteSessionStore.getSessions()[0]?.title).toBe('帮我排查登录失败');+ expect(remoteSessionStore.getSessions()[0]?.pendingLocalCreation).toBeFalsy();+ });++ it('lets an authoritative New Maker rename through after the preview is cleared', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: '帮我排查登录失败' }),+ ]);+ remoteSessionStore.setPendingTitlePreview('s1', '帮我排查登录失败');+ remoteSessionStore.clearPendingTitlePreview('s1');+ remoteSessionStore.applySessionPatch('dev-1', 's1', { title: 'New Maker' });+ expect(remoteSessionStore.getSessions()[0]?.title).toBe('New Maker');+ });++ it('keeps a title preview across a stale list that temporarily omits the new session', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s-old'),+ ]);+ remoteSessionStore.upsertDeviceSession(+ 'dev-1',+ 'Mac',+ session('s-new', { title: '帮我排查登录失败', pendingLocalCreation: true }),+ );+ remoteSessionStore.setPendingTitlePreview('s-new', '帮我排查登录失败');+ remoteSessionStore.applySessionPatch('dev-1', 's-new', { pendingLocalCreation: false });+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s-old'),+ ]);+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s-old'),+ session('s-new', { title: 'New Maker' }),+ ]);+ expect(remoteSessionStore.getSessions().find((row) => row.id === 's-new')?.title).toBe('帮我排查登录失败');+ });+it('dedupes an unchanged message push by id or client id', () => {remoteSessionStore.setMessages('s1', [message('m1', 's1')]);const versionAfterSet = remoteSessionStore.getMessageVersion();diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.tsindex 40bcdc66f6..d76d73f8a0 100644--- a/apps/mobile/src/session/newSession.ts+++ b/apps/mobile/src/session/newSession.ts@@ -1,5 +1,9 @@import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';import { collapseWorktreeDirForGrouping } from '@cindy/maker-shared/worktree-paths';+import {+ DEFAULT_DRAFT_SESSION_TITLE,+ deriveOptimisticSessionTitle,+} from '@cindy/maker-shared/session-title';import { i18n } from '@/i18n';import type { CreateSessionOptions, RemoteDirectoryEntry } from '@/device-link/mobileMakerTransport';import type { DeviceProvidersPayload } from '@/device-link/deviceProvidersCache';@@ -858,14 +862,28 @@ export function normalizeCreateSessionResult(value: unknown): CreateSessionResulexport function sessionFromCreateResult(result: CreateSessionResult,- fallback: Pick<NewSessionDraft, 'agentKind' | 'workspaceKind' | 'model' | 'effort' | 'permissionMode' | 'fastMode' | 'workingDir' | 'providerId'>,+ fallback: Pick<NewSessionDraft, 'agentKind' | 'workspaceKind' | 'model' | 'effort' | 'permissionMode' | 'fastMode' | 'workingDir' | 'providerId'> & {+ firstMessage?: string;+ attachments?: readonly { name?: string; originalName?: string; path?: string; category?: string }[];+ },now = new Date(),): RemoteSession {const iso = now.toISOString();+ const first = fallback.attachments?.[0];+ const optimisticTitle = deriveOptimisticSessionTitle({+ text: fallback.firstMessage,+ fileNames: (fallback.attachments ?? [])+ .filter((file) => !file.path?.startsWith('clipboard://'))+ .map((file) => file.originalName || file.name || '')+ .filter(Boolean),+ imageLabel: i18n.t('session.common.photo'),+ fileLabel: i18n.t('session.common.file'),+ firstFileIsImage: first?.category === 'image',+ });return {id: result.sessionId,userId: '',- title: 'New remote session',+ title: optimisticTitle || DEFAULT_DRAFT_SESSION_TITLE,workingDir: result.workDir ?? fallback.workingDir,workspaceKind: fallback.workspaceKind,model: fallback.model,diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.tsindex 9721f37b2d..b3dc595f5c 100644--- a/apps/mobile/src/session/newSessionCreation.ts+++ b/apps/mobile/src/session/newSessionCreation.ts@@ -28,6 +28,7 @@import { useSyncExternalStore } from 'react';import * as ExpoCrypto from 'expo-crypto';import { isPreconditionFailedRemoteError } from '@cindy/maker-shared/device-link-contract';+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';import { i18n } from '@/i18n';import { isTransientRemoteError, withTransientRemoteRetry } from '@/device-link/remoteRetry';import { formatRemoteError } from '@/device-link/remoteStatus';@@ -245,8 +246,12 @@ function attachFirstMessageSessionReferences(}function synthesizeSession(params: NewSessionCreationParams, draftOverride?: NewSessionDraft): RemoteSession {+ const draft = draftOverride ?? params.draft;return {- ...sessionFromCreateResult({ sessionId: params.sessionId }, draftOverride ?? params.draft),+ ...sessionFromCreateResult({ sessionId: params.sessionId }, {+ ...draft,+ attachments: params.attachments,+ }),pendingLocalCreation: true,};}@@ -264,6 +269,9 @@ export function startNewSessionCreation(params: NewSessionCreationParams): void);const session = synthesizeSession(params);remoteSessionStore.upsertDeviceSession(params.deviceId, params.deviceName, session);+ if (session.title && session.title !== DEFAULT_DRAFT_SESSION_TITLE) {+ remoteSessionStore.setPendingTitlePreview(params.sessionId, session.title);+ }const queued = attachFirstMessageSessionReferences(buildQueuedTextMessage(session,params.draft.firstMessage,@@ -308,6 +316,9 @@ export function retryNewSessionCreation(sessionId: string): void {// 重试前把乐观行 / 气泡恢复(返回编辑路径可能没走,行一般还在,upsert 幂等)。const session = synthesizeSession(task.params);remoteSessionStore.upsertDeviceSession(task.deviceId, task.deviceName, session);+ if (session.title && session.title !== DEFAULT_DRAFT_SESSION_TITLE) {+ remoteSessionStore.setPendingTitlePreview(sessionId, session.title);+ }const queued = attachFirstMessageSessionReferences(buildQueuedTextMessage(session,task.draft.firstMessage,@@ -332,6 +343,7 @@ export function dismissNewSessionCreation(sessionId: string, opts: { removeSynthif (opts.removeSyntheticRow) {remoteSessionStore.applySessionPatch(task.deviceId, sessionId, { status: 'deleted' });remoteSessionStore.setInputProjection(sessionId, null);+ remoteSessionStore.clearPendingTitlePreview(sessionId);}emit();}@@ -557,7 +569,13 @@ function failTask(task: InternalTask, status: 'create-failed' | 'enqueue-failed'// 禁发标——弱网下 fresh getSession / 会话页 load 可能都还没成功,不清的话// 用户拿着回填草稿仍被禁发,只能干等 load(codex review P2)。remoteSessionStore.setInputProjection(task.sessionId, null);- remoteSessionStore.applySessionPatch(task.deviceId, task.sessionId, { pendingLocalCreation: false });+ remoteSessionStore.clearPendingTitlePreview(task.sessionId);+ remoteSessionStore.applySessionPatch(task.deviceId, task.sessionId, {+ pendingLocalCreation: false,+ });+ remoteSessionStore.applySessionPatch(task.deviceId, task.sessionId, {+ title: DEFAULT_DRAFT_SESSION_TITLE,+ });}emit();}@@ -852,6 +870,7 @@ function cancelStaleOwnerTask(task: InternalTask): void {if (session && remoteSessionStore.getSessionDeviceId(task.sessionId) === task.deviceId) {remoteSessionStore.applySessionPatch(task.deviceId, task.sessionId, { status: 'deleted' });remoteSessionStore.setInputProjection(task.sessionId, null);+ remoteSessionStore.clearPendingTitlePreview(task.sessionId);}emit();}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 84d2a12fca..1d25794f78 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -19,6 +19,7 @@ import {isProductTurnDoneEvent,isTurnContinuationBoundaryEvent,} from '@cindy/maker-shared/turn-continuation';+import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';import { EMPTY_INPUT_PROJECTION, normalizeInputProjection } from '@/session/inputProjection';import { sortPendingInteractions } from '@/session/interactionModel';import { applySessionModelPrefPush } from '@/session/sessionModelMirror';@@ -283,6 +284,12 @@ function interactionsByRequestId(list: readonly PendingInteraction[]): Map<strinreturn byId;}const inputProjections = new Map<string, InputProjection>();+/**+ * 新建任务第一帧标题预览。权威行在自动起名写库前仍是 New Maker;入队成功后+ * pendingLocalCreation 必须清掉才能解禁,所以预览不能绑在那根标上。权威标题+ * 一旦离开哨兵(智能标题或用户改名)就让位。+ */+const pendingTitlePreview = new Map<string, string>();// Projection queries can resolve after a newer push or terminal boundary. Keep// a monotonic per-session authority epoch so late snapshots cannot overwrite// current queue / continuation state (mirrors Desktop makerChatStore).@@ -823,12 +830,15 @@ function recomputeSessions(): void {const next: RemoteSession[] = [];for (const { session, physicalDeviceId } of byId.values()) {const prev = prevById.get(session.id);- next.push(prev && remoteSessionEqual(prev, session) ? prev : session);+ const projected = applyPendingTitlePreview(session);+ next.push(prev && remoteSessionEqual(prev, projected) ? prev : projected);sessionDeviceIndex.set(session.id, physicalDeviceId);}for (const sessionId of [...sessionLiveActivity.keys()]) {if (!sessionDeviceIndex.has(sessionId)) sessionLiveActivity.delete(sessionId);}+ // 预览不因列表短暂缺席回收:旧 sessions:list 可能在远端建会话前发出、入队成功后才回来。+ // 权威标题落地、明确失败撤回、归档/删除、设备移除、clear() 才会丢掉。// 数组级同样调和:全部元素引用与序都未变时保留旧数组引用——useRemoteSessions 的// useSyncExternalStore 快照经 Object.is 即可短路,消费屏对无关 emit 零重渲染。mergedSessions = sameElementRefs(mergedSessions, next) ? mergedSessions : next;@@ -867,18 +877,43 @@ function stamp(session: RemoteSession, deviceId: string, deviceName: string): Rereturn { ...session, deviceLinkDeviceId: deviceId, deviceLinkDeviceName: deviceName };}+function dropPendingTitlePreview(sessionId: string): void {+ pendingTitlePreview.delete(sessionId);+}++function isDraftSentinelTitle(title: string | undefined): boolean {+ return !title+ || isDefaultDraftSessionTitle(title)+ || title === 'New remote session';+}++function applyPendingTitlePreview(session: RemoteSession): RemoteSession {+ const preview = pendingTitlePreview.get(session.id);+ if (!preview) return session;+ // 分片里可能已经是乐观原文(合成行),也可能仍是哨兵。只有权威标题变成+ // 另一串(智能标题 / 用户改名)才让位;不能把「分片 == 预览」当成终态丢掉。+ if (isDraftSentinelTitle(session.title) || session.title === preview) {+ return session.title === preview ? session : { ...session, title: preview };+ }+ dropPendingTitlePreview(session.id);+ return session;+}+/*** SQLite session 快照不包含 desktop main 内存里的 pending Agent intent。全量列表 / getSession* 对账只能刷新持久化字段,不能顺手抹掉已由 push / 权威查询写入的运行时镜像;显式携带该字段* 的新快照仍优先(包括 null)。*/function preserveSessionRuntimeFields(fresh: RemoteSession, local: RemoteSession | undefined): RemoteSession {+ if (!local) return fresh;+ let next = fresh;if (- !local- || Object.prototype.hasOwnProperty.call(fresh, 'agentSwitchIntent')- || local.agentSwitchIntent === undefined- ) return fresh;- return { ...fresh, agentSwitchIntent: local.agentSwitchIntent };+ !Object.prototype.hasOwnProperty.call(fresh, 'agentSwitchIntent')+ && local.agentSwitchIntent !== undefined+ ) {+ next = { ...next, agentSwitchIntent: local.agentSwitchIntent };+ }+ return next;}function normalizeMessages(list: readonly RemoteMessage[]): RemoteMessage[] {@@ -1533,6 +1568,24 @@ function recallParkedTaskUpdates(}export const remoteSessionStore = {+ /**+ * 新建任务第一帧标题预览。只盖哨兵,权威标题一旦离开哨兵就让位。+ * 失败撤回走 {@link clearPendingTitlePreview}。+ */+ setPendingTitlePreview(sessionId: string, title: string): void {+ const next = title.trim();+ if (!sessionId || !next) return;+ if (pendingTitlePreview.get(sessionId) === next) return;+ pendingTitlePreview.set(sessionId, next);+ recomputeSessions();+ },++ clearPendingTitlePreview(sessionId: string): void {+ if (!sessionId || !pendingTitlePreview.has(sessionId)) return;+ dropPendingTitlePreview(sessionId);+ recomputeSessions();+ },+/*** 读当前权威设备身份列表(setDeviceIdentity 注入的那份;未注入过为空)。* 会话页抽屉等在首页之外调 buildMobileHomePresentation 时传入,保证展示归一化@@ -1792,6 +1845,7 @@ export const remoteSessionStore = {if (patch.status === 'deleted' || patch.status === 'archived') {shard.sessions = shard.sessions.filter((s) => s.id !== sessionId);sessionLiveActivity.delete(sessionId);+ dropPendingTitlePreview(sessionId);let messageStateChanged = invalidateSessionMessageWindowState(sessionId, false);messageStateChanged = releaseSessionDetailProjections(sessionId) || messageStateChanged;sessionMessageLifecycle.forget(sessionId);@@ -1800,7 +1854,10 @@ export const remoteSessionStore = {} else {const wasPinned = shard.sessions[idx].pinnedAt != null;const unpinned = Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;- const patched = { ...shard.sessions[idx], ...patch } as RemoteSession;+ const patched = preserveSessionRuntimeFields(+ { ...shard.sessions[idx], ...patch } as RemoteSession,+ shard.sessions[idx],+ );if (remoteSessionEqual(shard.sessions[idx], patched)) return;shard.sessions = shard.sessions.map((s) => (s.id === sessionId ? patched : s));shouldReseedAfterPatch = wasPinned && unpinned;@@ -3166,6 +3223,7 @@ export const remoteSessionStore = {sessionMessageLifecycle.forget(sessionId);sessionLastAccessOrder.delete(sessionId);sessionDeviceIndex.delete(sessionId);+ dropPendingTitlePreview(sessionId);// revision 下限按会话回收:它不参与单轮快照回收(那会把覆盖权还给晚到的// 旧快照),所以只能在会话本身消失时清,保持有界。const sessionPrefix = interactionResolveKey(sessionId, '');@@ -3221,6 +3279,7 @@ export const remoteSessionStore = {nextSessionAccessOrder = 0;sessionDeviceIndex.clear();reseedHandlers.clear();+ pendingTitlePreview.clear();mergedSessions = [];deviceList = null;bumpMessageVersion();diff --git a/packages/maker-shared/src/__tests__/sessionTitle.test.ts b/packages/maker-shared/src/__tests__/sessionTitle.test.tsindex 5bebaa1e27..ac412f9475 100644--- a/packages/maker-shared/src/__tests__/sessionTitle.test.ts+++ b/packages/maker-shared/src/__tests__/sessionTitle.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';import {DEFAULT_DRAFT_SESSION_TITLE,+ deriveOptimisticSessionTitle,isDefaultDraftSessionTitle,normalizeAutoTitle,projectDraftSessionTitle,@@ -83,3 +84,45 @@ describe('projectDraftSessionTitle', () => {expect(projectDraftSessionTitle(once, '未命名任务')).toBe(once);});});++describe('deriveOptimisticSessionTitle', () => {+ it('有用户文字 → 原文截断,附件名不插手', () => {+ expect(deriveOptimisticSessionTitle({+ text: ' 帮我排查登录失败 ',+ fileNames: ['shot.png'],+ imageLabel: '图片',+ firstFileIsImage: true,+ })).toBe('帮我排查登录失败');+ });++ it('没文字、有附件名 → 用文件名', () => {+ expect(deriveOptimisticSessionTitle({+ text: ' ',+ fileNames: ['需求评审.pdf', 'shot.png'],+ fileLabel: '文件',+ })).toBe('需求评审.pdf');+ });++ it('附件名是绝对路径 → 只取 basename,与权威链路一致', () => {+ expect(deriveOptimisticSessionTitle({+ fileNames: ['/Users/dash/Downloads/需求评审.pdf'],+ })).toBe('需求评审.pdf');+ expect(deriveOptimisticSessionTitle({+ fileNames: ['C:\\Users\\dash\\Downloads\\shot.png'],+ })).toBe('shot.png');+ });++ it('没文字也没文件名、是图片 → 类别词', () => {+ expect(deriveOptimisticSessionTitle({+ fileNames: [],+ imageLabel: '图片',+ fileLabel: '文件',+ firstFileIsImage: true,+ })).toBe('图片');+ });++ it('什么都没有 → 空串,交给显示层兜底', () => {+ expect(deriveOptimisticSessionTitle({ text: '' })).toBe('');+ expect(deriveOptimisticSessionTitle({})).toBe('');+ });+});diff --git a/packages/maker-shared/src/sessionTitle.ts b/packages/maker-shared/src/sessionTitle.tsindex 85742fb1a2..f83d6e07ef 100644--- a/packages/maker-shared/src/sessionTitle.ts+++ b/packages/maker-shared/src/sessionTitle.ts@@ -61,3 +61,33 @@ export function projectDraftSessionTitle(if (isDefaultDraftSessionTitle(title) && unnamedLabel) return unnamedLabel;return title ?? '';}++/**+ * 新建任务第一帧该显示的标题。有用户文字就用原文截断;没有文字时才用附件名 /+ * 类别词。算不出任何东西时返回空串,调用方再落到哨兵的显示层兜底。+ *+ * 桌面乐观预览、手机合成行、远程临时行共用这一份,避免「先亮未命名任务、再跳成+ * 用户那句话」。mention / 引用的权威剔除仍在 desktop `deriveAutoTitleSeed`;+ * 这里只处理调用方已经确认可当标题的素材。+ */+function optimisticFileBaseName(name: string): string {+ return name.split(/[\\/]/).pop() ?? '';+}++export function deriveOptimisticSessionTitle(input: {+ text?: string | null;+ fileNames?: readonly string[] | null;+ imageLabel?: string | null;+ fileLabel?: string | null;+ firstFileIsImage?: boolean;+}): string {+ const fromText = normalizeAutoTitle(input.text ?? '');+ if (fromText) return fromText;+ for (const name of input.fileNames ?? []) {+ const fromFile = normalizeAutoTitle(optimisticFileBaseName(name));+ if (fromFile) return fromFile;+ }+ if (input.firstFileIsImage) return normalizeAutoTitle(input.imageLabel ?? '');+ if ((input.fileNames?.length ?? 0) > 0) return normalizeAutoTitle(input.fileLabel ?? '');+ return '';+}