Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(worktree): restore host-owned creation contract
kafeifei9b4edc336dcf
diff --git a/apps/desktop/src/main/maker-host/__tests__/newMakerWorktreeBranchPreferenceCache.test.ts b/apps/desktop/src/main/maker-host/__tests__/newMakerWorktreeBranchPreferenceCache.test.tsnew file mode 100644index 0000000000..e8c133912b--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/newMakerWorktreeBranchPreferenceCache.test.ts@@ -0,0 +1,50 @@+import path from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';++import {+ applyNewMakerWorktreeBranchPreference,+ getNewMakerWorktreeBranchPreference,+ resetNewMakerWorktreeBranchPreferencesForTest,+} from '../newMakerWorktreeBranchPreferenceCache';++describe('newMakerWorktreeBranchPreferenceCache', () => {+ afterEach(() => resetNewMakerWorktreeBranchPreferencesForTest());++ it('returns null until a repository has a host-owned selection', () => {+ expect(getNewMakerWorktreeBranchPreference('/tmp/repo')).toBeNull();+ });++ it('canonicalizes the repository key and isolates different repositories', () => {+ const snapshot = applyNewMakerWorktreeBranchPreference({+ baseRepo: '/tmp/parent/../repo/',+ sourceBranch: ' feature/mobile ',+ });++ expect(snapshot).toEqual({+ baseRepo: path.resolve('/tmp/repo'),+ sourceBranch: 'feature/mobile',+ revision: 1,+ });+ expect(getNewMakerWorktreeBranchPreference('/tmp/repo/.')).toEqual(snapshot);+ expect(getNewMakerWorktreeBranchPreference('/tmp/other')).toBeNull();+ });++ it('increments a per-repository revision even when the value is unchanged', () => {+ const first = applyNewMakerWorktreeBranchPreference({+ baseRepo: '/tmp/repo-a',+ sourceBranch: 'main',+ });+ const second = applyNewMakerWorktreeBranchPreference({+ baseRepo: '/tmp/repo-a',+ sourceBranch: 'main',+ });+ const other = applyNewMakerWorktreeBranchPreference({+ baseRepo: '/tmp/repo-b',+ sourceBranch: 'main',+ });++ expect(first.revision).toBe(1);+ expect(second.revision).toBe(2);+ expect(other.revision).toBe(1);+ });+});diff --git a/apps/desktop/src/main/maker-host/newMakerWorktreeBranchPreferenceCache.ts b/apps/desktop/src/main/maker-host/newMakerWorktreeBranchPreferenceCache.tsnew file mode 100644index 0000000000..c6381563dc--- /dev/null+++ b/apps/desktop/src/main/maker-host/newMakerWorktreeBranchPreferenceCache.ts@@ -0,0 +1,52 @@+/**+ * New Maker worktree source-branch preferences owned by this work endpoint.+ *+ * A source branch describes one repository, not the device-wide New Maker+ * draft. Keep it in a repo-scoped, process-lifetime cache so local Desktop and+ * device-link controllers can share one live value without persisting a branch+ * from repository A into repository B.+ */+import path from 'node:path';++export interface NewMakerWorktreeBranchPreferenceSnapshot {+ baseRepo: string;+ sourceBranch: string;+ revision: number;+}++const preferences = new Map<string, NewMakerWorktreeBranchPreferenceSnapshot>();++/** Canonical wire/store key. Callers validate that baseRepo is absolute first. */+export function canonicalizeNewMakerWorktreeBaseRepo(baseRepo: string): string {+ return path.resolve(baseRepo.trim());+}++export function getNewMakerWorktreeBranchPreference(+ baseRepo: string,+): NewMakerWorktreeBranchPreferenceSnapshot | null {+ return preferences.get(canonicalizeNewMakerWorktreeBaseRepo(baseRepo)) ?? null;+}++/**+ * Last host-accepted write wins. Same-value writes still advance revision so a+ * controller can fence a pull or invoke completion that started before it.+ */+export function applyNewMakerWorktreeBranchPreference(input: {+ baseRepo: string;+ sourceBranch: string;+}): NewMakerWorktreeBranchPreferenceSnapshot {+ const baseRepo = canonicalizeNewMakerWorktreeBaseRepo(input.baseRepo);+ const current = preferences.get(baseRepo);+ const snapshot: NewMakerWorktreeBranchPreferenceSnapshot = {+ baseRepo,+ sourceBranch: input.sourceBranch.trim(),+ revision: (current?.revision ?? 0) + 1,+ };+ preferences.set(baseRepo, snapshot);+ return snapshot;+}++/** Test-only reset for this process-lifetime cache. */+export function resetNewMakerWorktreeBranchPreferencesForTest(): void {+ preferences.clear();+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/newMakerWorktreeBranchPreferenceHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/newMakerWorktreeBranchPreferenceHandler.test.tsnew file mode 100644index 0000000000..bdc1f6c100--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/newMakerWorktreeBranchPreferenceHandler.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it, vi } from 'vitest';++import { MAKER_INVOKE, MAKER_PUSH } from '../channels';+import {+ registerNewMakerWorktreeBranchPreferenceHandler,+ type NewMakerWorktreeBranchPreferenceHandlerDeps,+} from '../newMakerWorktreeBranchPreferenceHandler';+import { IpcHarness } from './helpers/ipcHarness';++const SNAPSHOT = {+ baseRepo: '/tmp/repo',+ sourceBranch: 'feature/mobile',+ revision: 3,+};++function createDeps(+ overrides: Partial<NewMakerWorktreeBranchPreferenceHandlerDeps> = {},+): NewMakerWorktreeBranchPreferenceHandlerDeps {+ return {+ isDeviceLinkInvoke: vi.fn(() => false),+ assertTrustedCaller: vi.fn(),+ getPreference: vi.fn(() => null),+ applyPreference: vi.fn(() => SNAPSHOT),+ broadcast: vi.fn(),+ ...overrides,+ };+}++describe('New Maker worktree branch preference IPC', () => {+ it('returns null for a valid repository with no host selection', async () => {+ const harness = new IpcHarness();+ const deps = createDeps();+ registerNewMakerWorktreeBranchPreferenceHandler(harness, deps);++ await expect(+ harness.invoke(MAKER_INVOKE.GET_NEW_MAKER_WORKTREE_BRANCH_PREF, { baseRepo: '/tmp/repo' }),+ ).resolves.toBeNull();+ expect(deps.getPreference).toHaveBeenCalledWith('/tmp/repo');+ });++ it('applies and broadcasts the exact host snapshot', async () => {+ const harness = new IpcHarness();+ const deps = createDeps();+ registerNewMakerWorktreeBranchPreferenceHandler(harness, deps);++ await expect(+ harness.invoke(MAKER_INVOKE.APPLY_NEW_MAKER_WORKTREE_BRANCH_PREF, {+ baseRepo: '/tmp/repo',+ sourceBranch: ' feature/mobile ',+ }),+ ).resolves.toEqual(SNAPSHOT);++ expect(deps.applyPreference).toHaveBeenCalledWith({+ baseRepo: '/tmp/repo',+ sourceBranch: 'feature/mobile',+ });+ expect(deps.broadcast).toHaveBeenCalledWith(+ MAKER_PUSH.NEW_MAKER_WORKTREE_BRANCH_CHANGED,+ SNAPSHOT,+ );+ });++ it('allows a device-link invoke without an Electron sender', async () => {+ const harness = new IpcHarness();+ const deps = createDeps({ isDeviceLinkInvoke: vi.fn(() => true) });+ registerNewMakerWorktreeBranchPreferenceHandler(harness, deps);++ await expect(+ harness.invoke(MAKER_INVOKE.GET_NEW_MAKER_WORKTREE_BRANCH_PREF, { baseRepo: '/tmp/repo' }),+ ).resolves.toBeNull();+ expect(deps.assertTrustedCaller).not.toHaveBeenCalled();+ });++ it.each([+ [{ baseRepo: 'relative/repo' }, 'baseRepo must be absolute'],+ [{ baseRepo: '/tmp/repo', sourceBranch: '' }, 'sourceBranch is invalid'],+ [{ baseRepo: '/tmp/repo', sourceBranch: 'bad\0branch' }, 'sourceBranch is invalid'],+ ])('rejects invalid input %#', async (request, message) => {+ const harness = new IpcHarness();+ const deps = createDeps();+ registerNewMakerWorktreeBranchPreferenceHandler(harness, deps);+ const channel = Object.prototype.hasOwnProperty.call(request, 'sourceBranch')+ ? MAKER_INVOKE.APPLY_NEW_MAKER_WORKTREE_BRANCH_PREF+ : MAKER_INVOKE.GET_NEW_MAKER_WORKTREE_BRANCH_PREF;++ await expect(harness.invoke(channel, request)).rejects.toMatchObject({+ code: 'INVALID_PARAMS',+ message: `[INVALID_PARAMS] ${message}`,+ });+ expect(deps.broadcast).not.toHaveBeenCalled();+ });++ it('guards local callers before reading or mutating preferences', async () => {+ const harness = new IpcHarness();+ const rejection = new Error('untrusted renderer');+ const deps = createDeps({+ assertTrustedCaller: vi.fn(() => {+ throw rejection;+ }),+ });+ registerNewMakerWorktreeBranchPreferenceHandler(harness, deps);++ await expect(+ harness.invoke(MAKER_INVOKE.APPLY_NEW_MAKER_WORKTREE_BRANCH_PREF, {+ baseRepo: '/tmp/repo',+ sourceBranch: 'main',+ }),+ ).rejects.toBe(rejection);+ expect(deps.applyPreference).not.toHaveBeenCalled();+ expect(deps.broadcast).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex c4d5ea8026..4044ca5a5e 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -134,9 +134,22 @@ export const MAKER_INVOKE = {* 被控端 handler 校验布尔后转发给**自身 renderer**(WORKTREE_PREF_APPLY),renderer* setWorktreePreference 按字段写真实草稿;变更经既有 SYNC_NEW_MAKER_DRAFT re-mirror +* NEW_MAKER_DRAFT_CHANGED 广播回控制端。入参 = { worktreeEnabled: boolean }。- * 旧被控端无此 channel → CHANNEL_NOT_ALLOWED → 控制端吞掉降级(勾选仅本次草稿生效)。+ * 旧被控端无此 channel → CHANNEL_NOT_ALLOWED → 控制端保留最后一次宿主镜像,+ * 不在控制端制造一份仅本次草稿生效的本地偏好。*/APPLY_NEW_MAKER_WORKTREE_PREF: 'maker:apply-new-maker-worktree-pref',+ /**+ * 读取工作端某仓库的新建 worktree 源分支选择。分支是 repo-scoped,不能并入+ * vendor/device 全局的 GET_NEW_MAKER_DEFAULTS。入参 = { baseRepo: string };+ * 未选择返回 null,否则返回 { baseRepo, sourceBranch, revision }。+ */+ GET_NEW_MAKER_WORKTREE_BRANCH_PREF: 'maker:get-new-maker-worktree-branch-pref',+ /**+ * 写穿工作端某仓库的新建 worktree 源分支选择。工作端接受后返回并广播权威+ * { baseRepo, sourceBranch, revision };同值写也推进该仓库 revision。+ * 入参 = { baseRepo: string, sourceBranch: string }。+ */+ APPLY_NEW_MAKER_WORKTREE_BRANCH_PREF: 'maker:apply-new-maker-worktree-branch-pref',LIST_AVAILABLE_AGENTS: 'maker:list-available-agents',/*** Palette `/` 命令三源 (palette refactor):@@ -792,6 +805,12 @@ export const MAKER_PUSH = {* 控制端直接复用 resolveDeviceLinkDraftDefaults)。本地窗口不消费(被控端是真相、不自镜像)。*/NEW_MAKER_DRAFT_CHANGED: 'maker:new-maker-draft:changed',+ /**+ * 工作端某仓库的新建 worktree 源分支选择变化。payload =+ * { baseRepo, sourceBranch, revision }。同时广播本地 renderer 与经 device-link+ * sessions topic 订阅该设备的控制端;消费方必须按 device/baseRepo/revision 收敛。+ */+ NEW_MAKER_WORKTREE_BRANCH_CHANGED: 'maker:new-maker-worktree-branch:changed',/*** 被控端会话「非选中模型」effort/fast 变更广播。带 sessionId → session:<id> topic,转发给打开* 该远程会话的控制端,刷新其显示镜像。payload =diff --git a/apps/desktop/src/main/maker-ipc/newMakerWorktreeBranchPreferenceHandler.ts b/apps/desktop/src/main/maker-ipc/newMakerWorktreeBranchPreferenceHandler.tsnew file mode 100644index 0000000000..ce832270be--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/newMakerWorktreeBranchPreferenceHandler.ts@@ -0,0 +1,92 @@+/**+ * Host-owned, repository-scoped New Maker source branch IPC.+ *+ * Local Cindy renderers and allowlisted device-link controllers use the same+ * GET/APPLY handlers. APPLY updates the host cache before broadcasting the+ * accepted snapshot to local renderers and subscribed controllers.+ */+import path from 'node:path';++import type { NewMakerWorktreeBranchPreferenceSnapshot } from '../maker-host/newMakerWorktreeBranchPreferenceCache.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { MAKER_INVOKE, MAKER_PUSH } from './channels.js';+import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';++const MAX_BASE_REPO_LENGTH = 4096;+const MAX_SOURCE_BRANCH_LENGTH = 1024;++export interface NewMakerWorktreeBranchPreferenceHandlerDeps {+ isDeviceLinkInvoke(): boolean;+ assertTrustedCaller(event: unknown): void;+ getPreference(baseRepo: string): NewMakerWorktreeBranchPreferenceSnapshot | null;+ applyPreference(input: {+ baseRepo: string;+ sourceBranch: string;+ }): NewMakerWorktreeBranchPreferenceSnapshot;+ broadcast(+ channel: typeof MAKER_PUSH.NEW_MAKER_WORKTREE_BRANCH_CHANGED,+ payload: NewMakerWorktreeBranchPreferenceSnapshot,+ ): void;+}++function requireRequest(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throwIpcError('INVALID_PARAMS', 'request required');+ }+ return value as Record<string, unknown>;+}++function requireBaseRepo(value: unknown): string {+ if (typeof value !== 'string') {+ throwIpcError('INVALID_PARAMS', 'baseRepo must be string');+ }+ const baseRepo = value.trim();+ if (!baseRepo || baseRepo.length > MAX_BASE_REPO_LENGTH || baseRepo.includes('\0')) {+ throwIpcError('INVALID_PARAMS', 'baseRepo is invalid');+ }+ if (!path.isAbsolute(baseRepo)) {+ throwIpcError('INVALID_PARAMS', 'baseRepo must be absolute');+ }+ return baseRepo;+}++function requireSourceBranch(value: unknown): string {+ if (typeof value !== 'string') {+ throwIpcError('INVALID_PARAMS', 'sourceBranch must be string');+ }+ const sourceBranch = value.trim();+ if (+ !sourceBranch ||+ sourceBranch.length > MAX_SOURCE_BRANCH_LENGTH ||+ sourceBranch.includes('\0')+ ) {+ throwIpcError('INVALID_PARAMS', 'sourceBranch is invalid');+ }+ return sourceBranch;+}++export function registerNewMakerWorktreeBranchPreferenceHandler(+ registry: IpcHandlerRegistry,+ deps: NewMakerWorktreeBranchPreferenceHandlerDeps,+): void {+ const assertOrigin = (event: unknown): void => {+ if (!deps.isDeviceLinkInvoke()) deps.assertTrustedCaller(event);+ };++ registry.handle(MAKER_INVOKE.GET_NEW_MAKER_WORKTREE_BRANCH_PREF, (event, request: unknown) => {+ assertOrigin(event);+ const baseRepo = requireBaseRepo(requireRequest(request).baseRepo);+ return deps.getPreference(baseRepo);+ });++ registry.handle(MAKER_INVOKE.APPLY_NEW_MAKER_WORKTREE_BRANCH_PREF, (event, request: unknown) => {+ assertOrigin(event);+ const record = requireRequest(request);+ const snapshot = deps.applyPreference({+ baseRepo: requireBaseRepo(record.baseRepo),+ sourceBranch: requireSourceBranch(record.sourceBranch),+ });+ deps.broadcast(MAKER_PUSH.NEW_MAKER_WORKTREE_BRANCH_CHANGED, snapshot);+ return snapshot;+ });+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex eb405d7f1c..0f8d0eb708 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -41,6 +41,7 @@ import {import { and, desc, eq, gte, inArray, isNull, sql } from 'drizzle-orm';import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';import { getActiveAppSession, getActiveDataOwnerPushStamp } from '../appSessionState.js';+import { upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs.js';import type { AgentMeta } from '../../renderer/lib/ccAgent.types';import {deriveAutoTitleSeed,@@ -274,6 +275,10 @@ import {setNewMakerDraftCache,setProviderModelMemoryCache,} from '../maker-host/newMakerDefaultsCache.js';+import {+ applyNewMakerWorktreeBranchPreference,+ getNewMakerWorktreeBranchPreference,+} from '../maker-host/newMakerWorktreeBranchPreferenceCache.js';import { withRehydrateCloseSuppressed } from '../maker-host/rehydrateCloseSuppression.js';import { handleCloseSessionRequest } from './closeSessionRequest.js';import {@@ -446,6 +451,7 @@ import { validateHandoffWorkingDir } from './handoffWorkingDir.js';import { registerProjectPluginPolicyHandlers } from './projectPluginPolicyHandlers.js';import { registerPrecreatedWorktreeDiscardHandler } from './precreatedWorktreeDiscardHandler.js';import { registerNewMakerWorktreePreferenceHandler } from './newMakerWorktreePreferenceHandler.js';+import { registerNewMakerWorktreeBranchPreferenceHandler } from './newMakerWorktreeBranchPreferenceHandler.js';import {resolveFreshSourceBranch,restoreMissingManagedWorktreeForSession,@@ -4836,6 +4842,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)broadcast: broadcastToAllWindows,});+ // worktree 源分支不是设备全局草稿字段,而是 canonical baseRepo scoped 的 host 真相。+ // 本地 renderer 与 device-link 控制端共用 GET/APPLY;APPLY 先落 main 进程缓存,再把+ // 权威 snapshot 同时广播给本地窗口和 sessions topic 订阅者。+ registerNewMakerWorktreeBranchPreferenceHandler(createElectronIpcHandlerRegistry(), {+ isDeviceLinkInvoke,+ assertTrustedCaller: (event) =>+ assertTrustedAppRendererEvent(+ event as Parameters<typeof assertTrustedAppRendererEvent>[0],+ ),+ getPreference: getNewMakerWorktreeBranchPreference,+ applyPreference: applyNewMakerWorktreeBranchPreference,+ broadcast: broadcastToAllWindows,+ });+// 旧控制端的 device-link 会话模型预设写穿兼容入口。转发给被控端 renderer 后,renderer 将值// 收敛到 providerModelMemory 全局预设,同时经 SYNC_SESSION_MODEL_PREF 回流供旧控制端的// session-scoped 镜像显示。新控制端统一走 APPLY_NEW_MAKER_DRAFT_PREF。@@ -6026,39 +6046,55 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};const makerSessionRegistry = createElectronIpcHandlerRegistry();- registerMakerSessionCreateHandler(makerSessionRegistry, {- // CREATE_SESSION 同样先走 remote ensure:remote draft (尤其 collab- // lead) 的 SSH 重连 / agent 安装 / codex daemon MCP 注入必须先于- // bootstrap, 否则 lead 首个 turn 没有 cindy_orca, 与 orca 架构文档的- // "session start/resume 前置" 契约不符。本地会话 ensure 内部直接返回。- bootstrapSession: async (co) => {- await ensureRemoteReadyForSessionStart({ createOpts: co });- return bootstrapSession(co);- },- markOrcaRoleIfNeeded,- markKnownNonOrcaIfApplicable,- allocateDialogueWorkspace: ensureDialogueWorkspaceDir,- createSessionId: createId,- now: Date.now,- withSessionLock: withSendToSessionLock,- sendWorkerReadyMessage: (session) => {- // Orca worker 首次创建时发一条初始化消息,强制 codex 写 rollout 文件,- // 避免 app 重启后 thread/resume 因 rollout 缺失而失败。- observeFireAndForgetSendOutcome(- session.send({ type: 'user', content: ORCA_WORKER_READY_MESSAGE }, { planMode: false }),- {- owner: 'orca-worker-ready',- entrypoint: 'CREATE_SESSION',- sessionId: session.id,- agentKind: session.agentKind,- action: 'worker-ready-placeholder',- context: `CREATE_SESSION/${session.id}/worker-ready-placeholder`,- },- );+ registerMakerSessionCreateHandler(+ makerSessionRegistry,+ {+ // CREATE_SESSION 同样先走 remote ensure:remote draft (尤其 collab+ // lead) 的 SSH 重连 / agent 安装 / codex daemon MCP 注入必须先于+ // bootstrap, 否则 lead 首个 turn 没有 cindy_orca, 与 orca 架构文档的+ // "session start/resume 前置" 契约不符。本地会话 ensure 内部直接返回。+ bootstrapSession: async (co) => {+ await ensureRemoteReadyForSessionStart({ createOpts: co });+ const result = await bootstrapSession(co);+ // maker:create-session 是手机 / device-link 的创建入口,不经过+ // local-db:sessions:create,因此后者维护 recent_workdirs 的逻辑不会运行。+ // worktree 两步流此时 co.workingDir 已是隔离目录;picker 需要记住用户选的+ // 项目根,而不是 auto-* 运行目录。worktreeStore 以同一预生成 sessionId+ // 保存了权威 baseRepo。先完成 best-effort upsert 再让 handler 广播 created,+ // 这样 renderer 收到广播重拉 recent 表时不会撞到写入竞态。+ if (co.workspaceKind !== 'dialogue' && !co.remoteHostId) {+ const recentProjectDir = worktreeStore.get(result.session.id)?.baseRepo+ ?? getManagedWorktreeBasePath(co.workingDir)+ ?? co.workingDir;+ await upsertRecentWorkdir(recentProjectDir);+ }+ return result;+ },+ markOrcaRoleIfNeeded,+ markKnownNonOrcaIfApplicable,+ allocateDialogueWorkspace: ensureDialogueWorkspaceDir,+ createSessionId: createId,+ now: Date.now,+ withSessionLock: withSendToSessionLock,+ sendWorkerReadyMessage: (session) => {+ // Orca worker 首次创建时发一条初始化消息,强制 codex 写 rollout 文件,+ // 避免 app 重启后 thread/resume 因 rollout 缺失而失败。+ observeFireAndForgetSendOutcome(+ session.send({ type: 'user', content: ORCA_WORKER_READY_MESSAGE }, { planMode: false }),+ {+ owner: 'orca-worker-ready',+ entrypoint: 'CREATE_SESSION',+ sessionId: session.id,+ agentKind: session.agentKind,+ action: 'worker-ready-placeholder',+ context: `CREATE_SESSION/${session.id}/worker-ready-placeholder`,+ },+ );+ },+ broadcastSessionCreated,+ logCreateSession: (fields) => log.info('create-session invoked', fields),+ warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),},- broadcastSessionCreated,- logCreateSession: (fields) => log.info('create-session invoked', fields),- warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),});registerPrecreatedWorktreeDiscardHandler(makerSessionRegistry, {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex f14ef8d9fb..a325db4fb5 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -595,6 +595,9 @@ const fanOutDeviceLinkResponsivenessChanged = createIpcFanOut('device-link:respo// 交给 renderer 调它原来的本地 setter。仅被控端进程会收到(控制端从不收 → 监听不误触发)。const fanOutMakerDraftPrefApply = createIpcFanOut('maker:draft-pref:apply');const fanOutMakerWorktreePrefApply = createIpcFanOut('maker:worktree-pref:apply');+const fanOutNewMakerWorktreeBranchChanged = createIpcFanOut(+ 'maker:new-maker-worktree-branch:changed',+);const fanOutMakerSessionPrefApply = createIpcFanOut('maker:session-pref:apply');// 跨 Agent 迁移项的 wire 形态(同 main/cross-agent-convert/types.ts 的 MigrationItem,@@ -1972,6 +1975,23 @@ contextBridge.exposeInMainWorld('electronAPI', {* renderer 收到后 patchDraft 写真实草稿。仅被控端进程消费。*/onMakerWorktreePrefApply: fanOutMakerWorktreePrefApply,+ /** 读取工作端 canonical baseRepo 对应的 live 源分支选择;未选择返回 null。 */+ getNewMakerWorktreeBranchPreference: (baseRepo: string): Promise<{+ baseRepo: string;+ sourceBranch: string;+ revision: number;+ } | null> => ipcRenderer.invoke('maker:get-new-maker-worktree-branch-pref', { baseRepo }),+ /** 写入工作端 repo-scoped 源分支选择并返回 host 接受后的权威 snapshot。 */+ applyNewMakerWorktreeBranchPreference: (+ baseRepo: string,+ sourceBranch: string,+ ): Promise<{ baseRepo: string; sourceBranch: string; revision: number }> =>+ ipcRenderer.invoke('maker:apply-new-maker-worktree-branch-pref', {+ baseRepo,+ sourceBranch,+ }),+ /** 本机或任一 device-link 控制端改动该工作端分支选择后的权威广播。 */+ onNewMakerWorktreeBranchChanged: fanOutNewMakerWorktreeBranchChanged,onMakerSessionPrefApply: fanOutMakerSessionPrefApply,binding: {diff --git a/apps/desktop/src/renderer/__tests__/branchPick.test.ts b/apps/desktop/src/renderer/__tests__/branchPick.test.tsindex c622ebd74f..669a5bea0e 100644--- a/apps/desktop/src/renderer/__tests__/branchPick.test.ts+++ b/apps/desktop/src/renderer/__tests__/branchPick.test.ts@@ -1,12 +1,9 @@/*** branchPick.test.ts — 分支区点选语义(纯函数)回归。*- * 语义契约(2026-07-29 用户裁决第二版,实测后定稿):- * - 分支菜单永远可点;勾选框**跟随用户的分支选择**双向联动(本次草稿内生效,- * 持久化档位由调用方 source 分档控制,不在本函数职责内)- * - OFF + 选非当前分支 → enable-worktree(从别的分支启动必须隔离)- * - ON + 选回当前 HEAD → disable-worktree(回到当前 checkout 直接启动,对称)- * - ON + 选其它分支 = 改源分支;选当前源分支(非 HEAD)= no-op+ * 语义契约:+ * - checkbox 是唯一能改动 worktree 勾选状态的入口;+ * - ON / OFF 时选分支都只改源分支,选当前源分支 no-op;* - 永远不产生"checkout 用户 checkout"的效果*/import { describe, expect, it } from 'vitest';@@ -32,55 +29,26 @@ describe('resolveBranchPick', () => {).toEqual({ kind: 'noop' });});- it('worktree ON: picking the repo HEAD branch leaves worktree (symmetric follow)', () => {- // 用户最初的吐槽点:从 worktree 切回 main 时勾选仍亮着。定稿语义:选回当前- // HEAD = 不再需要隔离,勾选跟随熄灭(仅本次草稿,不写记忆)。- expect(- resolveBranchPick(- { worktreeEnabled: true, currentBranch: 'main', sourceBranch: 'feat/x' },- 'main',- ),- ).toEqual({ kind: 'disable-worktree' });- // source 恰好等于 HEAD 时同理:选它 = 回当前 checkout。- expect(- resolveBranchPick(- { worktreeEnabled: true, currentBranch: 'main', sourceBranch: 'main' },- 'main',- ),- ).toEqual({ kind: 'disable-worktree' });- });-- it('worktree OFF: picking the repo HEAD branch is a no-op', () => {- expect(- resolveBranchPick(- { worktreeEnabled: false, currentBranch: 'main', sourceBranch: '' },- 'main',- ),- ).toEqual({ kind: 'noop' });+ it('worktree OFF: picking a branch only changes the future worktree source', () => {+ for (const { currentBranch, picked } of [+ { currentBranch: 'main', picked: 'feat/x' },+ { currentBranch: null, picked: 'feat/y' },+ ]) {+ expect(+ resolveBranchPick(+ { worktreeEnabled: false, currentBranch, sourceBranch: '' },+ picked,+ ),+ ).toEqual({ kind: 'set-source', branch: picked });+ }});- it('worktree OFF: picking another branch enables worktree from it', () => {+ it('worktree OFF: picking the already selected source is a no-op', () => {expect(resolveBranchPick(- { worktreeEnabled: false, currentBranch: 'main', sourceBranch: '' },+ { worktreeEnabled: false, currentBranch: 'main', sourceBranch: 'feat/x' },'feat/x',),- ).toEqual({ kind: 'enable-worktree', branch: 'feat/x' });- });-- it('detached HEAD (currentBranch=null): no "current branch" special cases fire', () => {- // OFF:任何选择都按隔离启动;ON:任何选择都只是改源,绝不因 null 误触发退出。- expect(- resolveBranchPick(- { worktreeEnabled: false, currentBranch: null, sourceBranch: '' },- 'main',- ),- ).toEqual({ kind: 'enable-worktree', branch: 'main' });- expect(- resolveBranchPick(- { worktreeEnabled: true, currentBranch: null, sourceBranch: 'feat/x' },- 'main',- ),- ).toEqual({ kind: 'set-source', branch: 'main' });+ ).toEqual({ kind: 'noop' });});});diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.tsindex 7f62984c08..00d2e7384f 100644--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts@@ -332,7 +332,7 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {// currentBranch=null 是合法的 detached HEAD,不等于“不是 git 仓库”。// 未勾选时仍展示 HEAD,用户才能从这里开启 worktree / 选择源分支。expect(worktreeChipsRowSource).toContain(- ": (currentBranch ?? 'HEAD');",+ "const branchLabel = sourceBranch || currentBranch || 'HEAD';",);expect(worktreeChipsRowSource).toContain('const showBranchChip = !advancedHidden && !!detect.data?.isGitRepo;',diff --git a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.tsindex c1805417dc..3a9c9c5ed0 100644--- a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts@@ -506,6 +506,20 @@ describe('newMakerDraft store', () => {}});+ it('通用草稿 patch 不能改动 worktree 偏好', async () => {+ vi.resetModules();+ const { getDraft, patchDraft, setWorktreePreference } = await loadModule();++ patchDraft({ worktreeEnabled: true, worktreePreferenceCustomized: true });+ expect(getDraft().worktreeEnabled).toBe(false);+ expect(getDraft().worktreePreferenceCustomized).toBe(false);++ setWorktreePreference(true);+ patchDraft({ worktreeEnabled: false, worktreePreferenceCustomized: false });+ expect(getDraft().worktreeEnabled).toBe(true);+ expect(getDraft().worktreePreferenceCustomized).toBe(true);+ });+it('旧 false 快照不固化默认,旧 true 迁移为显式 override', async () => {memStorage.setItem('xdt:newMakerDraft:v1',diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.tsindex acd50b357a..56cc524963 100644--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts@@ -175,37 +175,101 @@ describe('Shared create project picker', () => {);});- it('keeps the worktree checkbox owned by the user alone (2026-07-29 invariant, v2)', () => {- // 用户裁决(实测后第二版):勾选状态只属于用户——+ it('keeps the worktree checkbox owned by direct checkbox interaction alone', () => {+ // 勾选状态只属于用户——// 1) 组件内不存在任何 useEffect 自动改写 enabled 的路径(资格变化只禁用、// 不改状态;旧 handleAutoDisable 机制不得复活);- // 2) 用户点击 checkbox(source='chip')→ 写穿工作端记忆(本地专用单字段 setter /+ // 2) 用户点击 checkbox → 写穿工作端记忆(本地专用单字段 setter /// device-link 远程 apply-new-maker-worktree-pref);- // 3) 用户选分支(source='branch-pick')→ 勾选双向联动但仅本次草稿、不落记忆- // (route 侧 source !== 'chip' 直接 return);+ // 3) 分支选择只修改源分支,永远不调用 onEnabledChange;// 4) checkbox 原样直出记忆(播种无 baseRepo 点亮门槛),发送侧按// 「勾选 && baseRepo 就绪」静默降级,不报错拦截。expect(worktreeChipsSource).not.toContain('handleAutoDisable');expect(worktreeChipsSource).not.toMatch(/useEffect\([^)]*onEnabledChange/s);- expect(worktreeChipsSource).toContain("onToggle={(v) => onEnabledChange(v, 'chip')}");- expect(worktreeChipsSource).toContain("onEnabledChange(true, 'branch-pick')");- expect(worktreeChipsSource).toContain("onEnabledChange(false, 'branch-pick')");- expect(branchPickSource).toContain("kind: 'disable-worktree'");- expect(newMakerDraftRouteSource).toContain("if (source !== 'chip') return;");+ expect(worktreeChipsSource).toContain('onToggle={onEnabledChange}');+ expect(worktreeChipsSource).not.toContain("'branch-pick'");+ expect(branchPickSource).not.toContain("kind: 'enable-worktree'");+ expect(branchPickSource).not.toContain("kind: 'disable-worktree'");expect(newMakerDraftRouteSource).toContain("'maker:apply-new-maker-worktree-pref'");expect(newMakerDraftRouteSource).toContain('setWorktreePreference(enabled)');- expect(newMakerDraftRouteSource).toContain('setWtEnabled(worktreePref)');+ const toggleHandler = newMakerDraftRouteSource.slice(+ newMakerDraftRouteSource.indexOf('const handleWtEnabledChange = useCallback('),+ newMakerDraftRouteSource.indexOf('const handleWtSourceBranchChange = useCallback('),+ );+ expect(toggleHandler.indexOf('setWtEnabled(enabled)')).toBeGreaterThan(+ toggleHandler.indexOf("'maker:apply-new-maker-worktree-pref'"),+ );+ expect(newMakerDraftRouteSource).toContain(+ "if (typeof remotePreference === 'boolean') setWtEnabled(remotePreference);",+ );+ expect(newMakerDraftRouteSource).toContain(+ 'if (isDeviceLinkDraft) setWtEnabled(false);',+ );expect(newMakerDraftRouteSource).toContain('wt.enabled && wt.baseRepo');- expect(newMakerDraftRouteSource).not.toContain('worktreeMissingRepo');+ const sendGuard = newMakerDraftRouteSource.slice(+ newMakerDraftRouteSource.indexOf('if (selectedWorkingDir && !isRemoteProjectDraft && selectedWorktree.enabled) {'),+ newMakerDraftRouteSource.indexOf('const dataOwnerAtSend = getDataOwnerGeneration();'),+ );+ expect(sendGuard).toContain('worktreeMissingRepo');+ expect(sendGuard).toContain('!selectedWorktree.branchPreferenceReady');+ expect(sendGuard).toContain('selectedWorktree.supportsRecoveryKeyDiscard !== true');+ expect(sendGuard).toContain('return false;');+ });++ it('mirrors the repo-scoped source branch through the selected working device', () => {+ // baseRepo ready 后才读:本机走 preload,device-link 草稿走被控端 invoke。+ expect(newMakerDraftRouteSource).toContain(+ 'window.electronAPI.getNewMakerWorktreeBranchPreference(wtBaseRepo)',+ );+ expect(newMakerDraftRouteSource).toContain(+ "'maker:get-new-maker-worktree-branch-pref'",+ );+ // 选择同样写回工作端;两条路径返回的权威 snapshot 进入同一 revision fence。+ expect(newMakerDraftRouteSource).toContain(+ 'window.electronAPI.applyNewMakerWorktreeBranchPreference(',+ );+ expect(newMakerDraftRouteSource).toContain(+ "'maker:apply-new-maker-worktree-branch-pref'",+ );+ expect(newMakerDraftRouteSource).toContain(+ 'snapshot.revision < previous.revision',+ );+ expect(newMakerDraftRouteSource).toContain(+ 'sameDraftWorktreeBranchTarget(requestTarget, currentTarget)',+ );+ // 本机 push 与远端转发 push 都消费同名 host snapshot;远端额外按 deviceId 过滤。+ expect(newMakerDraftRouteSource).toContain(+ 'window.electronAPI.onNewMakerWorktreeBranchChanged(',+ );+ expect(newMakerDraftRouteSource).toContain(+ "push.channel !== 'maker:new-maker-worktree-branch:changed'",+ );+ expect(newMakerDraftRouteSource).toContain(+ 'push.deviceId !== target.deviceId',+ );+ // GET 未完成时不让 currentBranch 的自动填空覆盖宿主已保存值。+ expect(newMakerDraftRouteSource).toContain(+ 'disabled={wtCreating || (wtBaseRepo != null && !wtBranchPreferenceReady)}',+ );++ const branchHandler = newMakerDraftRouteSource.slice(+ newMakerDraftRouteSource.indexOf('const handleWtSourceBranchChange = useCallback('),+ newMakerDraftRouteSource.indexOf('const handleWtBaseRepoChange = useCallback('),+ );+ expect(branchHandler).not.toContain('setWtEnabled(');+ expect(branchHandler).not.toContain('setWorktreePreference(');});it('merges branch and worktree into a single joined pill (Claude Code style)', () => {// 2026-07-29 用户裁决:[⎇ 分支 │ ☑ worktree] 是一个 pill、两个点击区;- // 分支菜单永远可点(worktree 开不了的仓库除外);悬停任一半区时分隔线隐去。+ // 分支选择与 checkbox 独立,未勾时也可先选源分支;悬停任一半区时分隔线隐去。expect(worktreeChipsSource).toContain('function BranchWorktreeChip');expect(worktreeChipsSource).toContain('data-testid="create-agent-branch-worktree"');expect(worktreeChipsSource).toContain(- 'const branchInteractive = !disabled && (effectiveWorktreeEnabled || !switchDisabled)',+ 'const branchInteractive = !switchDisabled',+ );+ expect(worktreeChipsSource).toContain(+ "const branchLabel = sourceBranch || currentBranch || 'HEAD'",);expect(worktreeChipsSource).toContain('group-hover:opacity-0');expect(worktreeChipsSource).not.toContain('function BranchChip');@@ -220,8 +284,8 @@ describe('Shared create project picker', () => {expect(newMakerDraftRouteSource).toContain('deviceLinkReconnectEpoch={remoteDraftRefreshEpoch}',);- expect(worktreeChipsSource).toContain("sourceBranch || branches.current || 'HEAD'");- expect(worktreeChipsSource).not.toContain("sourceBranch || branches.current || 'main'");+ expect(worktreeChipsSource).toContain("sourceBranch || currentBranch || 'HEAD'");+ expect(worktreeChipsSource).not.toContain("sourceBranch || currentBranch || 'main'");});it('invalidates worktree probe-derived fields when the selected project changes', () => {@@ -658,6 +722,7 @@ describe('Shared create project picker', () => {"throw new Error(t('newChat.modelSelector.remoteLoadFailed'))",);expect(newMakerDraftRouteSource).toContain("remoteDraftState.status === 'error'");+ expect(newMakerDraftRouteSource).not.toContain('remoteDraftState.loaded');expect(newMakerDraftRouteSource).toContain("toast.error(t('ccAgent.draft.remoteDefaultsLoadFailed'))",);diff --git a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.tsindex 6176bc59ee..947b34e228 100644--- a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts@@ -15,7 +15,7 @@ const sessionViewSource = readFileSync(describe('NewMakerDraftRoute worktree send flow', () => {it('enters a real session before creating the worktree in the background', () => {- // 2026-07-29 状态契约:生效条件 = 勾选 && baseRepo 就绪(不合格静默普通启动)。+ // 发送门已保证用户勾选时资格就绪;副作用分支仍以勾选 + baseRepo 双重防御。const worktreeBranch = source.indexOf('if (!isRemoteProjectDraft && wt.enabled && wt.baseRepo) {',);@@ -35,6 +35,24 @@ describe('NewMakerDraftRoute worktree send flow', () => {expect(worktreeCreate).toBeGreaterThan(navigate);});+ it('never silently downgrades an explicit worktree request to a normal session', () => {+ const selected = source.indexOf('const selectedWorktree = { ...wtRef.current };');+ const guard = source.indexOf(+ 'if (selectedWorkingDir && !isRemoteProjectDraft && selectedWorktree.enabled) {',+ selected,+ );+ const markInFlight = source.indexOf('markSendInFlight(true);', guard);+ const guardedSource = source.slice(guard, markInFlight);++ expect(selected).toBeGreaterThan(-1);+ expect(guard).toBeGreaterThan(selected);+ expect(markInFlight).toBeGreaterThan(guard);+ expect(guardedSource).toContain('!selectedWorktree.baseRepo');+ expect(guardedSource).toContain('!selectedWorktree.branchPreferenceReady');+ expect(guardedSource).toContain('selectedWorktree.supportsRecoveryKeyDiscard !== true');+ expect(guardedSource).toContain('return false;');+ });+it('keeps the first message as a session draft when background worktree creation fails', () => {const worktreeCreate = source.indexOf('window.electronAPI.worktreeCreate');const failedCard = source.indexOf("status: 'failed'", worktreeCreate);diff --git a/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx b/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsxindex 20ba4119b3..ce5bfd0787 100644--- a/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx+++ b/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx@@ -6,17 +6,14 @@* 2026-07-29 用户裁决(对齐 Claude Code):分支与 worktree 合并为**一个** pill——* 左半分支区、竖分隔线、右半 checkbox + "worktree",两个点击区各管各的。*- * 状态不变量(2026-07-29 用户裁决,实测后第二版):**勾选状态只属于用户**——+ * 状态不变量:**勾选状态只属于用户**——* - 系统/环境因素(切项目、探测结果、播种)永远不改 checkbox;资格不满足只是* 禁用 + tooltip,发送时由上层按「勾选 && 合格」静默降级,记忆永不被抹;- * - 用户点击 checkbox 本体(source='chip')→ 改状态并写工作端勾选记忆;- * - 用户选分支(source='branch-pick')→ 勾选**跟随本次选择**双向联动- * (选非当前分支必须隔离 → 亮;选回当前 HEAD → 灭;见 branchPick.ts),- * 但只对本次草稿生效、不写记忆——分支选择表达的是"这一次从哪启动",- * 不是"以后都默认 worktree"。+ * - 唯一改动路径 = 用户点击 checkbox 本体,并写入工作端勾选记忆;+ * - 分支选择始终只修改 worktree 源分支,永远不联动 checkbox。*- * 分支区语义:菜单永远可点(资格允许时);未勾时菜单脚注说明"选其他分支将以- * worktree 隔离启动",已勾时脚注说明"选当前分支将退回直接启动"。+ * 分支区语义:始终选择新 worktree 的源分支;checkbox 只决定本次新 session 是否+ * 真正创建 worktree。两者是独立控制,允许用户先选分支、再决定是否隔离。** worktree 名称 **自动生成**(不暴露 UI),由 useSuggestName 拉取后透传给上层。*/@@ -59,14 +56,8 @@ export interface WorktreeChipsRowProps {onAddRemoteProject?: () => void;emptyProjectLabel?: string;enabled: boolean;- /**- * 用户切换 worktree。source 决定是否写工作端勾选记忆:- * - 'chip':点 checkbox 本体 → 持久化;- * - 'branch-pick':分支选择的双向联动(用户动作,但表达的是"这一次从哪启动")- * → 仅本次草稿,不落记忆。- * 系统/环境路径不得调用它替用户翻状态。- */- onEnabledChange: (v: boolean, source: 'chip' | 'branch-pick') => void;+ /** 用户点击 checkbox 本体切换 worktree。系统/分支路径不得调用。 */+ onEnabledChange: (v: boolean) => void;sourceBranch: string;onSourceBranchChange: (v: string) => void;onBaseRepoChange?: (baseRepo: string | null) => void;@@ -205,17 +196,12 @@ export function WorktreeChipsRow({// ── 分支 chip 状态 ──const currentBranch = detect.data?.currentBranch ?? null;- // worktree ON 显源分支,列表加载失败/未返回时回退 'HEAD'(与发送管线的源分支- // 回退值一致,表示当前 checkout 而不是猜测 main)—— ON 状态下 chip 是唯一的- // 分支入口,绝不能因加载失败而消失。OFF 显仓库当前 HEAD 分支;detached HEAD- // 没有分支名时仍显示 HEAD,让默认未勾选用户保有开启 worktree 的入口。- const branchLabel = effectiveWorktreeEnabled- ? sourceBranch || branches.current || 'HEAD'- : (currentBranch ?? 'HEAD');+ // 分支与 checkbox 独立:未勾时也要回显用户刚选的源分支,否则菜单虽然可点、+ // 选择后却仍显示当前 HEAD,看起来像没有生效。首次未选择时回退当前 checkout。+ const branchLabel = sourceBranch || currentBranch || 'HEAD';const showBranchChip = !advancedHidden && !!detect.data?.isGitRepo;- // 分支菜单永远可点(worktree 开不了的仓库除外——已在 worktree 内等场景选分支- // 无法产生任何效果,菜单保持只读展示)。- const branchInteractive = !disabled && (effectiveWorktreeEnabled || !switchDisabled);+ // 分支选择与 checkbox 是两条独立轴;仅环境不具备 worktree 资格或创建在途时禁用。+ const branchInteractive = !switchDisabled;const handleBranchPick = useCallback((picked: string) => {@@ -223,20 +209,9 @@ export function WorktreeChipsRow({{ worktreeEnabled: effectiveWorktreeEnabled, currentBranch, sourceBranch: branchLabel },picked,);- if (effect.kind === 'set-source') {- onSourceBranchChange(effect.branch);- } else if (effect.kind === 'enable-worktree') {- // 同帧一起写:sourceBranch 非空会让"worktree 开启后回填 current"的- // effect 自然跳过,不会覆盖用户的选择。branch-pick 档 → 不落记忆。- onEnabledChange(true, 'branch-pick');- onSourceBranchChange(effect.branch);- } else if (effect.kind === 'disable-worktree') {- // 选回当前 HEAD → 勾选跟随熄灭(仅本次草稿);清源分支,下次开启重新回填。- onEnabledChange(false, 'branch-pick');- onSourceBranchChange('');- }+ if (effect.kind === 'set-source') onSourceBranchChange(effect.branch);},- [effectiveWorktreeEnabled, currentBranch, branchLabel, onSourceBranchChange, onEnabledChange],+ [effectiveWorktreeEnabled, currentBranch, branchLabel, onSourceBranchChange],);const branchWorktree = showBranchChip ? (@@ -247,6 +222,7 @@ export function WorktreeChipsRow({branchesFailed={branches.failed}onRetryBranches={branches.refetch}checked={enabled}+ branchSourceSelected={!!sourceBranch}branchInteractive={branchInteractive}checkboxDisabled={switchDisabled}cantUseReason={cantUseReason ?? undefined}@@ -256,7 +232,7 @@ export function WorktreeChipsRow({// 上次拉取失败的话,重新打开菜单就自动重试一次,不逼用户去点重试项。if (branches.failed && !branches.loading) branches.refetch();}}- onToggle={(v) => onEnabledChange(v, 'chip')}+ onToggle={onEnabledChange}compact={compact}/>) : null;@@ -395,6 +371,7 @@ function BranchWorktreeChip({branchesFailed,onRetryBranches,checked,+ branchSourceSelected,branchInteractive,checkboxDisabled,cantUseReason,@@ -411,7 +388,9 @@ function BranchWorktreeChip({onRetryBranches: () => void;/** worktree 勾选状态(工作端记忆原样直出;禁用时也照常显示,不做视觉造假)。 */checked: boolean;- /** 分支菜单是否可开(仅已勾时 = 源分支选择器;未勾只读展示当前 HEAD)。 */+ /** 用户是否已经显式选择过源分支(用于区分 tooltip 与首次展示的当前 HEAD)。 */+ branchSourceSelected: boolean;+ /** 分支菜单是否可开(与 checkbox 状态独立)。 */branchInteractive: boolean;checkboxDisabled?: boolean;cantUseReason?: string;@@ -460,7 +439,7 @@ function BranchWorktreeChip({const branchTipped = (<Tiptext={- checked+ checked || branchSourceSelected? t('newChat.branchChip.sourceTooltip'): t('newChat.branchChip.currentTooltip')}@@ -512,13 +491,6 @@ function BranchWorktreeChip({</DropdownMenuItem>)))}- {/* 脚注说明双向联动语义:未勾 → 选其他分支将开 worktree;已勾 → 选回- 当前分支将退回直接启动。用户第一次遇到"勾选跟着分支走"时不至于意外。 */}- <div className="mt-1 border-t border-border px-3 pb-1 pt-1.5 text-[11px] leading-snug text-muted-foreground">- {checked- ? t('newChat.branchChip.exitWorktreeHint')- : t('newChat.branchChip.worktreeHint')}- </div></DropdownMenuContent></DropdownMenu>) : (diff --git a/apps/desktop/src/renderer/components/new-chat/branchPick.ts b/apps/desktop/src/renderer/components/new-chat/branchPick.tsindex 42edd6fbc2..656e009cfa 100644--- a/apps/desktop/src/renderer/components/new-chat/branchPick.ts+++ b/apps/desktop/src/renderer/components/new-chat/branchPick.ts@@ -1,21 +1,17 @@/*** branchPick — 分支区点选语义的纯函数(与 UI 解耦,便于单测)。*- * 2026-07-29 用户裁决(第二版,实测后定稿):分支菜单永远可点,勾选框**跟随用户的- * 分支选择**双向联动——这是用户亲手的动作,不算系统擅改;但联动只对本次草稿生效,- * **不写工作端勾选记忆**(记忆只在用户点 checkbox 本体时保存,见调用方 source 分档):- * - 选非当前分支 → 开 worktree 并以其为源(从别的分支启动必须隔离,- * 绝不 checkout 用户的 checkout);- * - 选回当前 HEAD 分支 → 关 worktree(回到当前 checkout 直接启动,对称);- * - worktree 已勾时选其它分支 = 改源分支;选当前源分支(非 HEAD)= no-op。- * - 系统/环境因素(切项目、探测结果、播种)永远无权触达本函数之外的开关路径。+ * worktree 勾选状态只由 checkbox 本体控制:+ * - 分支菜单始终只选择未来 worktree 的源分支,选当前源分支为 no-op;+ * - worktree 未勾时也允许先选源分支,但绝不能因此开启或关闭 worktree;+ * - 系统/环境因素(切项目、探测结果、播种)同样无权改动勾选状态。* - 永远不产生"checkout 用户 checkout"的效果(effect 种类里根本没有这个选项)。*/export interface BranchPickState {- /** worktree 勾选框当前显示状态(用户记忆或本次草稿内联动后的值)。 */+ /** worktree 勾选框当前显示状态(工作端保存的用户偏好)。 */worktreeEnabled: boolean;- /** 仓库当前 HEAD 分支;detached / 未知时为 null。 */+ /** 仓库当前 HEAD 分支;保留在决策输入中,但不得据此联动 checkbox。 */currentBranch: string | null;/** worktree 源分支(仅 worktreeEnabled 时有意义)。 */sourceBranch: string;@@ -23,20 +19,11 @@ export interface BranchPickState {export type BranchPickEffect =| { kind: 'noop' }- | { kind: 'set-source'; branch: string }- | { kind: 'enable-worktree'; branch: string }- | { kind: 'disable-worktree' };+ | { kind: 'set-source'; branch: string };export function resolveBranchPick(state: BranchPickState, picked: string): BranchPickEffect {- if (state.worktreeEnabled) {- // 选回当前 HEAD = 不再需要隔离,勾选跟随熄灭(解决「从 worktree 切回 main- // 仍勾着」的不对称);detached(currentBranch=null)时无"当前分支"可言,不触发。- if (state.currentBranch !== null && picked === state.currentBranch) {- return { kind: 'disable-worktree' };- }- if (picked === state.sourceBranch) return { kind: 'noop' };- return { kind: 'set-source', branch: picked };- }- if (state.currentBranch !== null && picked === state.currentBranch) return { kind: 'noop' };- return { kind: 'enable-worktree', branch: picked };+ // ON / OFF 都只改源分支。effect union 刻意没有 enable / disable,从类型层保证+ // 分支选择无法联动 checkbox。+ if (picked === state.sourceBranch) return { kind: 'noop' };+ return { kind: 'set-source', branch: picked };}diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex 18f872a060..b5013ff962 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -233,6 +233,43 @@ import { revealOrcaWorkersTab } from '@/features/right-sidebar/plugins/orca-workconst log = createLogger('NewMakerDraftRoute');const IS_MAC_PLATFORM = typeof window !== 'undefined' && window.electronAPI?.platform === 'darwin';++interface DraftWorktreeBranchTarget {+ /** null = 当前电脑;string = device-link 被控工作端。 */+ deviceId: string | null;+ baseRepo: string | null;+}++interface DraftWorktreeBranchSync {+ deviceId: string | null;+ baseRepo: string;+ /** 工作端为该 canonical repo 维护的单调递增 revision;-1 表示 GET 未命中/不可用。 */+ revision: number;+}++function sameDraftWorktreeBranchTarget(+ left: DraftWorktreeBranchTarget,+ right: DraftWorktreeBranchTarget,+): boolean {+ return left.deviceId === right.deviceId && left.baseRepo === right.baseRepo;+}++function parseDraftWorktreeBranchSnapshot(+ value: unknown,+): NewMakerWorktreeBranchPreferenceSnapshot | null {+ if (!value || typeof value !== 'object') return null;+ const candidate = value as Partial<NewMakerWorktreeBranchPreferenceSnapshot>;+ if (+ typeof candidate.baseRepo !== 'string'+ || candidate.baseRepo.length === 0+ || typeof candidate.sourceBranch !== 'string'+ || candidate.sourceBranch.length === 0+ || typeof candidate.revision !== 'number'+ || !Number.isSafeInteger(candidate.revision)+ || candidate.revision < 0+ ) return null;+ return candidate as NewMakerWorktreeBranchPreferenceSnapshot;+}// F-COLLAB (2026-05): 老的 vendor='orca' 入口已退役,OrcaHeaderStrip 组件随之// 删除(它是给 isOrca 分支的 ChatInput.topSlot 用的)。Lead/Worker 协作组合现在// 由 ChatInput「+」菜单里的协同模式项控制,Lead 是当前 vendor 本身,@@ -611,6 +648,15 @@ export function NewMakerDraftRoute() {const [wtSupportsRecoveryKeyDiscard, setWtSupportsRecoveryKeyDiscard] = useState<boolean | null>(null,);+ // repo-scoped 分支偏好以工作端 main 为权威。target ref 在换设备 / repo 的同步动作里先行+ // 改写,挡住 React commit 前一瞬间到达的旧 GET / APPLY / push;seq 另挡异步 GET 晚到。+ const wtBranchTargetRef = useRef<DraftWorktreeBranchTarget>({+ deviceId: null,+ baseRepo: null,+ });+ const wtBranchReadSeqRef = useRef(0);+ const wtBranchSyncRef = useRef<DraftWorktreeBranchSync | null>(null);+ const [wtBranchSync, setWtBranchSync] = useState<DraftWorktreeBranchSync | null>(null);// F-COLLAB: 协同模式状态(enabled + worker 类型)直接读自 draft store,// 和 workingDir 走同一份 localStorage,重启 / 切走再回都能恢复。// 协同与项目/对话形态正交:两种草稿都向 ChatInput 提供入口;项目读项目级策略,@@ -691,6 +737,67 @@ export function NewMakerDraftRoute() {* 有没有项目只决定 workspaceKind 是 'project' 还是 'dialogue'。*/const isDeviceLinkDraft = effectiveDeviceLinkDeviceId != null;+ const wtBranchTarget: DraftWorktreeBranchTarget = {+ deviceId: effectiveDeviceLinkDeviceId ?? null,+ baseRepo: wtBaseRepo,+ };+ wtBranchTargetRef.current = wtBranchTarget;+ const wtBranchPreferenceReady = wtBaseRepo != null+ && wtBranchSync?.deviceId === wtBranchTarget.deviceId+ && wtBranchSync.baseRepo === wtBaseRepo;++ /**+ * 权威 snapshot 的统一落点。GET、APPLY response、本地 push、远端 push 全走这一道:+ * 设备/repo 必须仍是当前 target;同 target 只接受不小于已接收 host revision 的值。+ * APPLY response 与它的 push echo revision 相等是合法的幂等重复。+ */+ const acceptWtBranchSnapshot = useCallback((+ requestTarget: DraftWorktreeBranchTarget,+ rawSnapshot: unknown,+ ): boolean => {+ const snapshot = parseDraftWorktreeBranchSnapshot(rawSnapshot);+ if (!snapshot || !requestTarget.baseRepo) return false;+ const currentTarget = wtBranchTargetRef.current;+ if (!sameDraftWorktreeBranchTarget(requestTarget, currentTarget)) return false;+ if (snapshot.baseRepo !== currentTarget.baseRepo) return false;++ const previous = wtBranchSyncRef.current;+ if (+ previous+ && previous.deviceId === currentTarget.deviceId+ && previous.baseRepo === snapshot.baseRepo+ && snapshot.revision < previous.revision+ ) return false;++ const next: DraftWorktreeBranchSync = {+ deviceId: currentTarget.deviceId,+ baseRepo: snapshot.baseRepo,+ revision: snapshot.revision,+ };+ wtBranchSyncRef.current = next;+ setWtBranchSync(next);+ setWtSourceBranch(snapshot.sourceBranch);+ return true;+ }, []);++ /** GET 返回 null / 旧工作端无 channel 时也解除短暂 loading,但不伪造宿主 revision。 */+ const markWtBranchTargetReady = useCallback((target: DraftWorktreeBranchTarget) => {+ if (!target.baseRepo) return;+ if (!sameDraftWorktreeBranchTarget(target, wtBranchTargetRef.current)) return;+ const previous = wtBranchSyncRef.current;+ if (+ previous+ && previous.deviceId === target.deviceId+ && previous.baseRepo === target.baseRepo+ ) return;+ const next: DraftWorktreeBranchSync = {+ deviceId: target.deviceId,+ baseRepo: target.baseRepo,+ revision: -1,+ };+ wtBranchSyncRef.current = next;+ setWtBranchSync(next);+ }, []);/*** 远程草稿的附件闸门:**先选设备、之后再拖进来的**路径型附件同样进不了对端(Codex review P1)。*@@ -1260,17 +1367,83 @@ export function NewMakerDraftRoute() {}, [isDeviceLinkDraft, effectiveDeviceLinkDeviceId, capabilityAgentKind, capabilities]);// ── worktree 勾选 = 工作端记忆的镜像(2026-07-29 用户裁决:状态只属于用户) ────- // 本地草稿读本地 draft.worktreeEnabled;device-link 远程草稿读被控端镜像- // (remoteDraftState.value.worktreeEnabled,vendor 无关根字段,拉取完成前保持关,- // 不闪开)。checkbox **原样直出**记忆——不做 baseRepo/资格点亮门槛、没有任何- // 自动开关;环境合格性只影响 checkbox 禁用态与发送时是否真的走 worktree- // (handleSend 按「勾选 && baseRepo 就绪」静默降级,绝不报错拦截、绝不改记忆)。- const worktreePref = isDeviceLinkDraft- ? remoteDraftState.value?.worktreeEnabled === true- : draft.worktreeEnabled;+ // 本地草稿读本地 draft.worktreeEnabled;device-link 远程草稿只接受被控端明确返回的+ // boolean(remoteDraftState.value.worktreeEnabled,vendor 无关根字段)。同一设备重连时+ // 缺字段 / 拉取失败保留最后镜像;切到新设备时先回到默认未勾选。checkbox **原样直出**+ // 记忆——不做 baseRepo/资格点亮门槛、没有任何自动开关。环境合格性只影响+ // checkbox 禁用态;用户已勾选且当前项目尚不能创建 worktree 时,handleSend+ // 必须保留草稿并提示,不能静默创建普通 session,也不能改写用户记忆。useEffect(() => {- setWtEnabled(worktreePref);- }, [isDeviceLinkDraft, effectiveDeviceLinkDeviceId, worktreePref]);+ if (!isDeviceLinkDraft) {+ setWtEnabled(draft.worktreeEnabled);+ return;+ }+ if (remoteDraftState.status !== 'ready') return;+ const remotePreference = remoteDraftState.value?.worktreeEnabled;+ if (typeof remotePreference === 'boolean') setWtEnabled(remotePreference);+ }, [isDeviceLinkDraft, draft.worktreeEnabled, remoteDraftState]);+ // 放在同步 effect 后面:切设备的首帧 remoteDraftState 可能仍属于上一台设备,+ // 先处理旧快照再重置,保证它不能把新设备的默认 false 覆盖回去。+ useEffect(() => {+ if (isDeviceLinkDraft) setWtEnabled(false);+ }, [isDeviceLinkDraft, effectiveDeviceLinkDeviceId]);++ // ── worktree 源分支 = 工作端 repo-scoped 偏好镜像 ─────────────────────+ // detect-cwd 给出 canonical baseRepo 后再读;本地走 preload,device-link 草稿走+ // 被控端同名 invoke。seq + target ref 保证切设备/项目后的旧回包不能复活旧分支。+ useEffect(() => {+ if (!wtBaseRepo) return;+ const target: DraftWorktreeBranchTarget = {+ deviceId: effectiveDeviceLinkDeviceId ?? null,+ baseRepo: wtBaseRepo,+ };+ const seq = ++wtBranchReadSeqRef.current;+ let cancelled = false;+ const read = target.deviceId+ ? window.electronAPI.deviceLink.invoke(+ target.deviceId,+ 'maker:get-new-maker-worktree-branch-pref',+ [{ baseRepo: wtBaseRepo }],+ )+ : window.electronAPI.getNewMakerWorktreeBranchPreference(wtBaseRepo);+ void read+ .then((snapshot) => {+ if (cancelled || seq !== wtBranchReadSeqRef.current) return;+ if (snapshot != null && acceptWtBranchSnapshot(target, snapshot)) return;+ markWtBranchTargetReady(target);+ })+ .catch(() => {+ if (cancelled || seq !== wtBranchReadSeqRef.current) return;+ // 旧工作端无 channel / 瞬时断链时保留原有「当前分支」回退能力;重连代次会重读。+ markWtBranchTargetReady(target);+ });+ return () => {+ cancelled = true;+ };+ }, [+ wtBaseRepo,+ effectiveDeviceLinkDeviceId,+ remoteDraftRefreshEpoch,+ acceptWtBranchSnapshot,+ markWtBranchTargetReady,+ ]);++ // 当前电脑其它窗口 / mobile 控制端改分支后,本地 main 广播权威 snapshot。+ useEffect(() => window.electronAPI.onNewMakerWorktreeBranchChanged((snapshot) => {+ const target = wtBranchTargetRef.current;+ if (target.deviceId !== null || !target.baseRepo) return;+ acceptWtBranchSnapshot(target, snapshot);+ }), [acceptWtBranchSnapshot]);++ // device-link 草稿只接收当前目标设备转发的同名广播;payload 内 baseRepo + host+ // revision 仍交统一接受器校验,不能只凭 channel 就覆盖当前 UI。+ useEffect(() => window.electronAPI.deviceLink.onRemotePush((push) => {+ const target = wtBranchTargetRef.current;+ if (!target.deviceId || !target.baseRepo) return;+ if (push.deviceId !== target.deviceId) return;+ if (push.channel !== 'maker:new-maker-worktree-branch:changed') return;+ acceptWtBranchSnapshot(target, push.payload);+ }), [acceptWtBranchSnapshot]);// modelMemoryOverride:非选中行读镜像、改动经隧道写穿被控端(active=false)。providerId 由// ModelSelector 按行传入(每行各自的供应商)。写失败(旧版被控端 / 离线)静默吞 —— 乐观本地镜像@@ -1586,6 +1759,10 @@ export function NewMakerDraftRoute() {if (deviceChanged || workingDirChanged) {// worktreeEnabled is the user's working-device preference, not repo metadata.// Keep it across target changes; only invalidate the probed repository/branch.+ wtBranchReadSeqRef.current += 1;+ wtBranchTargetRef.current = { deviceId: req.deviceId, baseRepo: null };+ wtBranchSyncRef.current = null;+ setWtBranchSync(null);setWtBaseRepo(null);setWtSourceBranch('');setWtSupportsRecoveryKeyDiscard(null);@@ -2118,39 +2295,76 @@ export function NewMakerDraftRoute() {[handleWorkingDirChange],);- // 用户切换 worktree(2026-07-29 实测后第二版):- // - source='chip'(点 checkbox 本体)→ 写穿「工作端勾选记忆」——本地草稿写本地- // newMakerDraft 根字段;device-link 远程草稿写到被控端(状态归工作端所有,- // 控制端只是远程操作器,与手机端同语义);- // - source='branch-pick'(分支选择的双向联动)→ 仅本次草稿的 UI 态,不落记忆- // ——分支选择表达"这一次从哪启动",不改全局默认。- // 系统/环境路径没有任何入口能触达这里(不变量)。- const handleWtEnabledChange = useCallback(- (enabled: boolean, source: 'chip' | 'branch-pick') => {- setWtEnabled(enabled);- if (source !== 'chip') return;- if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {- remoteDraftRevisionRef.current += 1;- window.electronAPI.deviceLink- .invoke(effectiveDeviceLinkDeviceId, 'maker:apply-new-maker-worktree-pref', [- { worktreeEnabled: enabled },- ])- .catch(() => {- // 旧版被控端无此 channel(CHANNEL_NOT_ALLOWED)/ 隧道瞬断 → 勾选仅本次草稿- // 生效,不打断用户;被控端后续 push 回流可能把 UI 收敛回旧值,属可接受降级。- });- return;- }- setWorktreePreference(enabled);- },- [isDeviceLinkDraft, effectiveDeviceLinkDeviceId],- );+ // 用户点击 checkbox 是唯一改动路径。本地草稿直接写工作端偏好;+ // device-link 草稿先把操作交给被控端,只有被控端接受后才更新控制端+ // 显示镜像。分支、项目和资格变化都不能调用此回调。+ const handleWtEnabledChange = useCallback((enabled: boolean) => {+ if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {+ const writeRevision = remoteDraftRevisionRef.current + 1;+ remoteDraftRevisionRef.current = writeRevision;+ window.electronAPI.deviceLink+ .invoke(effectiveDeviceLinkDeviceId, 'maker:apply-new-maker-worktree-pref', [+ { worktreeEnabled: enabled },+ ])+ .then(() => {+ // 若权威 push 已先到,它已推进 revision 并收敛了 UI;+ // 只在没有更新回流时用本次宿主接受结果填充镜像。+ if (remoteDraftRevisionRef.current === writeRevision) setWtEnabled(enabled);+ })+ .catch(() => {+ // 旧版被控端无此 channel / 隧道瞬断:保留被控端上次的真实值,+ // 不在控制端制造一份仅本地生效的假偏好。+ });+ return;+ }+ setWtEnabled(enabled);+ setWorktreePreference(enabled);+ }, [isDeviceLinkDraft, effectiveDeviceLinkDeviceId]);const handleWtSourceBranchChange = useCallback((sourceBranch: string) => {- setWtSourceBranch(sourceBranch);- }, []);+ const normalized = sourceBranch.trim();+ const target = wtBranchTargetRef.current;+ // GET 尚未完成时 WorktreeChipsRow 可能尝试用 currentBranch 自动填空;先忽略,避免它+ // 抢在权威 repo 偏好返回前把已保存的选择覆盖掉。控件此时也会短暂 disabled。+ if (!normalized || !target.baseRepo || !wtBranchPreferenceReady) return;++ const apply = target.deviceId+ ? window.electronAPI.deviceLink.invoke(+ target.deviceId,+ 'maker:apply-new-maker-worktree-branch-pref',+ [{ baseRepo: target.baseRepo, sourceBranch: normalized }],+ )+ : window.electronAPI.applyNewMakerWorktreeBranchPreference(+ target.baseRepo,+ normalized,+ );+ void apply+ .then((snapshot) => {+ acceptWtBranchSnapshot(target, snapshot);+ })+ .catch(() => {+ // 兼容尚无 repo-scoped preference channel 的旧工作端:仍允许本次草稿选择分支。+ // 新工作端成功路径只接受 host snapshot/push,不在控制端制造第二份权威状态。+ if (sameDraftWorktreeBranchTarget(target, wtBranchTargetRef.current)) {+ setWtSourceBranch(normalized);+ }+ });+ }, [acceptWtBranchSnapshot, wtBranchPreferenceReady]);const handleWtBaseRepoChange = useCallback((baseRepo: string | null) => {+ const nextTarget: DraftWorktreeBranchTarget = {+ deviceId: effectiveDeviceLinkDeviceId ?? null,+ baseRepo,+ };+ if (+ wtBaseRepo === baseRepo+ && sameDraftWorktreeBranchTarget(nextTarget, wtBranchTargetRef.current)+ ) return;+ wtBranchReadSeqRef.current += 1;+ wtBranchTargetRef.current = nextTarget;+ wtBranchSyncRef.current = null;+ setWtBranchSync(null);+ setWtSourceBranch('');setWtBaseRepo(baseRepo);- }, []);+ }, [effectiveDeviceLinkDeviceId, wtBaseRepo]);const handleWtRecoveryKeyDiscardSupportChange = useCallback((supported: boolean | null) => {setWtSupportsRecoveryKeyDiscard(supported);}, []);@@ -2175,6 +2389,7 @@ export function NewMakerDraftRoute() {sourceBranch: wtSourceBranch,baseRepo: wtBaseRepo,supportsRecoveryKeyDiscard: wtSupportsRecoveryKeyDiscard,+ branchPreferenceReady: wtBranchPreferenceReady,});wtRef.current = {enabled: wtEnabled,@@ -2182,6 +2397,7 @@ export function NewMakerDraftRoute() {sourceBranch: wtSourceBranch,baseRepo: wtBaseRepo,supportsRecoveryKeyDiscard: wtSupportsRecoveryKeyDiscard,+ branchPreferenceReady: wtBranchPreferenceReady,};// ─── Send 拦截:vendorAuthGate → createSession → send / background worktree ──@@ -2294,6 +2510,21 @@ export function NewMakerDraftRoute() {// 改动;若异步块稍后再读 live ref,会把旧 workingDir 与新 baseRepo 拼成一次// 混合目标创建。这里与 selectedWorkingDir 同步快照,保证整笔创建目标一致。const selectedWorktree = { ...wtRef.current };+ // worktree 是用户对本次 project session 的明确选择。探测、分支偏好或远端+ // recovery 能力尚未就绪时保留输入并提示;绝不能把勾选静默降级成普通 session。+ if (selectedWorkingDir && !isRemoteProjectDraft && selectedWorktree.enabled) {+ if (!selectedWorktree.baseRepo) {+ toast.error(t('ccAgent.draft.worktreeMissingRepo'));+ return false;+ }+ if (+ !selectedWorktree.branchPreferenceReady+ || (isDeviceLinkDraft && selectedWorktree.supportsRecoveryKeyDiscard !== true)+ ) {+ toast.error(t('ccAgent.draft.deviceStillLoading'));+ return false;+ }+ }const dataOwnerAtSend = getDataOwnerGeneration();const isCurrentDataOwner = () =>dataOwnerAtSend.dataOwnerId === dataOwnerId &&@@ -2353,8 +2584,8 @@ export function NewMakerDraftRoute() {}| undefined;// 生效条件 = 勾选 && baseRepo 已就绪 && 被控端明确支持 recoveryKey discard。- // 旧 Desktop 可能接受未知 recoveryKey 却不持久化,不能把它当成支持端发起- // 预创建;能力不合格 / 探测未回时静默按普通方式启动,不报错不改勾选记忆。+ // 上面的发送门已阻止不完整状态;这里仍保留完整条件作副作用前的防御。+ // 旧 Desktop 可能接受未知 recoveryKey 却不持久化,不能把它当成支持端发起预创建。if (effectiveWorkingDir &&wt.enabled &&@@ -2620,8 +2851,8 @@ export function NewMakerDraftRoute() {const sessionId = makeDraftSessionId();const workingDir = selectedWorkingDir;const wt = selectedWorktree;- // 生效条件 = 勾选 && baseRepo 已就绪;不合格时静默普通启动(同 device-link 分支,- // 见 2026-07-29 状态不变量:勾选记忆永不因环境被改动或报错拦截)。+ // 生效条件 = 勾选 && baseRepo 已就绪。上面的发送门已阻止不完整状态;+ // 这里保留完整条件作创建副作用前的防御,且始终不改写勾选记忆。if (!isRemoteProjectDraft && wt.enabled && wt.baseRepo) {const baseRepo = wt.baseRepo;@@ -3586,7 +3817,7 @@ export function NewMakerDraftRoute() {worktreeDisabled={isRemoteProjectDraft}deviceLinkDeviceId={effectiveDeviceLinkDeviceId ?? null}deviceLinkReconnectEpoch={remoteDraftRefreshEpoch}- disabled={wtCreating}+ disabled={wtCreating || (wtBaseRepo != null && !wtBranchPreferenceReady)}/></div><ThemeBrandLockupdiff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 0bb5d74af6..eda5ec4ecc 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5136,9 +5136,7 @@"loading": "Loading branches…","loadFailed": "Failed to load branches — tap to retry","currentTooltip": "Current branch",- "sourceTooltip": "Worktree source branch",- "worktreeHint": "Picking another branch starts this chat in an isolated worktree",- "exitWorktreeHint": "Picking the current branch leaves worktree and starts directly on it"+ "sourceTooltip": "Worktree source branch"},"folderPicker": {"selectFolder": "Select folder",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex e848796065..001f94bdc3 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5134,9 +5134,7 @@"loading": "ブランチを読み込み中…","loadFailed": "ブランチの読み込みに失敗しました。タップして再試行","currentTooltip": "現在のブランチ",- "sourceTooltip": "worktree のソースブランチ",- "worktreeHint": "別のブランチを選ぶと worktree 分離で開始します",- "exitWorktreeHint": "現在のブランチを選ぶと worktree を解除し、そのまま開始します"+ "sourceTooltip": "worktree のソースブランチ"},"folderPicker": {"selectFolder": "フォルダを選択",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 83748a3a08..5d24ecae49 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5134,9 +5134,7 @@"loading": "브랜치 불러오는 중…","loadFailed": "브랜치를 불러오지 못했습니다. 눌러서 다시 시도","currentTooltip": "현재 브랜치",- "sourceTooltip": "worktree 소스 브랜치",- "worktreeHint": "다른 브랜치를 선택하면 worktree 격리로 시작합니다",- "exitWorktreeHint": "현재 브랜치를 선택하면 worktree를 해제하고 바로 시작합니다"+ "sourceTooltip": "worktree 소스 브랜치"},"folderPicker": {"selectFolder": "폴더 선택",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex e2a64079ed..9a4590aa1d 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5134,9 +5134,7 @@"loading": "加载分支中…","loadFailed": "分支列表加载失败,点此重试","currentTooltip": "当前分支",- "sourceTooltip": "worktree 源分支",- "worktreeHint": "选择其他分支将以 worktree 隔离启动",- "exitWorktreeHint": "选择当前分支将退出 worktree,直接在当前分支上启动"+ "sourceTooltip": "worktree 源分支"},"folderPicker": {"selectFolder": "选择文件夹",diff --git a/apps/desktop/src/renderer/state/newMakerDraft.ts b/apps/desktop/src/renderer/state/newMakerDraft.tsindex 24e04ca0ae..989786ac2a 100644--- a/apps/desktop/src/renderer/state/newMakerDraft.ts+++ b/apps/desktop/src/renderer/state/newMakerDraft.ts@@ -106,8 +106,9 @@ export interface NewMakerDraft {* 语义是「这台工作端上新建会话时 worktree 开关的默认状态」——桌面本机草稿与手机 /* 桌面控制端远程草稿读写同一份(读经 maker:get-new-maker-defaults 镜像,写经* maker:apply-new-maker-worktree-pref 写穿)。- * 只在用户**显式**切换开关时写入;资格探测失败(非 git 仓库 / 已在 worktree 内等)- * 触发的自动关闭只改 UI 态、不写这里,避免环境因素抹掉用户偏好。+ * 只在用户**显式**切换开关时写入;切项目、选分支、资格探测、重连等其它操作+ * 一律保持原值,避免环境因素抹掉用户偏好。+ * 直接复用 Cindy 现有 newMakerDraft 配置命名空间,不另建 worktree 专用配置。* 有效值由系统默认 + worktreePreferenceCustomized override 合成。*/worktreeEnabled: boolean;@@ -621,6 +622,10 @@ export function setWorktreePreference(enabled: boolean): void {export function patchDraft(patch: Partial<NewMakerDraft>): void {const normalizedPatch: Partial<NewMakerDraft> = { ...patch };+ // worktree 偏好只能经 setWorktreePreference 写入。把这条约束放在 store 边界,+ // 避免项目切换、草稿恢复或未来的通用 patch 调用方绕过「仅 checkbox 修改」契约。+ delete normalizedPatch.worktreeEnabled;+ delete normalizedPatch.worktreePreferenceCustomized;if ('workingDir' in normalizedPatch) {normalizedPatch.workingDir = normalizeDraftWorkingDir(normalizedPatch.workingDir);}@@ -667,11 +672,7 @@ export function patchDraft(patch: Partial<NewMakerDraft>): void {// 协同与项目/对话形态正交,切 workingDir 不再改 enabled。device-link 与 SSH 的 Worker// 创建和团队读写都在对应执行端完成;Worker 子会话不能嵌套协同,由会话侧入口判定兜住。currentDraft = next;- scheduleWrite({- preserveStoredWorktreePreference:- !('worktreeEnabled' in patch)- && !('worktreePreferenceCustomized' in patch),- });+ scheduleWrite({ preserveStoredWorktreePreference: true });emit();}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex cbd098bae8..4cfba4ce8a 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -44,6 +44,12 @@ type PendingRemotePrecreatedWorktreeTarget =type RemotePrecreatedWorktreeLedgerSnapshot =import('../shared/remotePrecreatedWorktreeLedger').RemotePrecreatedWorktreeLedgerSnapshot;+interface NewMakerWorktreeBranchPreferenceSnapshot {+ baseRepo: string;+ sourceBranch: string;+ revision: number;+}+/* ── Environment check ── */interface EnvCheckResult {@@ -2064,6 +2070,22 @@ interface ElectronAPI {/** 被控端本地 main → 自身 renderer:控制端写穿的「新建会话默认启用 worktree」(patchDraft 写真实草稿)。 */onMakerWorktreePrefApply: (cb: (payload: { worktreeEnabled: boolean }) => void) => () => void;+ /** 工作端 canonical baseRepo scoped 的新建 worktree 源分支;未选过返回 null。 */+ getNewMakerWorktreeBranchPreference: (+ baseRepo: string,+ ) => Promise<NewMakerWorktreeBranchPreferenceSnapshot | null>;++ /** 写穿本机工作端的源分支选择,返回 host 接受后的权威 snapshot。 */+ applyNewMakerWorktreeBranchPreference: (+ baseRepo: string,+ sourceBranch: string,+ ) => Promise<NewMakerWorktreeBranchPreferenceSnapshot>;++ /** 本机或远程控制端改动本工作端源分支后的权威广播。 */+ onNewMakerWorktreeBranchChanged: (+ cb: (snapshot: NewMakerWorktreeBranchPreferenceSnapshot) => void,+ ) => () => void;+/** 被控端本地 main → 自身 renderer:控制端写穿的会话「模型 effort/fast」pref(调本地 setter)。 */onMakerSessionPrefApply: (cb: (payload: {diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 34912b0924..7b48089ac4 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -31,6 +31,7 @@ import {ChevronsUpDown,Folder,FolderPlus,+ GitBranch,Image,Laptop,ListTodo,@@ -176,6 +177,7 @@ import {} from '@/session/newSessionPreferenceStore';import {remoteSessionStore,+ useRemoteNewMakerWorktreeBranchPreference,useRemoteNewMakerWorktreePreference,useRemoteSessions,} from '@/session/remoteSessionStore';@@ -268,19 +270,25 @@ import {type ProviderModelRow,} from '@/session/providerModelSections';import { ModelPickerSheet } from '@/session/ModelPickerSheet';+import { MobileChoicePickerList } from '@/session/MobileChoicePickerList';import { MobilePermissionPickerList } from '@/session/MobilePermissionPickerList';import { SheetModal } from '@/session/SheetModal';import { SheetSurface } from '@/session/SheetSurface';import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';import {+ applyWorktreePreferenceOnHost,buildWorktreeCreateRequest,formatWorktreeCreateFailure,resolveWorktreeEligibility,seedWorktreeEnabled,+ shouldAcceptWorktreeBranchListResult,+ shouldBlockNewSessionCreateForWorktree,shouldShowWorktreeToggle,worktreeEligibilityForTarget,worktreeEligibilityCaptionKey,worktreeEligibilityFromError,+ worktreeSourceBranchForTarget,+ type NewSessionWorktreeBranchSelectionSnapshot,type NewSessionWorktreeProbeSnapshot,} from '@/session/newSessionWorktree';import { mobileAgentLabel, mobileAgentVendor } from '@/session/sessionAgentSwitch';@@ -300,6 +308,13 @@ const COMPOSER_CARD_CHROME_HEIGHT = 78;// Android 的 SafeAreaView 已经包含状态栏顶部 inset,不能再叠加一档顶部留白。const NEW_SESSION_SCREEN_TOP_PADDING = Platform.OS === 'android' ? 0 : spacing.xl;+interface WorktreeBranchListSnapshot {+ target: { deviceId: string; workingDir: string };+ branches: string[];+ loading: boolean;+ failed: boolean;+}+export default function NewRemoteSessionScreen() {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();@@ -422,8 +437,27 @@ export default function NewRemoteSessionScreen() {// worktree 开关(project 模式 + 已选目录时显示):勾选值存工作端(get-new-maker-defaults// 播种 / 显式点击写穿),资格由 worktree:detect-cwd 探测(目录变化即重探,seq 防竞态)。const [worktreeProbe, setWorktreeProbe] = useState<NewSessionWorktreeProbeSnapshot | null>(null);+ const [worktreeDetectRetryNonce, setWorktreeDetectRetryNonce] = useState(0);+ const [worktreeBranchSelection, setWorktreeBranchSelection] =+ useState<NewSessionWorktreeBranchSelectionSnapshot | null>(null);+ const [worktreeBranchList, setWorktreeBranchList] =+ useState<WorktreeBranchListSnapshot | null>(null);+ const [worktreeBranchSheetOpen, setWorktreeBranchSheetOpen] = useState(false);+ const [worktreeBranchSheetSnap, setWorktreeBranchSheetSnap] =+ useState<ContextSheetSnap>('half');+ const [worktreeBranchPreferenceSavingKey, setWorktreeBranchPreferenceSavingKey] =+ useState<string | null>(null);+ const [worktreeBranchPreferenceReadyKey, setWorktreeBranchPreferenceReadyKey] =+ useState<string | null>(null);const worktreeDetectSeqRef = useRef(0);+ const worktreeBranchListSeqRef = useRef(0);+ const worktreeBranchPreferencePullSeqRef = useRef(0);+ const worktreeBranchPreferenceWriteSeqRef = useRef(0);+ const worktreeBranchTargetRef = useRef({ deviceId: '', workingDir: '' });const worktreeSeedSeqRef = useRef(0);+ const worktreePreferenceWriteSeqRef = useRef(0);+ const [worktreePreferenceSavingDeviceId, setWorktreePreferenceSavingDeviceId] =+ useState<string | null>(null);const [attachments, setAttachments] = useState<RemoteSerializedAttachment[]>([]);// create() 里 await 在途图片上传后闭包里的 attachments 已是旧值,经 ref 读最新列表。const attachmentsRef = useRef(attachments);@@ -815,21 +849,80 @@ export default function NewRemoteSessionScreen() {const agentLabel = mobileAgentLabel(draft.agentKind);// effect 在 commit 后才会把旧探测结果重置为 probing;render 期先按设备 + cwd 同步// 对齐 target,切项目/设备后立即创建也拿不到上一仓库的 baseRepo/sourceBranch。- const worktreeEligibility = worktreeEligibilityForTarget(worktreeProbe, {+ const worktreeTarget = {deviceId: selectedDeviceId ?? '',workingDir: draft.workspaceKind === 'project' ? draft.workingDir.trim() : '',- });+ };+ worktreeBranchTargetRef.current = worktreeTarget;+ const worktreeEligibility = worktreeEligibilityForTarget(worktreeProbe, worktreeTarget);+ const worktreeBranchBaseRepo = worktreeEligibility.status === 'eligible'+ ? worktreeEligibility.baseRepo+ : '';+ const remoteWorktreeBranchPreference = useRemoteNewMakerWorktreeBranchPreference(+ selectedDeviceId,+ worktreeBranchBaseRepo,+ );+ const worktreeSourceBranch = worktreeSourceBranchForTarget(+ worktreeBranchSelection,+ worktreeTarget,+ worktreeEligibility,+ );+ const worktreeBranchListMatchesTarget = worktreeBranchList != null+ && worktreeBranchList.target.deviceId === worktreeTarget.deviceId+ && worktreeBranchList.target.workingDir.trim() === worktreeTarget.workingDir.trim();+ const worktreeBranchOptions = useMemo(+ () => worktreeBranchListMatchesTarget+ ? worktreeBranchList.branches.map((branch) => ({ id: branch, label: branch }))+ : [],+ [worktreeBranchList, worktreeBranchListMatchesTarget],+ );// worktree 开关行:project + 已选目录才显示;老被控端(unsupported)整行隐藏。const worktreeRowVisible = shouldShowWorktreeToggle({workspaceKind: draft.workspaceKind,workingDir: draft.workingDir,eligibility: worktreeEligibility,});- const worktreeToggleDisabled = creating || worktreeEligibility.status !== 'eligible';+ const worktreePreferenceSaving =+ selectedDeviceId != null && worktreePreferenceSavingDeviceId === selectedDeviceId;+ const worktreeBranchPreferenceKey = selectedDeviceId && worktreeBranchBaseRepo+ ? `${selectedDeviceId}\u0000${worktreeBranchBaseRepo}`+ : '';+ // host cache 是 process-lifetime,连接代次也属于权威读取的 identity。桌面重启后+ // 即使 deviceId/repo 没变,也必须重新 GET,不能继续相信手机内存里的旧 revision。+ const worktreeBranchPreferenceSyncKey = worktreeBranchPreferenceKey+ ? `${worktreeBranchPreferenceKey}\u0000${connectionEpoch}\u0000${presenceVersion}`+ : '';+ const worktreeBranchPreferenceReady = worktreeBranchPreferenceSyncKey.length > 0+ && worktreeBranchPreferenceReadyKey === worktreeBranchPreferenceSyncKey;+ const worktreeBranchPreferenceSaving = worktreeBranchPreferenceKey.length > 0+ && worktreeBranchPreferenceSavingKey === worktreeBranchPreferenceKey;+ const worktreeToggleDisabled =+ creating+ || worktreePreferenceSaving+ || (worktreeEligibility.status !== 'eligible' && !worktreeEnabled);+ // 分支区与 checkbox 是两条独立轴:OFF 时也可先选源分支;保存 checkbox 偏好在途+ // 同样不影响只读的分支枚举。只有目标尚不具备 worktree 资格或创建在途时禁用。+ const worktreeBranchDisabled = creating+ || worktreeBranchPreferenceSaving+ || !worktreeBranchPreferenceReady+ || worktreeEligibility.status !== 'eligible';+ const worktreeBranchSheetVisible = worktreeBranchSheetOpen+ && worktreeEligibility.status === 'eligible'+ && worktreeBranchListMatchesTarget;// 勾选展示 = 工作端记忆**原样直出**(2026-07-29 用户裁决:状态只属于用户,系统不做- // 视觉折叠);资格不满足只体现为禁用 + caption,创建时按「勾选 && 合格」静默降级。+ // 视觉折叠);项目目标资格不满足时显示 caption 并阻止创建,不能静默降级普通目录。const worktreeChecked = worktreeEnabled;const worktreeCaptionKey = worktreeEligibilityCaptionKey(worktreeEligibility);+ const worktreeCreateBlocked = shouldBlockNewSessionCreateForWorktree({+ applicable: draft.workspaceKind === 'project' && draft.workingDir.trim().length > 0,+ enabled: worktreeEnabled,+ eligibility: worktreeEligibility,+ preferenceSaving: worktreePreferenceSaving,+ })+ || worktreeBranchPreferenceSaving+ || (worktreeEnabled+ && worktreeEligibility.status === 'eligible'+ && !worktreeBranchPreferenceReady);const createValidation = useMemo(() => validateNewSessionDraft(draft, draftContent),[draft, draftContent],@@ -875,7 +968,8 @@ export default function NewRemoteSessionScreen() {);const canCreate = (!createValidation || (voiceIsListening && createValidationIsMissingPayload))&& !creating- && !voiceIsProcessing;+ && !voiceIsProcessing+ && !worktreeCreateBlocked;const voiceIsBusy = voiceIsListening || voiceIsProcessing;// 录音计时(红点+m:ss 胶囊,与会话页/桌面同形态);pillWidth 同步驱动工具排占位。// counting 只认真实采集,启动链路(权限弹窗等)不计入时长,pending 期显示 0:00。@@ -1526,6 +1620,7 @@ export default function NewRemoteSessionScreen() {setWorkspacePickerOpen(false);setAgentPickerOpen(false);setPermissionSheetOpen(false);+ setWorktreeBranchSheetOpen(false);setModelSheetOpen(true);}, []);@@ -1534,6 +1629,7 @@ export default function NewRemoteSessionScreen() {setWorkspacePickerOpen(false);setAgentPickerOpen(false);setModelSheetOpen(false);+ setWorktreeBranchSheetOpen(false);setPermissionSheetSnap('half');setPermissionSheetOpen(true);}, []);@@ -1564,11 +1660,13 @@ export default function NewRemoteSessionScreen() {const cwd = draft.workspaceKind === 'project' ? draft.workingDir.trim() : '';const seq = ++worktreeDetectSeqRef.current;const target = { deviceId: selectedDeviceId ?? '', workingDir: cwd };+ let cancelled = false;+ let retryTimer: ReturnType<typeof setTimeout> | null = null;setWorktreeProbe({ target, eligibility: { status: 'probing' } });// Relay 离线时不把预期的 NOT_CONNECTED 固化成 detect-failed;online /// connectionEpoch / presenceVersion 变化后自动重探,覆盖手机重连和工作端// 重新上线两种路径。- if (!selectedDeviceId || !cwd || deviceLinkStatus !== 'online') return;+ if (!selectedDeviceId || !cwd || deviceLinkStatus !== 'online') return undefined;void withTransientRemoteRetry(async () => {await openLink(selectedDeviceId);return maker.worktree.detectCwd(cwd);@@ -1581,11 +1679,94 @@ export default function NewRemoteSessionScreen() {});}).catch((err: unknown) => {- if (seq !== worktreeDetectSeqRef.current) return;- setWorktreeProbe({- target,- eligibility: worktreeEligibilityFromError(err),- });+ if (cancelled || seq !== worktreeDetectSeqRef.current) return;+ const eligibility = worktreeEligibilityFromError(err);+ setWorktreeProbe({ target, eligibility });+ if (eligibility.status === 'recovering') {+ // 换网后 relay 可能已 online,但旧 peer link 仍在 ACK/握手恢复窗口;连接+ // epoch/presence 未必再次变化,不能要求用户重选目录才能触发下一轮探测。+ retryTimer = setTimeout(() => {+ if (!cancelled) setWorktreeDetectRetryNonce((value) => value + 1);+ }, 1_500);+ }+ });+ return () => {+ cancelled = true;+ if (retryTimer) clearTimeout(retryTimer);+ };+ }, [+ connectionEpoch,+ deviceLinkStatus,+ presenceVersion,+ worktreeDetectRetryNonce,+ selectedDeviceId,+ draft.workspaceKind,+ draft.workingDir,+ maker,+ openLink,+ ]);++ // 换设备 / 工作目录 = 换 branch target:关闭旧 sheet 并清掉显式选择与列表缓存。+ // render 期另有 worktreeSourceBranchForTarget fence,effect 落地前的首帧也不会串仓。+ useEffect(() => {+ worktreeBranchListSeqRef.current += 1;+ worktreeBranchPreferencePullSeqRef.current += 1;+ setWorktreeBranchPreferenceReadyKey(null);+ setWorktreeBranchSheetOpen(false);+ setWorktreeBranchSelection(null);+ setWorktreeBranchList(null);+ }, [selectedDeviceId, draft.workspaceKind, draft.workingDir]);++ // Host 是 repo-scoped sourceBranch 的单一真相。先按 canonical baseRepo pull,随后+ // maker:new-maker-worktree-branch:changed push 会更新同一 store 镜像;旧 pull 由+ // host revision + 本地 target/seq 双重 fence 拒绝,不能盖过桌面端较新的选择。+ useEffect(() => {+ const seq = ++worktreeBranchPreferencePullSeqRef.current;+ if (+ !selectedDeviceId+ || deviceLinkStatus !== 'online'+ || worktreeEligibility.status !== 'eligible'+ ) return;+ const target = {+ deviceId: selectedDeviceId,+ workingDir: draft.workspaceKind === 'project' ? draft.workingDir.trim() : '',+ };+ const baseRepo = worktreeEligibility.baseRepo;+ const syncKey = worktreeBranchPreferenceSyncKey;+ // effect 发生前 render 已因 syncKey 不同而 fail closed;这里再清旧镜像,确保+ // 新 host 从 rev1 开始时不会被上一进程留下的 revN 挡掉。+ remoteSessionStore.clearNewMakerWorktreeBranchPreference(selectedDeviceId, baseRepo);+ void withTransientRemoteRetry(async () => {+ await openLink(selectedDeviceId);+ return maker.getNewMakerWorktreeBranchPref(baseRepo);+ }, { maxAttempts: 2 })+ .then((snapshot) => {+ const latestTarget = worktreeBranchTargetRef.current;+ if (!shouldAcceptWorktreeBranchListResult({+ requestSeq: seq,+ latestSeq: worktreeBranchPreferencePullSeqRef.current,+ requestTarget: target,+ latestTarget,+ })) return;+ if (snapshot === null) {+ remoteSessionStore.clearNewMakerWorktreeBranchPreference(selectedDeviceId, baseRepo);+ } else {+ if (snapshot.baseRepo !== baseRepo) return;+ remoteSessionStore.setNewMakerWorktreeBranchPreference(selectedDeviceId, snapshot);+ }+ setWorktreeBranchPreferenceReadyKey(syncKey);+ })+ .catch(() => {+ const latestTarget = worktreeBranchTargetRef.current;+ if (!shouldAcceptWorktreeBranchListResult({+ requestSeq: seq,+ latestSeq: worktreeBranchPreferencePullSeqRef.current,+ requestTarget: target,+ latestTarget,+ })) return;+ // 老被控端无新 channel 时允许用 detect-cwd 当前分支兼容运行;断线会被+ // 页面其它连接门槛拦住,下一连接代次重新读取。+ setWorktreeBranchPreferenceReadyKey(syncKey);});}, [connectionEpoch,@@ -1596,11 +1777,158 @@ export default function NewRemoteSessionScreen() {draft.workingDir,maker,openLink,+ worktreeEligibility,+ worktreeBranchPreferenceSyncKey,+ ]);++ // pull / push / 手机 apply 成功都只写 store;这里把当前 device + baseRepo 的权威+ // snapshot 投影回页面 target。桌面端改分支后无需重开 sheet 即时回显。+ useEffect(() => {+ if (!remoteWorktreeBranchPreference || worktreeEligibility.status !== 'eligible') return;+ if (remoteWorktreeBranchPreference.baseRepo !== worktreeEligibility.baseRepo) return;+ setWorktreeBranchSelection({+ target: {+ deviceId: selectedDeviceId ?? '',+ workingDir: draft.workspaceKind === 'project' ? draft.workingDir.trim() : '',+ },+ sourceBranch: remoteWorktreeBranchPreference.sourceBranch,+ });+ }, [+ remoteWorktreeBranchPreference,+ selectedDeviceId,+ draft.workspaceKind,+ draft.workingDir,+ worktreeEligibility,+ ]);++ // —— worktree 源分支:列表只属于当前设备 + cwd;OFF 也允许打开和选择。+ // seq + render 期 target ref 防止切项目/设备时旧请求晚到覆盖新目标。+ const loadWorktreeBranches = useCallback((force = false) => {+ if (!selectedDeviceId || worktreeEligibility.status !== 'eligible') return;+ const target = {+ deviceId: selectedDeviceId,+ workingDir: draft.workingDir.trim(),+ };+ const currentMatches = worktreeBranchList != null+ && worktreeBranchList.target.deviceId === target.deviceId+ && worktreeBranchList.target.workingDir.trim() === target.workingDir;+ if (+ !force+ && currentMatches+ && !worktreeBranchList.loading+ && !worktreeBranchList.failed+ ) return;++ const seq = ++worktreeBranchListSeqRef.current;+ setWorktreeBranchList({ target, branches: [], loading: true, failed: false });+ void withTransientRemoteRetry(async () => {+ await openLink(selectedDeviceId);+ return maker.worktree.listBranches(worktreeEligibility.baseRepo);+ }, { maxAttempts: 2 })+ .then((result) => {+ const latestTarget = worktreeBranchTargetRef.current;+ if (!shouldAcceptWorktreeBranchListResult({+ requestSeq: seq,+ latestSeq: worktreeBranchListSeqRef.current,+ requestTarget: target,+ latestTarget,+ })) return;+ const branches = Array.from(new Set(+ (result.branches ?? [])+ .filter((branch): branch is string => typeof branch === 'string')+ .map((branch) => branch.trim())+ .filter(Boolean),+ ));+ setWorktreeBranchList({ target, branches, loading: false, failed: false });+ })+ .catch(() => {+ const latestTarget = worktreeBranchTargetRef.current;+ if (!shouldAcceptWorktreeBranchListResult({+ requestSeq: seq,+ latestSeq: worktreeBranchListSeqRef.current,+ requestTarget: target,+ latestTarget,+ })) return;+ setWorktreeBranchList({ target, branches: [], loading: false, failed: true });+ });+ }, [+ draft.workingDir,+ maker,+ openLink,+ selectedDeviceId,+ worktreeBranchList,+ worktreeEligibility,+ ]);++ const openWorktreeBranchPicker = useCallback(() => {+ if (worktreeBranchDisabled) return;+ setDevicePickerOpen(false);+ setWorkspacePickerOpen(false);+ setAgentPickerOpen(false);+ setModelSheetOpen(false);+ setPermissionSheetOpen(false);+ setContextSheetOpen(false);+ setBrowseOpen(false);+ setWorktreeBranchSheetSnap('half');+ setWorktreeBranchSheetOpen(true);+ loadWorktreeBranches(false);+ }, [loadWorktreeBranches, worktreeBranchDisabled]);++ const selectWorktreeSourceBranch = useCallback((sourceBranch: string) => {+ if (+ !selectedDeviceId+ || worktreeEligibility.status !== 'eligible'+ || worktreeBranchPreferenceSaving+ ) return;+ const target = { ...worktreeBranchTargetRef.current };+ const baseRepo = worktreeEligibility.baseRepo;+ const normalizedSourceBranch = sourceBranch.trim();+ if (!normalizedSourceBranch) return;+ const key = `${selectedDeviceId}\u0000${baseRepo}`;+ const writeSeq = worktreeBranchPreferenceWriteSeqRef.current + 1;+ worktreeBranchPreferenceWriteSeqRef.current = writeSeq;+ setWorktreeBranchPreferenceSavingKey(key);+ setWorktreeBranchSheetOpen(false);+ // 选择分支只写 repo-scoped branch pref,绝不调用 checkbox 的 apply channel。+ void withTransientRemoteRetry(async () => {+ await openLink(selectedDeviceId);+ return maker.applyNewMakerWorktreeBranchPref(baseRepo, normalizedSourceBranch);+ }, { maxAttempts: 2 })+ .then((snapshot) => {+ if (writeSeq !== worktreeBranchPreferenceWriteSeqRef.current) return;+ const latestTarget = worktreeBranchTargetRef.current;+ if (+ latestTarget.deviceId !== target.deviceId+ || latestTarget.workingDir.trim() !== target.workingDir.trim()+ || snapshot.baseRepo !== baseRepo+ ) return;+ remoteSessionStore.setNewMakerWorktreeBranchPreference(selectedDeviceId, snapshot);+ })+ .catch((err: unknown) => {+ if (writeSeq !== worktreeBranchPreferenceWriteSeqRef.current) return;+ const latestTarget = worktreeBranchTargetRef.current;+ if (+ latestTarget.deviceId === target.deviceId+ && latestTarget.workingDir.trim() === target.workingDir.trim()+ ) setError(formatRemoteError(err));+ })+ .finally(() => {+ if (worktreeBranchPreferenceWriteSeqRef.current === writeSeq) {+ setWorktreeBranchPreferenceSavingKey(null);+ }+ });+ }, [+ maker,+ openLink,+ selectedDeviceId,+ worktreeBranchPreferenceSaving,+ worktreeEligibility,]);// —— worktree 勾选播种:选中设备后读工作端 get-new-maker-defaults 的 worktreeEnabled// (vendor 无关,agentKind 只是通道入参,经 ref 读当前值,不因切 agent 重播)。- // 设备切换 / 链路重连重新播种;老被控端 / 缺字段 → 未勾选。+ // 设备切换 / 链路重连重新播种;老被控端 / 缺字段 / 拉取失败只保留当前镜像。+ // 全新设备在 store 中没有镜像时本来就是默认未勾选,无需失败路径代替宿主写值。const worktreeSeedAgentKindRef = useRef(draft.agentKind);worktreeSeedAgentKindRef.current = draft.agentKind;useEffect(() => {@@ -1621,21 +1949,12 @@ export default function NewRemoteSessionScreen() {remoteSessionStore.getNewMakerWorktreePreference(selectedDeviceId).revision!== preferenceRevisionAtStart) return;- remoteSessionStore.setNewMakerWorktreePreference(- selectedDeviceId,- seedWorktreeEnabled(defaults),- );+ const enabled = seedWorktreeEnabled(defaults);+ if (enabled === null) return;+ remoteSessionStore.setNewMakerWorktreePreference(selectedDeviceId, enabled);})- .catch((error: unknown) => {- // 只有已确认的旧端通道不兼容才回落未勾选。断连 / 超时保留最后镜像;- // connectionEpoch 变化后 effect 会重拉,不能把工作端拥有的 true 静默抹掉。- if (seq !== worktreeSeedSeqRef.current) return;- if (- remoteSessionStore.getNewMakerWorktreePreference(selectedDeviceId).revision- !== preferenceRevisionAtStart- ) return;- if (worktreeEligibilityFromError(error).status !== 'unsupported') return;- remoteSessionStore.setNewMakerWorktreePreference(selectedDeviceId, false);+ .catch(() => {+ // 断连、超时、旧端不支持都不能改 checkbox;重连后由下一次 pull 收敛。});}, [connectionEpoch,@@ -1646,16 +1965,41 @@ export default function NewRemoteSessionScreen() {openLink,]);- // 用户显式点击开关:本地翻转 + fire-and-forget 写穿工作端记忆(失败吞掉,仅本次生效)。- // 资格不满足导致的禁用不会走到这里 —— 环境因素不抹掉用户偏好。+ // 用户显式点击开关:先写工作端,工作端接受后才更新手机内存镜像。+ // 资格不满足导致的禁用不会走到这里 —— 环境因素不抹掉用户偏好;+ // 写入失败也不在手机上制造一份假的持久状态。const toggleWorktree = useCallback(() => {- if (!selectedDeviceId) return;+ if (!selectedDeviceId || worktreePreferenceSaving) return;+ const targetDeviceId = selectedDeviceId;const next = !worktreeEnabled;- remoteSessionStore.setNewMakerWorktreePreference(selectedDeviceId, next);// 播种在途回包不得覆盖用户显式选择(seq 作废旧回包)。worktreeSeedSeqRef.current += 1;- void maker.applyNewMakerWorktreePref(next).catch(() => undefined);- }, [maker, selectedDeviceId, worktreeEnabled]);+ const preferenceRevisionAtStart =+ remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId).revision;+ const writeSeq = worktreePreferenceWriteSeqRef.current + 1;+ worktreePreferenceWriteSeqRef.current = writeSeq;+ setWorktreePreferenceSavingDeviceId(targetDeviceId);+ void applyWorktreePreferenceOnHost({+ enabled: next,+ apply: maker.applyNewMakerWorktreePref,+ mirror: (enabled) => {+ if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;+ // 权威 push 或其它显式操作若已先到,它拥有更新 revision;+ // 不用这个较早的 invoke 完成再次覆盖。+ if (+ remoteSessionStore.getNewMakerWorktreePreference(targetDeviceId).revision+ !== preferenceRevisionAtStart+ ) return;+ remoteSessionStore.setNewMakerWorktreePreference(targetDeviceId, enabled);+ },+ })+ .catch(() => undefined)+ .finally(() => {+ if (worktreePreferenceWriteSeqRef.current === writeSeq) {+ setWorktreePreferenceSavingDeviceId(null);+ }+ });+ }, [maker, selectedDeviceId, worktreeEnabled, worktreePreferenceSaving]);useEffect(() => {const tracker = createMobileVoiceDictionaryLearningTracker({@@ -2021,6 +2365,8 @@ export default function NewRemoteSessionScreen() {onPress={() => {setModelSheetOpen(false);setAgentPickerOpen(false);+ setPermissionSheetOpen(false);+ setWorktreeBranchSheetOpen(false);setContextSheetView('main');setContextSheetOpen(true);}}@@ -2041,9 +2387,21 @@ export default function NewRemoteSessionScreen() {const renderCreateButton = () => (<PressableaccessibilityLabel={creating ? t('session.new.creatingSession') : t('session.new.createAndSend')}- accessibilityHint={createValidation ?? undefined}+ accessibilityHint={createValidation+ ?? (worktreeBranchPreferenceSaving+ ? t('session.new.worktreeBranchSaving')+ : worktreeCreateBlocked && worktreeCaptionKey+ ? t(worktreeCaptionKey)+ : undefined)}accessibilityRole="button"- accessibilityState={{ busy: creating || voiceIsProcessing || undefined, disabled: !canCreate || undefined }}+ accessibilityState={{+ busy: creating+ || voiceIsProcessing+ || worktreePreferenceSaving+ || worktreeBranchPreferenceSaving+ || undefined,+ disabled: !canCreate || undefined,+ }}disabled={!canCreate}hitSlop={10}onPress={() => void create()}@@ -2535,6 +2893,10 @@ export default function NewRemoteSessionScreen() {setError(t('session.new.selectDeviceError'));return;}+ if (worktreeCreateBlocked) {+ if (worktreeCaptionKey) setError(t(worktreeCaptionKey));+ return;+ }creatingRef.current = true;setCreating(true);setError(null);@@ -2693,6 +3055,7 @@ export default function NewRemoteSessionScreen() {const resp = await maker.worktree.create(buildWorktreeCreateRequest({sessionId,eligibility: worktreeEligibility,+ sourceBranch: worktreeSourceBranch,suggestedName: suggested,recoveryKey,}));@@ -2821,7 +3184,10 @@ export default function NewRemoteSessionScreen() {voiceState,waitForPendingUploads,worktreeEligibility,+ worktreeCreateBlocked,+ worktreeCaptionKey,worktreeEnabled,+ worktreeSourceBranch,]);// 目标模式建会话(对齐桌面 handleCreateGoal):createSession → goal.set(被控端落@@ -3131,34 +3497,79 @@ export default function NewRemoteSessionScreen() {</View>{worktreeRowVisible ? (<View style={styles.worktreeToggleWrap}>- <Pressable- accessibilityLabel={t('session.new.useWorktree')}- accessibilityRole="checkbox"- accessibilityState={{- checked: worktreeChecked,- disabled: worktreeToggleDisabled || undefined,- }}- disabled={worktreeToggleDisabled}- onPress={toggleWorktree}- style={({ pressed }) => [- styles.worktreeToggleRow,- pressed && styles.pressed,- worktreeToggleDisabled && styles.disabled,- ]}- testID="newSession.worktreeToggle"- >- <View style={[- styles.worktreeCheckbox,- worktreeChecked && styles.worktreeCheckboxChecked,- ]}>- {worktreeChecked ? (- <Check color={colors.ctaText} size={iconSize.xs} strokeWidth={iconStroke.bold} />- ) : null}+ <View style={styles.worktreeControlTouchWrap}>+ <View style={styles.worktreeControl} testID="newSession.branchWorktreeControl">+ <View+ pointerEvents="none"+ style={[+ styles.worktreeControlBackground,+ worktreeChecked && styles.worktreeControlChecked,+ ]}+ />+ <Pressable+ accessibilityLabel={t('session.new.selectWorktreeBranchA11y', {+ branch: worktreeSourceBranch,+ })}+ accessibilityRole="button"+ accessibilityState={{+ busy: worktreeBranchPreferenceSaving || undefined,+ disabled: worktreeBranchDisabled || undefined,+ expanded: worktreeBranchSheetVisible || undefined,+ }}+ disabled={worktreeBranchDisabled}+ onPress={openWorktreeBranchPicker}+ style={({ pressed }) => [+ styles.worktreeBranchSegment,+ pressed && styles.pressed,+ worktreeBranchDisabled && styles.disabled,+ ]}+ testID="newSession.worktreeBranchPicker"+ >+ <GitBranch+ color={worktreeChecked ? colors.textPrimary : colors.textTertiary}+ size={iconSize.sm}+ strokeWidth={iconStroke.regular}+ />+ <Text style={styles.worktreeBranchLabel} numberOfLines={1}>+ {worktreeSourceBranch}+ </Text>+ {!worktreeBranchDisabled ? (+ <ChevronDown+ color={colors.textTertiary}+ size={iconSize.xs}+ strokeWidth={iconStroke.regular}+ />+ ) : null}+ </Pressable>+ <View style={styles.worktreeControlDivider} />+ <Pressable+ accessibilityLabel={t('session.new.useWorktree')}+ accessibilityRole="checkbox"+ accessibilityState={{+ checked: worktreeChecked,+ disabled: worktreeToggleDisabled || undefined,+ }}+ disabled={worktreeToggleDisabled}+ onPress={toggleWorktree}+ style={({ pressed }) => [+ styles.worktreeToggleRow,+ pressed && styles.pressed,+ worktreeToggleDisabled && styles.disabled,+ ]}+ testID="newSession.worktreeToggle"+ >+ <View style={[+ styles.worktreeCheckbox,+ worktreeChecked && styles.worktreeCheckboxChecked,+ ]}>+ {worktreeChecked ? (+ <Check color={colors.ctaText} size={iconSize.xs} strokeWidth={iconStroke.bold} />+ ) : null}+ </View>+ <Text style={styles.worktreeToggleLabel} numberOfLines={1}>worktree</Text>+ </Pressable></View>- <Text style={styles.worktreeToggleLabel} numberOfLines={1}>- {t('session.new.useWorktree')}- </Text>- </Pressable>+ </View>{worktreeCaptionKey ? (<Text style={styles.worktreeCaption} testID="newSession.worktreeCaption">{t(worktreeCaptionKey)}@@ -3508,6 +3919,54 @@ export default function NewRemoteSessionScreen() {/>)}</ContextSheet>+ <SheetModal+ backdropTestID="newSession.worktreeBranchSheet.backdrop"+ onBackdropPress={() => setWorktreeBranchSheetOpen(false)}+ onRequestClose={() => setWorktreeBranchSheetOpen(false)}+ visible={worktreeBranchSheetVisible}+ >+ <SheetSurface+ bottomInset={safeAreaInsets.bottom}+ heights={permissionSheetHeights}+ onClose={() => setWorktreeBranchSheetOpen(false)}+ onSnapChange={setWorktreeBranchSheetSnap}+ snap={worktreeBranchSheetSnap}+ testID="newSession.worktreeBranchSheet"+ title={t('session.new.worktreeSourceBranch')}+ >+ {worktreeBranchList?.loading ? (+ <View style={styles.worktreeBranchStatusRow}>+ <ActivityIndicator color={colors.textSecondary} size="small" />+ <Text style={styles.worktreeBranchStatusText}>+ {t('session.new.worktreeBranchesLoading')}+ </Text>+ </View>+ ) : worktreeBranchList?.failed || worktreeBranchOptions.length === 0 ? (+ <Pressable+ accessibilityLabel={t('session.new.worktreeBranchesRetry')}+ accessibilityRole="button"+ onPress={() => loadWorktreeBranches(true)}+ style={({ pressed }) => [+ styles.worktreeBranchStatusRow,+ pressed && styles.pressed,+ ]}+ testID="newSession.worktreeBranchSheet.retry"+ >+ <Text style={styles.worktreeBranchStatusText}>+ {t('session.new.worktreeBranchesRetry')}+ </Text>+ </Pressable>+ ) : (+ <MobileChoicePickerList+ activeId={worktreeSourceBranch}+ disabled={creating}+ onSelect={selectWorktreeSourceBranch}+ options={worktreeBranchOptions}+ testID="newSession.worktreeBranchSheet.option"+ />+ )}+ </SheetSurface>+ </SheetModal><ModelPickerSheetactiveModelId={draft.model}activePermissionMode={displayPermissionMode}@@ -3912,26 +4371,79 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({height: StyleSheet.hairlineWidth,marginVertical: spacing.xs,},- // worktree 开关行(selectorStack 内、工作区选择器之后):自绘 checkbox 同 browseCheckbox- // 基因,行高与 selectorRow 对齐;caption 缩进到与文案左缘对齐。+ // 分支 + worktree 是两个独立点击区组成的一枚紧凑 pill。点击区实高 44;背景绝对+ // 内缩 5pt 后视觉高 34,既不牺牲触控面积,也不让「worktree」重新显得臃肿。worktreeToggleWrap: {gap: spacing.xs,},- worktreeToggleRow: {+ worktreeControlTouchWrap: {alignItems: 'center',alignSelf: 'flex-start',+ justifyContent: 'center',+ maxWidth: '100%',+ minHeight: 44,+ },+ worktreeControl: {+ alignItems: 'stretch',flexDirection: 'row',- gap: spacing.md,- minHeight: 42,+ height: 44,+ maxWidth: '100%',+ position: 'relative',+ },+ worktreeControlBackground: {+ backgroundColor: colors.surfaceChip,+ borderColor: colors.border,+ borderRadius: radius.pill,+ borderWidth: StyleSheet.hairlineWidth,+ bottom: 5,+ left: 0,+ position: 'absolute',+ right: 0,+ top: 5,+ },+ worktreeControlChecked: {+ borderColor: colors.borderStrong,+ },+ worktreeBranchSegment: {+ alignItems: 'center',+ flexDirection: 'row',+ flexShrink: 1,+ gap: spacing.xs,+ minHeight: 44,+ minWidth: 72,+ paddingLeft: spacing.sm,+ paddingRight: spacing.xs,+ },+ worktreeBranchLabel: {+ color: colors.textTertiary,+ flexShrink: 1,+ fontSize: typeScale.footnote,+ fontWeight: fontWeight.medium,+ lineHeight: lineHeight.caption,+ minWidth: 0,+ },+ worktreeControlDivider: {+ alignSelf: 'center',+ backgroundColor: colors.border,+ height: 16,+ width: StyleSheet.hairlineWidth,+ },+ worktreeToggleRow: {+ alignItems: 'center',+ flexDirection: 'row',+ gap: spacing.xs,+ minHeight: 44,+ paddingLeft: spacing.xs,+ paddingRight: spacing.sm,},worktreeCheckbox: {alignItems: 'center',borderColor: colors.borderStrong,borderRadius: radius.pill,borderWidth: StyleSheet.hairlineWidth,- height: 20,+ height: 18,justifyContent: 'center',- width: 20,+ width: 18,},worktreeCheckboxChecked: {backgroundColor: colors.cta,@@ -3940,16 +4452,30 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({worktreeToggleLabel: {color: colors.textTertiary,flexShrink: 1,- fontSize: typeScale.body,+ fontSize: typeScale.footnote,fontWeight: fontWeight.medium,- lineHeight: lineHeight.body,+ lineHeight: lineHeight.caption,minWidth: 0,},worktreeCaption: {color: colors.textTertiary,fontSize: typeScale.caption,lineHeight: lineHeight.caption,- marginLeft: 20 + spacing.md,+ marginLeft: spacing.sm,+ },+ worktreeBranchStatusRow: {+ alignItems: 'center',+ borderRadius: radius.pill,+ flexDirection: 'row',+ gap: spacing.sm,+ minHeight: 48,+ paddingHorizontal: spacing.sm,+ },+ worktreeBranchStatusText: {+ color: colors.textSecondary,+ flex: 1,+ fontSize: typeScale.body,+ fontWeight: fontWeight.medium,},hint: { color: colors.textSecondary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },errorText: {diff --git a/apps/mobile/scripts/mock-device-link-host.mjs b/apps/mobile/scripts/mock-device-link-host.mjsindex ce2716d9d5..dba86efc1b 100644--- a/apps/mobile/scripts/mock-device-link-host.mjs+++ b/apps/mobile/scripts/mock-device-link-host.mjs@@ -11,6 +11,7 @@ const DEFAULT_API_BASE = 'http://localhost:3333';const DEFAULT_DEVICE_ID = 'mobile-e2e-host';const DEFAULT_DEVICE_NAME = 'XDMaker Mock Mac';const DEFAULT_SESSION_ID = 'mock-session-1';+const MOCK_WORKTREE_BRANCHES = ['main', 'feature/mobile-worktree', 'release/mobile'];// 日志脱敏:session id 可能来自 env / 真实本地 db,只打印首尾预览,不落明文// (CodeQL js/clear-text-logging)。@@ -40,6 +41,7 @@ const startedAt = new Date();const state = realDbPath? createRealDbState({ dbPath: realDbPath, sessionId, deviceId, deviceName, startedAt, limit: realDbLimit }): createMockState({ deviceId, sessionId, deviceName, scenario, startedAt });+const mockWorktree = createMockWorktreeState(state);const controllerTopics = new Map();const revokedControllers = new Set();const visualTransitionKeys = new Set();@@ -299,6 +301,14 @@ async function handleInvoke(controllerId, channel, args) {return agentCapabilities(String(args[0] ?? 'claude-code'));case 'maker:provider:list':return mockProviders();+ case 'maker:get-new-maker-defaults':+ return { worktreeEnabled: mockWorktree.enabled };+ case 'maker:apply-new-maker-worktree-pref':+ return applyMockWorktreePreference(args[0]);+ case 'maker:get-new-maker-worktree-branch-pref':+ return getMockWorktreeBranchPreference(args[0]);+ case 'maker:apply-new-maker-worktree-branch-pref':+ return applyMockWorktreeBranchPreference(args[0]);case 'maker:switch-session-agent':return registerAgentSwitchIntent(String(args[0] ?? sessionId),@@ -341,6 +351,16 @@ async function handleInvoke(controllerId, channel, args) {return statPath(args[0]?.path);case 'fs:mkdir-p':return { resolvedPath: String(args[0]?.path ?? '/tmp') };+ case 'worktree:detect-cwd':+ return detectMockWorktreeCwd(args[0]);+ case 'worktree:list-branches':+ return listMockWorktreeBranches(args[0]);+ case 'worktree:suggest-name':+ return suggestMockWorktreeName(args[0]);+ case 'worktree:create':+ return createMockWorktree(args[0]);+ case 'worktree:discard-precreated':+ return discardMockPrecreatedWorktree(args[0]);case 'text-file:read-preview':return readTextFilePreview(args[0]?.filePath);case 'maker:schedule:list':@@ -1254,6 +1274,227 @@ function listMessages(id, opts = {}) {return filtered.slice(-limit);}+/**+ * Native E2E does not create real git directories, but the worktree fixture mirrors the+ * Desktop IPC response shapes and ownership transition closely enough to exercise the+ * mobile two-step flow: pre-create a worktree, then claim it with maker:create-session.+ */+function createMockWorktreeState(mockState) {+ const baseRepos = new Set(+ mockState.sessions+ .filter((session) => session.workspaceKind !== 'dialogue')+ .map((session) => typeof session.workingDir === 'string' ? session.workingDir.trim() : '')+ .filter((workingDir) => path.isAbsolute(workingDir)),+ );+ if (baseRepos.size === 0) baseRepos.add('/tmp/xdt-maker-mobile-e2e');+ return {+ baseRepos,+ branches: [...MOCK_WORKTREE_BRANCHES],+ currentBranch: MOCK_WORKTREE_BRANCHES[0],+ enabled: false,+ nameSequence: 0,+ branchPreferenceRevision: new Map(),+ branchPreferences: new Map(),+ bySessionId: new Map(),+ };+}++function mockIpcError(code, message) {+ const error = new Error(message);+ error.code = code;+ return error;+}++function requireMockObject(value, description) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw mockIpcError('INVALID_PARAMS', `${description} required`);+ }+ return value;+}++function requireMockString(value, field) {+ if (typeof value !== 'string' || !value.trim()) {+ throw mockIpcError('INVALID_PARAMS', `${field} required`);+ }+ return value.trim();+}++function applyMockWorktreePreference(raw) {+ const pref = requireMockObject(raw, 'worktree preference');+ if (typeof pref.worktreeEnabled !== 'boolean') {+ throw mockIpcError('INVALID_PARAMS', 'worktreeEnabled must be boolean');+ }+ mockWorktree.enabled = pref.worktreeEnabled;+ return undefined;+}++function getMockWorktreeBranchPreference(raw) {+ const input = requireMockObject(raw, 'worktree branch preference request');+ const baseRepo = requireMockString(input.baseRepo, 'baseRepo');+ return mockWorktree.branchPreferences.get(path.normalize(baseRepo)) ?? null;+}++function applyMockWorktreeBranchPreference(raw) {+ const input = requireMockObject(raw, 'worktree branch preference request');+ const baseRepo = path.normalize(requireMockString(input.baseRepo, 'baseRepo'));+ const sourceBranch = requireMockString(input.sourceBranch, 'sourceBranch');+ if (!mockWorktree.baseRepos.has(baseRepo)) {+ throw mockIpcError('NOT_GIT_REPO', 'baseRepo is not a known mock git repository');+ }+ if (sourceBranch !== 'HEAD' && !mockWorktree.branches.includes(sourceBranch)) {+ throw mockIpcError('INVALID_PARAMS', 'sourceBranch is not a known mock branch');+ }+ const revision = (mockWorktree.branchPreferenceRevision.get(baseRepo) ?? 0) + 1;+ const snapshot = { baseRepo, sourceBranch, revision };+ mockWorktree.branchPreferenceRevision.set(baseRepo, revision);+ mockWorktree.branchPreferences.set(baseRepo, snapshot);+ broadcast('maker:new-maker-worktree-branch:changed', snapshot);+ return snapshot;+}++function managedWorktreeRepoRoot(cwd) {+ const normalized = path.normalize(cwd);+ const marker = `${path.sep}.cindy-worktrees${path.sep}`;+ const markerIndex = normalized.indexOf(marker);+ if (markerIndex > 0) {+ const inferredBaseRepo = normalized.slice(0, markerIndex);+ if (mockWorktree.baseRepos.has(inferredBaseRepo)) return inferredBaseRepo;+ }+ const candidates = [...mockWorktree.baseRepos]+ .filter((repo) => normalized === repo || normalized.startsWith(`${repo}${path.sep}`))+ .sort((a, b) => b.length - a.length);+ return candidates[0] ?? null;+}++function detectMockWorktreeCwd(raw) {+ const input = requireMockObject(raw, 'worktree detect request');+ const cwd = requireMockString(input.cwd, 'cwd');+ if (!path.isAbsolute(cwd)) {+ return {+ isGitRepo: false,+ isInsideWorktree: false,+ gitInstalled: true,+ supportsRecoveryKeyDiscard: true,+ };+ }+ const repoRoot = managedWorktreeRepoRoot(cwd);+ if (!repoRoot) {+ return {+ isGitRepo: false,+ isInsideWorktree: false,+ gitInstalled: true,+ supportsRecoveryKeyDiscard: true,+ };+ }+ return {+ isGitRepo: true,+ isInsideWorktree: path.normalize(cwd).includes(`${path.sep}.cindy-worktrees${path.sep}`),+ gitInstalled: true,+ currentBranch: mockWorktree.currentBranch,+ repoRoot,+ supportsRecoveryKeyDiscard: true,+ };+}++function listMockWorktreeBranches(raw) {+ const input = requireMockObject(raw, 'worktree branch request');+ const baseRepo = requireMockString(input.baseRepo, 'baseRepo');+ if (!path.isAbsolute(baseRepo)) {+ throw mockIpcError('INVALID_PARAMS', 'baseRepo must be absolute');+ }+ if (!mockWorktree.baseRepos.has(path.normalize(baseRepo))) {+ throw mockIpcError('NOT_GIT_REPO', 'baseRepo is not a known mock git repository');+ }+ return {+ branches: [...mockWorktree.branches],+ current: mockWorktree.currentBranch,+ };+}++function suggestMockWorktreeName(raw) {+ const input = requireMockObject(raw, 'worktree name request');+ requireMockString(input.baseRepo, 'baseRepo');+ mockWorktree.nameSequence += 1;+ return { name: `mobile-e2e-${mockWorktree.nameSequence}` };+}++function createMockWorktree(raw) {+ const input = requireMockObject(raw, 'worktree create request');+ const sessionId = requireMockString(input.sessionId, 'sessionId');+ const baseRepo = requireMockString(input.baseRepo, 'baseRepo');+ const name = requireMockString(input.name, 'name');+ const sourceBranch = requireMockString(input.sourceBranch, 'sourceBranch');+ const recoveryKey = input.recoveryKey === undefined+ ? undefined+ : requireMockString(input.recoveryKey, 'recoveryKey');++ if (!/^[a-z0-9](?:[a-z0-9-]{0,18}[a-z0-9])?$/.test(name) || name.includes('--')) {+ return {+ ok: false,+ error: {+ kind: 'unknown',+ message: 'worktree 名称非法',+ hint: '名称只能包含小写字母、数字和单个连字符,且不超过 20 个字符',+ },+ };+ }+ if (sourceBranch !== 'HEAD' && !mockWorktree.branches.includes(sourceBranch)) {+ return {+ ok: false,+ error: {+ kind: 'unknown',+ message: `源分支 "${sourceBranch}" 不存在`,+ hint: '请刷新分支列表或选择其他源分支',+ },+ };+ }++ const normalizedBaseRepo = path.normalize(baseRepo);+ const meta = {+ sessionId,+ name,+ path: path.join(normalizedBaseRepo, '.cindy-worktrees', name),+ baseRepo: normalizedBaseRepo,+ branch: `xdt/${name}`,+ sourceBranch,+ createdAt: new Date().toISOString(),+ ...(recoveryKey ? { recoveryKey } : {}),+ };+ mockWorktree.baseRepos.add(normalizedBaseRepo);+ mockWorktree.bySessionId.set(sessionId, { meta, claimed: false });+ return { ok: true, meta };+}++function discardMockPrecreatedWorktree(raw) {+ const input = requireMockObject(raw, 'discard pre-created worktree request');+ const sessionId = requireMockString(input.sessionId, 'sessionId');+ const hasPath = input.path !== undefined;+ const hasRecoveryKey = input.recoveryKey !== undefined;+ if (hasPath === hasRecoveryKey) {+ throw mockIpcError(+ 'INVALID_PARAMS',+ 'discard pre-created worktree requires exactly one recovery locator',+ );+ }++ const record = mockWorktree.bySessionId.get(sessionId);+ if (!record) return { discarded: true };+ if (record.claimed) {+ throw mockIpcError('PRECONDITION_FAILED', '会话已认领该 worktree,拒绝补偿回收');+ }+ if (hasPath && requireMockString(input.path, 'path') !== record.meta.path) {+ throw mockIpcError('PERMISSION_DENIED', '预创建 worktree 路径与登记记录不匹配');+ }+ if (+ hasRecoveryKey+ && requireMockString(input.recoveryKey, 'recoveryKey') !== record.meta.recoveryKey+ ) {+ throw mockIpcError('PERMISSION_DENIED', '预创建 worktree 恢复关联键与登记记录不匹配');+ }+ mockWorktree.bySessionId.delete(sessionId);+ return { discarded: true, branchDeleted: true };+}+async function enqueueMessage(controllerId, id, queued) {applyPendingAgentSwitchIntent(id);const text = typeof queued?.text === 'string' ? queued.text : 'mobile message';@@ -1275,11 +1516,17 @@ function createSession(opts = {}) {// 对 provided id 幂等),缺省才由 mock 生成——新建会话乐观管线依赖这一契约。const id = typeof opts?.id === 'string' && opts.id ? opts.id : `mock-created-${Date.now()}`;const workingDir = typeof opts?.workingDir === 'string' ? opts.workingDir : '/tmp/xdt-maker-mobile-e2e';+ const precreatedWorktree = mockWorktree.bySessionId.get(id);+ const claimedWorktree = precreatedWorktree?.meta.path === workingDir+ ? precreatedWorktree+ : null;+ if (claimedWorktree) claimedWorktree.claimed = true;const session = {...state.sessions[0],id,title: 'Mobile Created Mock Session',workingDir,+ worktreePath: claimedWorktree?.meta.path ?? null,workspaceKind: opts?.workspaceKind === 'dialogue' ? 'dialogue' : 'project',model: typeof opts?.model === 'string' ? opts.model : state.sessions[0].model,effort: typeof opts?.effort === 'string' ? opts.effort : state.sessions[0].effort,diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.tsindex 5d30e7e052..6717804511 100644--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts@@ -47,6 +47,8 @@ describe('mobile maker transport', () => {'maker:apply-new-maker-draft-pref','maker:get-new-maker-defaults','maker:apply-new-maker-worktree-pref',+ 'maker:get-new-maker-worktree-branch-pref',+ 'maker:apply-new-maker-worktree-branch-pref','maker:usage:model-pricing','maker:usage:codex-rate-limits','maker:usage:codex-rate-limit-reset',@@ -111,6 +113,7 @@ describe('mobile maker transport', () => {'fs:stat-path','fs:mkdir-p','worktree:detect-cwd',+ 'worktree:list-branches','worktree:suggest-name','worktree:create','worktree:discard-precreated',@@ -359,7 +362,10 @@ describe('mobile maker transport', () => {await maker.getNewMakerDefaults('claude-code');await maker.applyNewMakerWorktreePref(true);+ await maker.getNewMakerWorktreeBranchPref('/repo');+ await maker.applyNewMakerWorktreeBranchPref('/repo', 'feature/mobile-sync');await maker.worktree.detectCwd('/repo/app');+ await maker.worktree.listBranches('/repo');await maker.worktree.suggestName('/repo');await maker.worktree.create({sessionId: 'preset-session-1',@@ -380,7 +386,13 @@ describe('mobile maker transport', () => {expect(calls.map((call) => [call.channel, call.args])).toEqual([['maker:get-new-maker-defaults', ['claude-code']],['maker:apply-new-maker-worktree-pref', [{ worktreeEnabled: true }]],+ ['maker:get-new-maker-worktree-branch-pref', [{ baseRepo: '/repo' }]],+ ['maker:apply-new-maker-worktree-branch-pref', [{+ baseRepo: '/repo',+ sourceBranch: 'feature/mobile-sync',+ }]],['worktree:detect-cwd', [{ cwd: '/repo/app' }]],+ ['worktree:list-branches', [{ baseRepo: '/repo' }]],['worktree:suggest-name', [{ baseRepo: '/repo' }]],['worktree:create', [{sessionId: 'preset-session-1',diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.tsindex f04b09eaad..a1746868bc 100644--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts@@ -137,6 +137,32 @@ describe('native e2e environment', () => {);});+ it('keeps the mock host capable of exercising the native worktree two-step flow', () => {+ const mockHost = readFileSync(resolve(process.cwd(), 'scripts/mock-device-link-host.mjs'), 'utf8');++ for (const channel of [+ 'maker:get-new-maker-defaults',+ 'maker:apply-new-maker-worktree-pref',+ 'worktree:detect-cwd',+ 'worktree:list-branches',+ 'worktree:suggest-name',+ 'worktree:create',+ 'worktree:discard-precreated',+ ]) {+ expect(mockHost).toContain(`case '${channel}':`);+ }+ expect(mockHost).toContain("const MOCK_WORKTREE_BRANCHES = ['main', 'feature/mobile-worktree', 'release/mobile'];");+ expect(mockHost).toContain('supportsRecoveryKeyDiscard: true');+ expect(mockHost).toContain('branches: [...mockWorktree.branches]');+ expect(mockHost).toContain('current: mockWorktree.currentBranch');+ expect(mockHost).toContain("path: path.join(normalizedBaseRepo, '.cindy-worktrees', name)");+ expect(mockHost).toContain('branch: `xdt/${name}`');+ expect(mockHost).toContain('sourceBranch,');+ expect(mockHost).toContain('worktreePath: claimedWorktree?.meta.path ?? null');+ expect(mockHost).toContain("throw mockIpcError('PRECONDITION_FAILED', '会话已认领该 worktree,拒绝补偿回收')");+ expect(mockHost).toContain('return { discarded: true, branchDeleted: true };');+ });+it('can run reconnect smoke as a self-contained local relay gate', () => {const packageJson = readFileSync(resolve(process.cwd(), 'package.json'), 'utf8');const reconnectSmoke = readFileSync(resolve(process.cwd(), 'scripts/device-link-reconnect-smoke.mjs'), 'utf8');diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex 164212f2b7..0c40137d70 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -693,6 +693,33 @@ describe('new session model', () => {]);});+ it('folds managed worktree sessions into their base repo project', () => {+ const options = buildRecentWorkspaceOptions([+ remoteSession('base', {+ workingDir: '/repo/app',+ userSendAt: '2026-01-01T00:01:00.000Z',+ }),+ remoteSession('current-worktree', {+ workingDir: '/repo/app/.cindy-worktrees/auto-one',+ worktreePath: '/repo/app/.cindy-worktrees/auto-one',+ userSendAt: '2026-01-01T00:03:00.000Z',+ }),+ remoteSession('legacy-worktree', {+ workingDir: '/repo/app/.xdt-worktrees/auto-two',+ worktreePath: '/repo/app/.xdt-worktrees/auto-two',+ userSendAt: '2026-01-01T00:02:00.000Z',+ }),+ ]);++ expect(options).toEqual([{+ workingDir: '/repo/app',+ title: 'app',+ sessionCount: 3,+ lastActivityAt: '2026-01-01T00:03:00.000Z',+ }]);+ expect(pickInitialNewSessionWorkspace('', options)).toBe('/repo/app');+ });+it('prefills a blank new session from the most recent workspace only', () => {const recentWorkspaces = buildRecentWorkspaceOptions([remoteSession('old', {@@ -1001,7 +1028,10 @@ describe('new session composer surface', () => {expect(createSource).toContain('const latestDraftText = await finishVoiceRecording();');expect(createSource).toContain('effectiveDraft = { ...draft, firstMessage: latestDraftText };');expect(createSource).toContain('creatingRef.current = false;');- expect(newSource).toContain('accessibilityState={{ busy: creating || voiceIsProcessing || undefined, disabled: !canCreate || undefined }}');+ expect(createButtonSource).toContain('busy: creating');+ expect(createButtonSource).toContain('|| worktreePreferenceSaving');+ expect(createButtonSource).toContain('|| worktreeBranchPreferenceSaving');+ expect(newSource).toContain('disabled: !canCreate || undefined,');// No start cue on mobile: playing a cue via expo-audio during capture stalls// the AVAudioEngine record tap (see mobileVoiceCue.ts). Only the end cue is wired.expect(newSource).not.toContain('playMobileVoiceInputStartCue');@@ -1079,19 +1109,36 @@ describe('new session worktree wiring (source locks)', () => {expect(newSource).toContain('useRemoteNewMakerWorktreePreference(selectedDeviceId)',);- expect(newSource).toMatch(- /if \(worktreeEligibilityFromError\(error\)\.status !== 'unsupported'\) return;\s*remoteSessionStore\.setNewMakerWorktreePreference\(selectedDeviceId, false\);/,+ expect(newSource).toContain('if (enabled === null) return;');+ expect(newSource).not.toContain(+ 'remoteSessionStore.setNewMakerWorktreePreference(selectedDeviceId, false);',);expect(newSource).toMatch(/\}, \[\s*connectionEpoch,\s*deviceLinkStatus,\s*presenceVersion,\s*selectedDeviceId,\s*maker,\s*openLink,\s*\]\);/,);- // 显式点击才写穿工作端记忆;写失败吞掉降级。- expect(newSource).toContain('void maker.applyNewMakerWorktreePref(next).catch(() => undefined);');+ // 显式点击才写穿工作端记忆;工作端接受后才更新手机镜像。+ expect(newSource).toContain('applyWorktreePreferenceOnHost({');+ expect(newSource).toContain('apply: maker.applyNewMakerWorktreePref,');+ expect(newSource).not.toContain(+ 'void maker.applyNewMakerWorktreePref(next).catch(() => undefined);',+ );+ // host-first 写入期间,适用 worktree 的项目由按钮和 create() 二次门禁阻止读取旧镜像;+ // 对话工作区不应被一份与当前创建无关的偏好写入卡住。+ expect(newSource).toContain('&& !worktreeCreateBlocked;');+ expect(newSource).toContain(+ "applicable: draft.workspaceKind === 'project' && draft.workingDir.trim().length > 0,",+ );+ const createEntry = newSource.indexOf('const create = useCallback(async () => {');+ const createBody = newSource.slice(createEntry, createEntry + 1_200);+ expect(createBody).not.toContain('|| worktreePreferenceSaving');+ expect(createBody).toContain('if (worktreeCreateBlocked) {');+ expect(newSource).toContain('worktreeBranchPreferenceSaving');+ expect(newSource).toContain('worktreeCreateBlocked && worktreeCaptionKey');});it('re-probes worktree eligibility when the relay or workstation reconnects', () => {expect(newSource).toContain(- "if (!selectedDeviceId || !cwd || deviceLinkStatus !== 'online') return;",+ "if (!selectedDeviceId || !cwd || deviceLinkStatus !== 'online') return undefined;",);const detectEffect = newSource.indexOf('return maker.worktree.detectCwd(cwd);',@@ -1192,15 +1239,37 @@ describe('new session worktree wiring (source locks)', () => {);});- it('binds eligibility to device/cwd and carries pre-created cleanup metadata into the pipeline', () => {- expect(newSource).toContain('const worktreeEligibility = worktreeEligibilityForTarget(worktreeProbe, {');+ it('binds eligibility and source branch to device/cwd, then carries cleanup metadata into the pipeline', () => {+ expect(newSource).toContain('const worktreeTarget = {');expect(newSource).toContain('deviceId: selectedDeviceId ??');+ expect(newSource).toContain('worktreeEligibilityForTarget(worktreeProbe, worktreeTarget)');+ expect(newSource).toContain('worktreeSourceBranchForTarget(');+ expect(newSource).toContain('shouldAcceptWorktreeBranchListResult({');+ expect(newSource).toContain('sourceBranch: worktreeSourceBranch,');expect(newSource).toContain('precreatedWorktree = {');expect(newSource).toContain('recoveryKey,');expect(newSource).toContain('originalWorkingDir: effectiveDraft.workingDir,');expect(newSource).toContain('precreatedWorktree,');});+ it('keeps branch selection independent from the worktree checkbox', () => {+ const disabledStart = newSource.indexOf('const worktreeBranchDisabled =');+ const disabledEnd = newSource.indexOf(';', disabledStart);+ expect(disabledStart).toBeGreaterThan(-1);+ expect(newSource.slice(disabledStart, disabledEnd + 1)).not.toContain('worktreeEnabled');++ const selectStart = newSource.indexOf('const selectWorktreeSourceBranch = useCallback(');+ const selectEnd = newSource.indexOf('// —— worktree 勾选播种', selectStart);+ const selectBlock = newSource.slice(selectStart, selectEnd);+ expect(selectBlock).toContain('maker.applyNewMakerWorktreeBranchPref(');+ expect(selectBlock).not.toContain('toggleWorktree');+ expect(selectBlock).not.toContain('maker.applyNewMakerWorktreePref(');+ expect(newSource).toContain('maker.getNewMakerWorktreeBranchPref(baseRepo)');+ expect(newSource).toContain('useRemoteNewMakerWorktreeBranchPreference(');+ expect(newSource).toContain('testID="newSession.worktreeBranchPicker"');+ expect(newSource).toContain('testID="newSession.worktreeToggle"');+ });+it('applies the protocol timeout override map to mobile invokes (worktree:create needs 60s)', () => {// 2026-07-29 与 main 合并后,移动端逐通道超时统一走 invokeTimeouts 的// resolveMobileInvokeTimeoutMs(mobile 专属表 → 协议契约表 INVOKE_TIMEOUT_OVERRIDES_MSdiff --git a/apps/mobile/src/__tests__/newSessionWorktree.test.ts b/apps/mobile/src/__tests__/newSessionWorktree.test.tsindex 5fefc0b402..91218ee157 100644--- a/apps/mobile/src/__tests__/newSessionWorktree.test.ts+++ b/apps/mobile/src/__tests__/newSessionWorktree.test.ts@@ -2,25 +2,29 @@* 新建会话 worktree 纯决策逻辑测试(newSessionWorktree):* - 资格判定:detect-cwd 回包按 gitInstalled → isGitRepo → isInsideWorktree 短路,* eligible 携带 baseRepo(repoRoot 缺失回落 workingDir)与 sourceBranch(detached 回落 HEAD);- * - 探测结果绑定 device/cwd,切目标后的同步 render 不暴露旧 eligible;- * - 探测抛错归并:CHANNEL_NOT_ALLOWED(老被控端)→ unsupported 整行隐藏,其余 detect-failed;- * - 播种归并:worktreeEnabled 严格 === true 才算勾选;+ * - 探测与显式分支选择都绑定 device/cwd,切目标后的同步 render 不暴露旧仓库状态;+ * - 探测抛错归并:CHANNEL_NOT_ALLOWED→ unsupported,瞬时断连→ recovering,其余 detect-failed;+ * - 播种归并:只接受工作端明确 boolean,缺字段/异常形状保留当前镜像;* - 两步流第一步入参:suggest-name 结果归一(空/非法走 auto- 兜底,过工作端名字白名单);* - 失败展示:message + hint 拼装。*/-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import type { MobileWorktreeDetectCwdResult } from '@/device-link/mobileMakerTransport';import {+ applyWorktreePreferenceOnHost,buildWorktreeCreateRequest,fallbackWorktreeName,formatWorktreeCreateFailure,normalizeSuggestedWorktreeName,resolveWorktreeEligibility,seedWorktreeEnabled,+ shouldBlockNewSessionCreateForWorktree,+ shouldAcceptWorktreeBranchListResult,shouldShowWorktreeToggle,worktreeEligibilityForTarget,worktreeEligibilityCaptionKey,worktreeEligibilityFromError,+ worktreeSourceBranchForTarget,type NewSessionWorktreeEligibility,} from '@/session/newSessionWorktree';@@ -111,6 +115,78 @@ describe('worktreeEligibilityForTarget', () => {});});+describe('worktreeSourceBranchForTarget', () => {+ const eligible: NewSessionWorktreeEligibility = {+ status: 'eligible',+ baseRepo: '/repo/a',+ sourceBranch: 'main',+ };+ const selected = {+ target: { deviceId: 'dev-a', workingDir: '/repo/a' },+ sourceBranch: 'feature/mobile',+ };++ it('同目标的显式选择优先,且与 worktree checkbox 状态无关', () => {+ expect(worktreeSourceBranchForTarget(+ selected,+ { deviceId: 'dev-a', workingDir: ' /repo/a ' },+ eligible,+ )).toBe('feature/mobile');+ });++ it('切设备或目录后同步回落新目标当前分支,不泄漏上一仓库选择', () => {+ expect(worktreeSourceBranchForTarget(+ selected,+ { deviceId: 'dev-b', workingDir: '/repo/a' },+ { ...eligible, sourceBranch: 'release' },+ )).toBe('release');+ expect(worktreeSourceBranchForTarget(+ selected,+ { deviceId: 'dev-a', workingDir: '/repo/b' },+ { ...eligible, baseRepo: '/repo/b', sourceBranch: 'develop' },+ )).toBe('develop');+ });++ it('资格未就绪时 fail closed 到 HEAD', () => {+ expect(worktreeSourceBranchForTarget(+ selected,+ { deviceId: 'dev-b', workingDir: '/repo/b' },+ { status: 'probing' },+ )).toBe('HEAD');+ });+});++describe('shouldAcceptWorktreeBranchListResult', () => {+ const targetA = { deviceId: 'dev-a', workingDir: '/repo/a' };++ it('只接受当前序号、当前设备与当前 cwd 的列表回包', () => {+ expect(shouldAcceptWorktreeBranchListResult({+ requestSeq: 2,+ latestSeq: 2,+ requestTarget: targetA,+ latestTarget: { deviceId: 'dev-a', workingDir: ' /repo/a ' },+ })).toBe(true);+ expect(shouldAcceptWorktreeBranchListResult({+ requestSeq: 1,+ latestSeq: 2,+ requestTarget: targetA,+ latestTarget: targetA,+ })).toBe(false);+ expect(shouldAcceptWorktreeBranchListResult({+ requestSeq: 2,+ latestSeq: 2,+ requestTarget: targetA,+ latestTarget: { deviceId: 'dev-b', workingDir: '/repo/a' },+ })).toBe(false);+ expect(shouldAcceptWorktreeBranchListResult({+ requestSeq: 2,+ latestSeq: 2,+ requestTarget: targetA,+ latestTarget: { deviceId: 'dev-a', workingDir: '/repo/b' },+ })).toBe(false);+ });+});+describe('worktreeEligibilityFromError', () => {it('CHANNEL_NOT_ALLOWED(老被控端)→ unsupported(整行隐藏降级)', () => {// 真实 wire 形状:DeviceLinkError 的 code 在 .code 字段,message **不含**该字面量@@ -129,21 +205,58 @@ describe('worktreeEligibilityFromError', () => {.toEqual({ status: 'unsupported' });});- it('其它错误(断连/超时)→ detect-failed(行保留、开关禁用)', () => {+ it('断连/超时→ recovering,由页面自动重试', () => {expect(worktreeEligibilityFromError(new Error('INVOKE_TIMEOUT')))- .toEqual({ status: 'detect-failed' });+ .toEqual({ status: 'recovering' });+ expect(worktreeEligibilityFromError(+ Object.assign(new Error('target offline'), { code: 'DEVICE_OFFLINE' }),+ )).toEqual({ status: 'recovering' });+ expect(worktreeEligibilityFromError(+ Object.assign(new Error('circuit open'), { code: 'DEVICE_UNRESPONSIVE' }),+ )).toEqual({ status: 'recovering' });+ });++ it('未知非瞬时错误→ detect-failed(行保留、开关禁用)', () => {expect(worktreeEligibilityFromError(undefined)).toEqual({ status: 'detect-failed' });});});describe('seedWorktreeEnabled', () => {- it('只有 worktreeEnabled === true 才播种为勾选;缺字段/异常形状一律 false', () => {+ it('只接受工作端明确 boolean;缺字段/异常形状不覆盖当前镜像', () => {expect(seedWorktreeEnabled({ worktreeEnabled: true })).toBe(true);expect(seedWorktreeEnabled({ worktreeEnabled: false })).toBe(false);- expect(seedWorktreeEnabled({})).toBe(false);- expect(seedWorktreeEnabled(null)).toBe(false);- expect(seedWorktreeEnabled(undefined)).toBe(false);- expect(seedWorktreeEnabled({ worktreeEnabled: 1 as unknown as boolean })).toBe(false);+ expect(seedWorktreeEnabled({})).toBeNull();+ expect(seedWorktreeEnabled(null)).toBeNull();+ expect(seedWorktreeEnabled(undefined)).toBeNull();+ expect(seedWorktreeEnabled({ worktreeEnabled: 1 as unknown as boolean })).toBeNull();+ });+});++describe('applyWorktreePreferenceOnHost', () => {+ it('工作端接受后才更新手机镜像', async () => {+ const order: string[] = [];+ await applyWorktreePreferenceOnHost({+ enabled: true,+ apply: vi.fn(async () => {+ order.push('host');+ }),+ mirror: vi.fn(() => {+ order.push('mobile-mirror');+ }),+ });+ expect(order).toEqual(['host', 'mobile-mirror']);+ });++ it('工作端写入失败时不改手机镜像', async () => {+ const mirror = vi.fn();+ await expect(applyWorktreePreferenceOnHost({+ enabled: true,+ apply: vi.fn(async () => {+ throw new Error('offline');+ }),+ mirror,+ })).rejects.toThrow('offline');+ expect(mirror).not.toHaveBeenCalled();});});@@ -162,6 +275,7 @@ describe('shouldShowWorktreeToggle / caption key', () => {it('caption key 覆盖探测中 / 三种不合格原因 / 探测失败;eligible 无 caption', () => {expect(worktreeEligibilityCaptionKey({ status: 'probing' })).toBe('session.new.worktreeDetecting');+ expect(worktreeEligibilityCaptionKey({ status: 'recovering' })).toBe('session.new.worktreeRecovering');expect(worktreeEligibilityCaptionKey({ status: 'ineligible', reason: 'gitMissing' })).toBe('session.new.worktreeGitMissing');expect(worktreeEligibilityCaptionKey({ status: 'ineligible', reason: 'notGitRepo' })).toBe('session.new.worktreeNotGitRepo');expect(worktreeEligibilityCaptionKey({ status: 'ineligible', reason: 'alreadyInWorktree' })).toBe('session.new.worktreeAlreadyInWorktree');@@ -171,6 +285,57 @@ describe('shouldShowWorktreeToggle / caption key', () => {});});+describe('shouldBlockNewSessionCreateForWorktree', () => {+ const eligible: NewSessionWorktreeEligibility = {+ status: 'eligible', baseRepo: '/repo', sourceBranch: 'main',+ };++ it('偏好写入在途时双向都阻止按旧 checkbox 镜像创建', () => {+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: true, enabled: false, eligibility: eligible, preferenceSaving: true,+ })).toBe(true);+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: true, enabled: true, eligibility: eligible, preferenceSaving: true,+ })).toBe(true);+ });++ it('对话工作区或尚未选项目目录时不受工作端 worktree 偏好阻塞', () => {+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: false,+ enabled: true,+ eligibility: { status: 'probing' },+ preferenceSaving: false,+ })).toBe(false);+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: false,+ enabled: true,+ eligibility: { status: 'detect-failed' },+ preferenceSaving: true,+ })).toBe(false);+ });++ it('ON 时必须等当前目标 eligible,OFF 与老端 unsupported 允许普通创建', () => {+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: true, enabled: true, eligibility: { status: 'probing' }, preferenceSaving: false,+ })).toBe(true);+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: true,+ enabled: true,+ eligibility: { status: 'ineligible', reason: 'notGitRepo' },+ preferenceSaving: false,+ })).toBe(true);+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: true, enabled: true, eligibility: eligible, preferenceSaving: false,+ })).toBe(false);+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: true, enabled: false, eligibility: { status: 'probing' }, preferenceSaving: false,+ })).toBe(false);+ expect(shouldBlockNewSessionCreateForWorktree({+ applicable: true, enabled: true, eligibility: { status: 'unsupported' }, preferenceSaving: false,+ })).toBe(false);+ });+});+describe('worktree 名与 create 入参', () => {it('suggest-name 非空取 trim;空/非字符串走 auto- 兜底(过工作端 [a-z0-9-]、≤20 白名单)', () => {expect(normalizeSuggestedWorktreeName(' fix-login ')).toBe('fix-login');@@ -201,6 +366,16 @@ describe('worktree 名与 create 入参', () => {});});+ it('显式选择的源分支覆盖 detect-cwd 当前分支,且会 trim', () => {+ expect(buildWorktreeCreateRequest({+ sessionId: 's-1',+ eligibility: { status: 'eligible', baseRepo: '/repo/root', sourceBranch: 'main' },+ sourceBranch: ' feature/mobile ',+ suggestedName: 'fix-login',+ recoveryKey: 'recovery-key-1234567890',+ }).sourceBranch).toBe('feature/mobile');+ });+it('suggest-name 失败(null)时 create 入参用 auto- 兜底名', () => {const request = buildWorktreeCreateRequest({sessionId: 's-1',diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 53b362b93c..5d94f9b1ca 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -238,6 +238,105 @@ describe('remoteSessionStore', () => {});});+ it('mirrors host-revisioned worktree branches without coupling them to the checkbox', () => {+ remoteSessionStore.setNewMakerWorktreePreference('dev-1', true);++ remoteSessionStore.applyRemotePush(+ 'dev-1',+ 'maker:new-maker-worktree-branch:changed',+ { baseRepo: '/repo/a', sourceBranch: 'feature/mobile', revision: 1 },+ );+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/a')).toEqual({+ baseRepo: '/repo/a',+ sourceBranch: 'feature/mobile',+ revision: 1,+ });+ expect(remoteSessionStore.getNewMakerWorktreePreference('dev-1')).toEqual({+ enabled: true,+ revision: 1,+ });++ // 同一分支的较新 host snapshot 仍要推进 revision,给在途 pull / apply 回包做 fence。+ remoteSessionStore.applyRemotePush(+ 'dev-1',+ 'maker:new-maker-worktree-branch:changed',+ { baseRepo: '/repo/a', sourceBranch: 'feature/mobile', revision: 2 },+ );+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/a')?.revision)+ .toBe(2);++ // 更旧 revision 以及同 revision 的冲突值都无权覆盖已接受的宿主快照。+ remoteSessionStore.applyRemotePush(+ 'dev-1',+ 'maker:new-maker-worktree-branch:changed',+ { baseRepo: '/repo/a', sourceBranch: 'stale', revision: 1 },+ );+ remoteSessionStore.applyRemotePush(+ 'dev-1',+ 'maker:new-maker-worktree-branch:changed',+ { baseRepo: '/repo/a', sourceBranch: 'conflict', revision: 2 },+ );+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/a')).toEqual({+ baseRepo: '/repo/a',+ sourceBranch: 'feature/mobile',+ revision: 2,+ });+ });++ it('isolates worktree branch snapshots by device and canonical repo, then clears their shards', () => {+ remoteSessionStore.setNewMakerWorktreeBranchPreference('dev-1', {+ baseRepo: '/repo/a', sourceBranch: 'main', revision: 1,+ });+ remoteSessionStore.setNewMakerWorktreeBranchPreference('dev-1', {+ baseRepo: '/repo/b', sourceBranch: 'release', revision: 4,+ });+ remoteSessionStore.setNewMakerWorktreeBranchPreference('dev-2', {+ baseRepo: '/repo/a', sourceBranch: 'develop', revision: 2,+ });++ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/a')?.sourceBranch)+ .toBe('main');+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/b')?.sourceBranch)+ .toBe('release');+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-2', '/repo/a')?.sourceBranch)+ .toBe('develop');+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-2', '/repo/b')).toBeNull();++ remoteSessionStore.removeDevice('dev-1');+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/a')).toBeNull();+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/b')).toBeNull();+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-2', '/repo/a')?.sourceBranch)+ .toBe('develop');++ remoteSessionStore.clear();+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-2', '/repo/a')).toBeNull();+ });++ it('ignores malformed worktree branch pushes without disturbing an accepted snapshot', () => {+ remoteSessionStore.setNewMakerWorktreeBranchPreference('dev-1', {+ baseRepo: '/repo/a', sourceBranch: 'main', revision: 3,+ });+ for (const payload of [+ null,+ { baseRepo: '', sourceBranch: 'release', revision: 4 },+ { baseRepo: '/repo/a', sourceBranch: '', revision: 4 },+ { baseRepo: '/repo/a', sourceBranch: 'release', revision: -1 },+ { baseRepo: '/repo/a', sourceBranch: 'release', revision: 3.5 },+ { baseRepo: '/repo/a', sourceBranch: 'release', revision: '4' },+ ]) {+ remoteSessionStore.applyRemotePush(+ 'dev-1',+ 'maker:new-maker-worktree-branch:changed',+ payload,+ );+ }+ expect(remoteSessionStore.getNewMakerWorktreeBranchPreference('dev-1', '/repo/a')).toEqual({+ baseRepo: '/repo/a',+ sourceBranch: 'main',+ revision: 3,+ });+ });+it('mirrors structured session money and legacy USD usage pushes', () => {remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex 1522c48ef8..63819a59a0 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -317,6 +317,16 @@ export interface MobileNewMakerDefaults {[key: string]: unknown;}+/**+ * 工作端拥有的 New Maker worktree 源分支镜像。revision 由工作端按 canonical+ * baseRepo 独立递增;手机只用它做 pull / push / apply 回包的乱序收敛,不自行生成。+ */+export interface MobileWorktreeBranchPreferenceSnapshot {+ baseRepo: string;+ sourceBranch: string;+ revision: number;+}+/** 工作端 worktree:detect-cwd 资格探测回包(形状对齐被控端 DetectCwdResp)。 */export interface MobileWorktreeDetectCwdResult {isGitRepo: boolean;@@ -332,6 +342,12 @@ export interface MobileWorktreeDetectCwdResult {supportsRecoveryKeyDiscard?: boolean;}+/** 工作端 worktree:list-branches 回包(本地分支列表 + 当前 HEAD 分支)。 */+export interface MobileWorktreeListBranchesResult {+ branches: string[];+ current: string;+}+/** 工作端 worktree:create 元信息(形状对齐被控端 WorktreeMeta)。 */export interface MobileWorktreeMeta {sessionId: string;@@ -445,6 +461,18 @@ export interface MobileMakerTransport {getNewMakerDefaults(agentKind: MobileAgentKind): Promise<MobileNewMakerDefaults>;/** 「新建会话默认启用 worktree」写穿工作端(老被控端 → 调用方吞掉降级)。 */applyNewMakerWorktreePref(worktreeEnabled: boolean): Promise<void>;+ /** 读取工作端某 canonical repo 的 New Maker worktree 源分支;未选择过返回 null。 */+ getNewMakerWorktreeBranchPref(+ baseRepo: string,+ ): Promise<MobileWorktreeBranchPreferenceSnapshot | null>;+ /**+ * 把源分支选择写穿工作端;回包是工作端接受后的权威 snapshot。+ * 与 worktree checkbox 使用独立 channel,选择分支不会改动开关偏好。+ */+ applyNewMakerWorktreeBranchPref(+ baseRepo: string,+ sourceBranch: string,+ ): Promise<MobileWorktreeBranchPreferenceSnapshot>;/*** worktree 两步建会话的工作端通道(git/fs 全在被控端执行):detect-cwd 做资格探测,* suggest-name 生成名字,create 以预生成 sessionId 建 worktree 拿路径(第二步再以该@@ -452,6 +480,7 @@ export interface MobileMakerTransport {*/worktree: {detectCwd(cwd: string): Promise<MobileWorktreeDetectCwdResult>;+ listBranches(baseRepo: string): Promise<MobileWorktreeListBranchesResult>;suggestName(baseRepo: string): Promise<{ name: string }>;create(req: {sessionId: string;@@ -668,8 +697,13 @@ export function createMobileMakerTransport({getNewMakerDefaults: (agentKind) => call('maker:get-new-maker-defaults', [agentKind]),applyNewMakerWorktreePref: (worktreeEnabled) =>call('maker:apply-new-maker-worktree-pref', [{ worktreeEnabled }]),+ getNewMakerWorktreeBranchPref: (baseRepo) =>+ call('maker:get-new-maker-worktree-branch-pref', [{ baseRepo }]),+ applyNewMakerWorktreeBranchPref: (baseRepo, sourceBranch) =>+ call('maker:apply-new-maker-worktree-branch-pref', [{ baseRepo, sourceBranch }]),worktree: {detectCwd: (cwd) => call('worktree:detect-cwd', [{ cwd }]),+ listBranches: (baseRepo) => call('worktree:list-branches', [{ baseRepo }]),suggestName: (baseRepo) => call('worktree:suggest-name', [{ baseRepo }]),create: (req) => call('worktree:create', [req]),discardPrecreated: (input) => call('worktree:discard-precreated', [input]),diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex 29a3a72c18..a6eef2367b 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -162,7 +162,13 @@"previewNotReadyTitle": "Not ready to create yet","previewReadySubtitle": "Confirming creates the session on the controlled device and queues the first message.","useWorktree": "Use worktree",+ "worktreeSourceBranch": "Source branch",+ "selectWorktreeBranchA11y": "Select the worktree source branch. Current: {{branch}}",+ "worktreeBranchesLoading": "Loading branches…",+ "worktreeBranchSaving": "Syncing the selected branch…",+ "worktreeBranchesRetry": "Could not load branches. Tap to retry","worktreeDetecting": "Detecting environment…",+ "worktreeRecovering": "Reconnecting and retrying automatically…","worktreeGitMissing": "git not detected — install it first","worktreeNotGitRepo": "Current directory is not a git repository","worktreeAlreadyInWorktree": "Already inside a worktree, nesting is not allowed",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 41e85d8a5c..1df9cd82e3 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -162,7 +162,13 @@"previewNotReadyTitle": "まだ作成できません","previewReadySubtitle": "確認すると、操作対象のデバイスにセッションを作成し、最初のメッセージをキューに追加します。","useWorktree": "worktree を使用",+ "worktreeSourceBranch": "ソースブランチ",+ "selectWorktreeBranchA11y": "worktree のソースブランチを選択。現在は {{branch}}",+ "worktreeBranchesLoading": "ブランチを読み込み中…",+ "worktreeBranchSaving": "選択したブランチを同期中…",+ "worktreeBranchesRetry": "ブランチを読み込めません。タップして再試行","worktreeDetecting": "環境を検出中…",+ "worktreeRecovering": "接続を復旧中です。自動的に再試行しています…","worktreeGitMissing": "git が検出されません。先にインストールしてください","worktreeNotGitRepo": "現在のディレクトリは git リポジトリではありません","worktreeAlreadyInWorktree": "すでに worktree 内です。ネストは禁止です",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex a5ad8fda68..3401c7d8c5 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -162,7 +162,13 @@"previewNotReadyTitle": "아직 만들 수 없습니다","previewReadySubtitle": "확인하면 제어 기기에 세션을 만들고 첫 메시지를 대기열에 추가합니다.","useWorktree": "worktree 사용",+ "worktreeSourceBranch": "소스 브랜치",+ "selectWorktreeBranchA11y": "worktree 소스 브랜치 선택. 현재 {{branch}}",+ "worktreeBranchesLoading": "브랜치 불러오는 중…",+ "worktreeBranchSaving": "선택한 브랜치 동기화 중…",+ "worktreeBranchesRetry": "브랜치를 불러오지 못했습니다. 탭하여 다시 시도","worktreeDetecting": "환경 감지 중…",+ "worktreeRecovering": "연결을 복구하는 중이며 자동으로 다시 시도하고 있습니다…","worktreeGitMissing": "git이 감지되지 않습니다. 먼저 설치하세요","worktreeNotGitRepo": "현재 디렉터리는 git 리포지토리가 아닙니다","worktreeAlreadyInWorktree": "이미 worktree 안에 있어 중첩이 금지됩니다",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 9448a82cec..733e0001eb 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -162,7 +162,13 @@"previewNotReadyTitle": "还不能创建","previewReadySubtitle": "确认后会在被控设备创建任务,并把首条消息加入队列。","useWorktree": "使用 worktree",+ "worktreeSourceBranch": "源分支",+ "selectWorktreeBranchA11y": "选择 worktree 源分支,当前 {{branch}}",+ "worktreeBranchesLoading": "正在读取分支…",+ "worktreeBranchSaving": "正在同步所选分支…",+ "worktreeBranchesRetry": "无法读取分支,点按重试","worktreeDetecting": "检测环境中…",+ "worktreeRecovering": "连接恢复中,正在自动重试…","worktreeGitMissing": "未检测到 git,请先安装","worktreeNotGitRepo": "当前目录不是 git 仓库","worktreeAlreadyInWorktree": "已在 worktree 中,禁止嵌套",diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.tsindex 98f5644009..fc9062ebce 100644--- a/apps/mobile/src/session/newSession.ts+++ b/apps/mobile/src/session/newSession.ts@@ -1,4 +1,5 @@import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';+import { collapseWorktreeDirForGrouping } from '@cindy/maker-shared/worktree-paths';import { i18n } from '@/i18n';import type { CreateSessionOptions, RemoteDirectoryEntry } from '@/device-link/mobileMakerTransport';import { reconcileEffortForModel, type ProviderModelRow } from './providerModelSections';@@ -276,8 +277,9 @@ export function buildRecentWorkspaceOptions(if (deviceId && session.deviceLinkDeviceId && session.deviceLinkDeviceId !== deviceId) continue;if (session.status === 'deleted') continue;if (session.workspaceKind !== 'project') continue;- const workingDir = session.workingDir?.trim();- if (!workingDir) continue;+ const rawWorkingDir = session.workingDir?.trim();+ if (!rawWorkingDir) continue;+ const workingDir = collapseWorktreeDirForGrouping(rawWorkingDir);const lastActivityAt = session.userSendAt ?? session.updatedAt ?? session.createdAt;const current = byPath.get(workingDir);if (!current) {diff --git a/apps/mobile/src/session/newSessionWorktree.ts b/apps/mobile/src/session/newSessionWorktree.tsindex 0bcfbbb875..f74ef90d8b 100644--- a/apps/mobile/src/session/newSessionWorktree.ts+++ b/apps/mobile/src/session/newSessionWorktree.ts@@ -6,13 +6,14 @@* 再以该路径 + 同一预生成 sessionId 走 createSession(两步共用 sessionId,工作端* close-session 时才能按 worktreeStore 绑定回收 worktree)。*- * 本模块只做纯函数(资格判定 / 播种归并 / create 入参组装 / 错误展示),不碰 React- * 与 transport 实例,便于 vitest 直接覆盖;接线在 app/sessions/new.tsx。+ * 本模块只做纯决策和可注入的小编排,不直接依赖 React 与 transport 实例,+ * 便于 vitest 直接覆盖;接线在 app/sessions/new.tsx。*/import type {MobileNewMakerDefaults,MobileWorktreeDetectCwdResult,} from '@/device-link/mobileMakerTransport';+import { isTransientRemoteError } from '@/device-link/remoteRetry';/** 资格不满足的原因(语义对齐桌面 newChat.worktree.{gitMissing,notGitRepo,alreadyInWorktree})。 */export type NewSessionWorktreeIneligibleReason =@@ -23,6 +24,7 @@ export type NewSessionWorktreeIneligibleReason =/*** worktree 开关的资格状态:* - probing:探测中(目录/设备刚变化,结果未回)→ 开关禁用 + 「检测环境中…」;+ * - recovering:瞬时断连/超时,页面会自动重试 → 开关禁用 + 恢复连接 caption;* - eligible:可用,携带 create 所需的 baseRepo(repoRoot)与 sourceBranch(当前分支);* - ineligible:环境不满足 → 开关禁用 + 原因 caption;* - unsupported:老被控端无 worktree 通道(CHANNEL_NOT_ALLOWED)→ 整行隐藏;@@ -30,6 +32,7 @@ export type NewSessionWorktreeIneligibleReason =*/export type NewSessionWorktreeEligibility =| { status: 'probing' }+ | { status: 'recovering' }| { status: 'eligible'; baseRepo: string; sourceBranch: string }| { status: 'ineligible'; reason: NewSessionWorktreeIneligibleReason }| { status: 'unsupported' }@@ -46,6 +49,24 @@ export interface NewSessionWorktreeProbeSnapshot {eligibility: NewSessionWorktreeEligibility;}+/** 用户显式选择的源分支只属于发起选择时的设备 + 工作目录,不得跨目标复用。 */+export interface NewSessionWorktreeBranchSelectionSnapshot {+ target: NewSessionWorktreeProbeTarget;+ sourceBranch: string;+}++/** list-branches 回包只有请求序号与设备/cwd 都仍是最新目标时才允许落 state。 */+export function shouldAcceptWorktreeBranchListResult(input: {+ requestSeq: number;+ latestSeq: number;+ requestTarget: NewSessionWorktreeProbeTarget;+ latestTarget: NewSessionWorktreeProbeTarget;+}): boolean {+ return input.requestSeq === input.latestSeq+ && input.requestTarget.deviceId === input.latestTarget.deviceId+ && input.requestTarget.workingDir.trim() === input.latestTarget.workingDir.trim();+}+/*** 只向当前选择暴露同 target 的结果。React effect 要到 commit 后才会把 state 重置为* probing;render 阶段先做这道同步 fence,用户切项目/设备后立即创建也不会拿旧 baseRepo。@@ -64,11 +85,34 @@ export function worktreeEligibilityForTarget(return snapshot.eligibility;}+/**+ * 读取当前目标真正应展示 / 创建所用的源分支:同目标的显式选择优先,否则回落+ * detect-cwd 的当前分支。target fence 与 eligibility fence 双保险,切设备或项目后的+ * 同步 render 绝不会把上一仓库的同名/异名分支带过去。+ */+export function worktreeSourceBranchForTarget(+ snapshot: NewSessionWorktreeBranchSelectionSnapshot | null,+ target: NewSessionWorktreeProbeTarget,+ eligibility: NewSessionWorktreeEligibility,+): string {+ if (+ snapshot+ && snapshot.target.deviceId === target.deviceId+ && snapshot.target.workingDir.trim() === target.workingDir.trim()+ && snapshot.sourceBranch.trim()+ ) {+ return snapshot.sourceBranch.trim();+ }+ return eligibility.status === 'eligible'+ ? eligibility.sourceBranch.trim() || 'HEAD'+ : 'HEAD';+}+/*** 把工作端 detect-cwd 回包归并为资格状态。判定顺序对齐桌面 WorktreeChipsRow:* gitInstalled → isGitRepo → isInsideWorktree 逐项短路。* baseRepo 取 repoRoot(工作端 git rev-parse --show-toplevel),缺失回落 workingDir;- * sourceBranch 取当前分支(手机没有分支选择 UI,等价于桌面分支 chip 回填 current),+ * sourceBranch 先取当前分支,作为移动端分支选择器尚未显式选择时的默认值;* detached HEAD 时 currentBranch 缺失,必须回落 'HEAD' 才能从当前 commit 派生;* 不能猜 main(仓库未必有 main,也不能静默偏离当前 checkout)。*@@ -93,7 +137,8 @@ export function resolveWorktreeEligibility(/*** detect-cwd 抛错的归并:老被控端 CHANNEL_NOT_ALLOWED → unsupported(整行隐藏,- * 「worktree 不可用」降级);其余(断连/超时)→ detect-failed(行保留、开关禁用)。+ * 「worktree 不可用」降级);断连/超时 → recovering(页面自动重试);其余未知错误+ * → detect-failed(行保留、开关禁用)。** 真实 wire 形状:被控端 dispatch 回 { code:'CHANNEL_NOT_ALLOWED', message:"channel* 'worktree:detect-cwd' not allowed remotely" },移动端 unwrapInvoke 抛@@ -106,14 +151,37 @@ export function worktreeEligibilityFromError(error: unknown): NewSessionWorktreeconst message = error instanceof Error ? error.message : typeof error === 'string' ? error : String(error);const text = `${typeof code === 'string' ? code : ''} ${message}`;if (text.includes('CHANNEL_NOT_ALLOWED')) return { status: 'unsupported' };+ // DEVICE_UNRESPONSIVE 是本机熔断器为了阻止原地重试风暴而产出的快速失败,+ // 对页面生命周期仍是可恢复状态:Context 的代表性探测会自动关熔断,本页定时+ // 重探即可,不能把它固化成“目录环境错误”。+ if (text.includes('DEVICE_UNRESPONSIVE')) return { status: 'recovering' };+ if (isTransientRemoteError(error)) return { status: 'recovering' };return { status: 'detect-failed' };}-/** 播种归并:工作端 get-new-maker-defaults 的 worktreeEnabled,缺字段/形状异常一律按未勾选。 */+/**+ * 读取工作端 get-new-maker-defaults 的明确偏好。缺字段/形状异常返回 null,+ * 由控制端保留当前镜像;全新设备的镜像自身默认未勾选。+ */export function seedWorktreeEnabled(defaults: MobileNewMakerDefaults | null | undefined,-): boolean {- return defaults?.worktreeEnabled === true;+): boolean | null {+ return typeof defaults?.worktreeEnabled === 'boolean'+ ? defaults.worktreeEnabled+ : null;+}++/**+ * 手机只是远程控制器:checkbox 偏好先由工作端接受,再更新手机内存镜像。+ * apply 失败时 mirror 绝不执行,避免留下一份仅手机生效的假偏好。+ */+export async function applyWorktreePreferenceOnHost(input: {+ enabled: boolean;+ apply: (enabled: boolean) => Promise<void>;+ mirror: (enabled: boolean) => void;+}): Promise<void> {+ await input.apply(input.enabled);+ input.mirror(input.enabled);}/** 开关行是否显示:project 模式 + 已选 workingDir,且通道未被判定为不可用。 */@@ -127,6 +195,27 @@ export function shouldShowWorktreeToggle(input: {&& input.eligibility.status !== 'unsupported';}+/**+ * checkbox 正在写工作端时不能按旧镜像创建;已勾选且当前目标尚未确认 eligible 时,+ * 也不能静默退化为普通目录会话。unsupported 是老工作端的兼容降级:控件整行隐藏,+ * 继续允许创建普通会话,避免用户被一份无法在该工作端关闭的旧镜像永久卡住。+ */+export function shouldBlockNewSessionCreateForWorktree(input: {+ /** 当前草稿是否真的会使用 worktree:仅 project + 已选目录。 */+ applicable: boolean;+ enabled: boolean;+ eligibility: NewSessionWorktreeEligibility;+ preferenceSaving: boolean;+}): boolean {+ // 对话工作区 / 尚未选目录时 worktree 控件本就隐藏,工作端记忆不能反向卡住+ // 普通会话创建;切回具体项目后再按该项目资格决定是否阻止。+ if (!input.applicable) return false;+ if (input.preferenceSaving) return true;+ return input.enabled+ && input.eligibility.status !== 'eligible'+ && input.eligibility.status !== 'unsupported';+}+/** 资格未通过时的 caption 文案 key(session.json);eligible/unsupported 无 caption。 */export function worktreeEligibilityCaptionKey(eligibility: NewSessionWorktreeEligibility,@@ -134,6 +223,8 @@ export function worktreeEligibilityCaptionKey(switch (eligibility.status) {case 'probing':return 'session.new.worktreeDetecting';+ case 'recovering':+ return 'session.new.worktreeRecovering';case 'ineligible':switch (eligibility.reason) {case 'gitMissing':@@ -174,6 +265,8 @@ export interface WorktreeCreateRequest {export function buildWorktreeCreateRequest(input: {sessionId: string;eligibility: Extract<NewSessionWorktreeEligibility, { status: 'eligible' }>;+ /** 当前目标的显式源分支;省略时兼容旧调用方,回落 detect-cwd 当前分支。 */+ sourceBranch?: string | null;suggestedName: string | null | undefined;recoveryKey: string;now?: number;@@ -182,7 +275,7 @@ export function buildWorktreeCreateRequest(input: {sessionId: input.sessionId,baseRepo: input.eligibility.baseRepo,name: normalizeSuggestedWorktreeName(input.suggestedName, input.now),- sourceBranch: input.eligibility.sourceBranch,+ sourceBranch: input.sourceBranch?.trim() || input.eligibility.sourceBranch,recoveryKey: input.recoveryKey,};}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 711afb7b72..7cf5f67873 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -47,6 +47,16 @@ export interface RemoteNewMakerWorktreePreference {const EMPTY_NEW_MAKER_WORKTREE_PREFERENCE: RemoteNewMakerWorktreePreference =Object.freeze({ enabled: false, revision: 0 });+/**+ * 工作端拥有的 New Maker worktree 源分支镜像。null 表示该 device + canonical+ * baseRepo 尚无显式选择;revision 完全采用工作端快照,手机不自行递增。+ */+export type RemoteNewMakerWorktreeBranchPreference = {+ baseRepo: string;+ sourceBranch: string;+ revision: number;+} | null;+/*** 会话元数据在途写登记(app 级单例):首页乐观写(置顶/归档/删除/重命名)begin 时* track、settle 时 release;`sessions:patched` push 应用前经 filterPatch 遮蔽在途@@ -118,8 +128,15 @@ const EMPTY_SESSION_RUN_STATUS: RemoteSessionRunStatus = Object.freeze({});const shards = new Map<string, DeviceShard>();-// 工作端拥有的 New Maker worktree 偏好按设备隔离;push 属 sessions topic,无 sessionId。+// 工作端拥有的 New Maker worktree 偏好按设备隔离;这里只是不持久化的显示镜像,+// push 属 sessions topic,无 sessionId。唯一持久副本仍在被控端现有 Cindy 配置里。const newMakerWorktreePreferences = new Map<string, RemoteNewMakerWorktreePreference>();+// deviceId → canonical baseRepo → 工作端权威分支快照。分支与 checkbox 是两份独立镜像;+// 任一分支 pull / push / write-back 都不得改动 newMakerWorktreePreferences。+const newMakerWorktreeBranchPreferences = new Map<+ string,+ Map<string, Exclude<RemoteNewMakerWorktreeBranchPreference, null>>+>();const messages = new Map<string, RemoteMessage[]>();// The maker event is broadcast before its async DB create/update completes. Keep the latest// plan snapshot briefly in the session mirror so a late initial `messages:created` row cannot@@ -1998,6 +2015,11 @@ export const remoteSessionStore = {if (enabled !== null) this.setNewMakerWorktreePreference(deviceId, enabled);return;}+ if (channel === 'maker:new-maker-worktree-branch:changed') {+ const snapshot = readPushedNewMakerWorktreeBranchPreference(payload);+ if (snapshot !== null) this.setNewMakerWorktreeBranchPreference(deviceId, snapshot);+ return;+ }if (channel === 'local-db:sessions:created') {reseedHandlers.get(deviceId)?.forEach((handler) => handler());return;@@ -2543,6 +2565,7 @@ export const remoteSessionStore = {removeDevice(deviceId: string): void {const hadShard = shards.delete(deviceId);const hadWorktreePreference = newMakerWorktreePreferences.delete(deviceId);+ const hadWorktreeBranchPreferences = newMakerWorktreeBranchPreferences.delete(deviceId);// Sweep per-session maps for this device regardless of whether the shard still exists, and// drop the index entries too — otherwise sessionDeviceIndex (and any maps it points at)// leak orphans when the shard was already pruned.@@ -2580,7 +2603,12 @@ export const remoteSessionStore = {removedSession = true;}}- if (!hadShard && !removedSession && !hadWorktreePreference) return;+ if (+ !hadShard+ && !removedSession+ && !hadWorktreePreference+ && !hadWorktreeBranchPreferences+ ) return;bumpMessageVersion();recomputeSessions();},@@ -2588,6 +2616,7 @@ export const remoteSessionStore = {clear(): void {shards.clear();newMakerWorktreePreferences.clear();+ newMakerWorktreeBranchPreferences.clear();messages.clear();livePlanSnapshots.clear();pendingInteractions.clear();@@ -2680,6 +2709,66 @@ export const remoteSessionStore = {?? EMPTY_NEW_MAKER_WORKTREE_PREFERENCE;},+ setNewMakerWorktreeBranchPreference(+ deviceId: string,+ snapshot: RemoteNewMakerWorktreeBranchPreference,+ ): void {+ if (!deviceId || snapshot === null) return;+ const baseRepo = snapshot.baseRepo.trim();+ const sourceBranch = snapshot.sourceBranch.trim();+ if (+ !baseRepo+ || !sourceBranch+ || !Number.isInteger(snapshot.revision)+ || snapshot.revision < 0+ ) return;++ let byRepo = newMakerWorktreeBranchPreferences.get(deviceId);+ const current = byRepo?.get(baseRepo);+ if (current) {+ // revision 由 host 按 canonical repo 单调递增。旧快照不能覆盖;相等只接受+ // 完全相同的幂等 echo,同 revision 的冲突值也必须拒绝。+ if (snapshot.revision < current.revision) return;+ if (snapshot.revision === current.revision) return;+ }+ if (!byRepo) {+ byRepo = new Map();+ newMakerWorktreeBranchPreferences.set(deviceId, byRepo);+ }+ byRepo.set(baseRepo, {+ baseRepo,+ sourceBranch,+ revision: snapshot.revision,+ });+ // 同一 sourceBranch 的新 host revision 也必须发布:它给在途 pull / apply 回包做 fence。+ emit();+ },++ /**+ * GET 的 null 是工作端对该 repo「当前没有偏好」的权威回答,不是漏包。+ * 桌面进程重启后 host revision 会从头开始;先删掉手机保存的旧高 revision,+ * 后续 rev1 snapshot / push 才有资格成为新进程的真相。+ */+ clearNewMakerWorktreeBranchPreference(+ deviceId: string,+ baseRepo: string,+ ): void {+ const normalizedBaseRepo = baseRepo.trim();+ if (!deviceId || !normalizedBaseRepo) return;+ const byRepo = newMakerWorktreeBranchPreferences.get(deviceId);+ if (!byRepo?.delete(normalizedBaseRepo)) return;+ if (byRepo.size === 0) newMakerWorktreeBranchPreferences.delete(deviceId);+ emit();+ },++ getNewMakerWorktreeBranchPreference(+ deviceId: string | null | undefined,+ baseRepo: string | null | undefined,+ ): RemoteNewMakerWorktreeBranchPreference {+ if (!deviceId || !baseRepo?.trim()) return null;+ return newMakerWorktreeBranchPreferences.get(deviceId)?.get(baseRepo.trim()) ?? null;+ },+getPendingInteractions(sessionId: string): PendingInteraction[] {return pendingInteractions.get(sessionId) ?? emptyPendingInteractions;},@@ -2988,6 +3077,28 @@ function readPushedNewMakerWorktreeEnabled(payload: unknown): boolean | null {return null;}+function readPushedNewMakerWorktreeBranchPreference(+ payload: unknown,+): RemoteNewMakerWorktreeBranchPreference {+ if (!isRecord(payload)) return null;+ const baseRepo = payload.baseRepo;+ const sourceBranch = payload.sourceBranch;+ const revision = payload.revision;+ if (+ typeof baseRepo !== 'string'+ || !baseRepo.trim()+ || typeof sourceBranch !== 'string'+ || !sourceBranch.trim()+ || !Number.isInteger(revision)+ || (revision as number) < 0+ ) return null;+ return {+ baseRepo: baseRepo.trim(),+ sourceBranch: sourceBranch.trim(),+ revision: revision as number,+ };+}+function hasDeviceLinkTruncationMarker(value: Record<string, unknown> | null): boolean {return value?.[DEVICE_LINK_TRUNCATED_FLAG] === true;}@@ -3110,6 +3221,16 @@ export function useRemoteNewMakerWorktreePreference();}+export function useRemoteNewMakerWorktreeBranchPreference(+ deviceId: string | null | undefined,+ baseRepo: string | null | undefined,+): RemoteNewMakerWorktreeBranchPreference {+ return useSyncExternalStore(+ remoteSessionStore.subscribe,+ () => remoteSessionStore.getNewMakerWorktreeBranchPreference(deviceId, baseRepo),+ );+}+export function useSessionPendingInteractions(sessionId: string): PendingInteraction[] {return useSyncExternalStore(remoteSessionStore.subscribe,diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex bc5b41e8c7..1e2feb2e86 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -97,10 +97,12 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {it('放行 device-link 远程草稿镜像只读读(控制端 seed 被控端当前 New Maker 草稿)', () => {expect(REMOTE_INVOKE_ALLOWLIST.has('maker:get-new-maker-defaults')).toBe(true);+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:get-new-maker-worktree-branch-pref')).toBe(true);});it('放行 device-link 模型列表 effort/fast 写穿(草稿 + 会话非选中,控制端→被控端)', () => {expect(REMOTE_INVOKE_ALLOWLIST.has('maker:apply-new-maker-draft-pref')).toBe(true);+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:apply-new-maker-worktree-branch-pref')).toBe(true);expect(REMOTE_INVOKE_ALLOWLIST.has('maker:set-session-model-pref')).toBe(true);});@@ -322,6 +324,7 @@ describe('PUSH_FORWARD_ALLOWLIST', () => {it('转发 device-link 模型列表变更(草稿全量 + 会话非选中)', () => {expect(PUSH_FORWARD_ALLOWLIST.has('maker:new-maker-draft:changed')).toBe(true);+ expect(PUSH_FORWARD_ALLOWLIST.has('maker:new-maker-worktree-branch:changed')).toBe(true);expect(PUSH_FORWARD_ALLOWLIST.has('maker:session-model-pref:changed')).toBe(true);});diff --git a/packages/device-link/src/__tests__/topics.test.ts b/packages/device-link/src/__tests__/topics.test.tsindex 6841b43798..a11b05e9d1 100644--- a/packages/device-link/src/__tests__/topics.test.ts+++ b/packages/device-link/src/__tests__/topics.test.ts@@ -33,6 +33,11 @@ describe('topicForPush', () => {expect(topicForPush('maker:new-maker-draft:changed', { claudeCode: {}, codex: {} })).toBe('sessions',);+ expect(topicForPush('maker:new-maker-worktree-branch:changed', {+ baseRepo: '/tmp/repo',+ sourceBranch: 'feature/mobile',+ revision: 2,+ })).toBe('sessions');});it('learn:event → sessions(账号级:run 关联触发/蒸馏两个任务,单 sessionId 路由会漏)', () => {diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 71987b6dbf..33b509ac02 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -222,6 +222,11 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [// UI 副作用);回读经 maker:get-new-maker-defaults + NEW_MAKER_DRAFT_CHANGED 回流。// 老被控端无 handler → CHANNEL_NOT_ALLOWED → 控制端吞掉降级(勾选仅本次草稿生效)。'maker:apply-new-maker-worktree-pref',+ // device-link 新建 worktree 源分支镜像:branch 选择属于被控端 canonical baseRepo,+ // 控制端先按 repo 拉取、显式选择时写穿,被控端返回/广播带 revision 的权威 snapshot。+ // GET 只读 main 内存镜像;APPLY 只更新该 repo 的 future-session 偏好,不执行 git/fs。+ 'maker:get-new-maker-worktree-branch-pref',+ 'maker:apply-new-maker-worktree-branch-pref',// 模型供应商目录(只读):远程会话的模型选择器据此 1:1 镜像被控端的「供应商+模型」结构。// 被控端 dispatch 在返回前剥离 routing 等执行字段(见 device-link/dispatch.ts),只回显示用字段。'maker:provider:list',@@ -525,6 +530,9 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([// 控制端的远程项目草稿据此实时刷新显示镜像(remoteDraftState)。账号 / 全局级、无 sessionId →// topics.ts 的 ACCOUNT_CHANNELS 把它并入 `sessions` topic(控制端按设备订阅 sessions)。'maker:new-maker-draft:changed',+ // 被控端 repo-scoped worktree 源分支选择变化;无 sessionId,topics.ts 按账号级+ // 并入 sessions topic,控制端再按来源 deviceId + payload.baseRepo 精确消费。+ 'maker:new-maker-worktree-branch:changed',// 被控端会话「非选中模型」effort/fast 变更:被控端本地改 / 应用控制端写后广播,带 sessionId →// 默认路由到 session:<id> topic;控制端打开该远程会话时已订阅,据此刷新显示镜像。'maker:session-model-pref:changed',diff --git a/packages/device-link/src/topics.ts b/packages/device-link/src/topics.tsindex de7a101454..3acdf88128 100644--- a/packages/device-link/src/topics.ts+++ b/packages/device-link/src/topics.ts@@ -92,6 +92,7 @@ const ACCOUNT_CHANNELS: ReadonlySet<string> = new Set([// 被控端「当前 New Maker 草稿」全量变更:账号 / 全局级(无 sessionId),并入 `sessions` topic// 随设备列表订阅一起走(控制端打开远程项目草稿时据此实时刷新),不另开一档 topic。'maker:new-maker-draft:changed',+ 'maker:new-maker-worktree-branch:changed',// /learn run 状态机流转:payload = { type, run },run 同时关联触发会话与蒸馏会话// (状态卡两处都渲染),按单一 sessionId 路由会漏一边 → 按账号级并入 `sessions` topic// (低频状态机事件,量极小)。diff --git a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts b/packages/maker-shared/src/__tests__/deviceLinkContract.test.tsindex b4e8fb164b..724b889ab9 100644--- a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts+++ b/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts@@ -41,6 +41,9 @@ describe('device-link shared contract', () => {expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:schedule:delete-run');expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:usage:codex-rate-limits');expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:usage:codex-rate-limit-reset');+ expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:get-new-maker-worktree-branch-pref');+ expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:apply-new-maker-worktree-branch-pref');+ expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('worktree:list-branches');expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('worktree:discard-precreated');expect(MOBILE_REMOTE_INVOKE_CHANNELS).not.toContain(DEVICE_LINK_VOICE_CREDENTIAL_SYNC_CHANNEL);expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain(DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL);diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.tsindex 541689d931..868c4a1333 100644--- a/packages/maker-shared/src/deviceLinkContract.ts+++ b/packages/maker-shared/src/deviceLinkContract.ts@@ -288,6 +288,10 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [// 根字段。老被控端 CHANNEL_NOT_ALLOWED → 吞掉降级(勾选仅本次草稿生效)。'maker:get-new-maker-defaults','maker:apply-new-maker-worktree-pref',+ // 工作端 canonical baseRepo scoped 的 worktree 源分支 live 镜像。GET 未命中返回 null;+ // APPLY 返回并广播 { baseRepo, sourceBranch, revision },同值写也推进 revision。+ 'maker:get-new-maker-worktree-branch-pref',+ 'maker:apply-new-maker-worktree-branch-pref',// 模型选择列表元信息:被控端视角的模型单价表(只读;拉不到 → 隐藏价格)。'maker:usage:model-pricing',// Codex app-server 官方控制面:只读额度/reset 次数 + 人工确认后的单次 reset。@@ -359,6 +363,7 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = ['fs:mkdir-p',// —— Worktree(新建会话前在工作端预建隔离 worktree;git/fs 全在被控端执行)——// - detect-cwd:资格探测(git 已装 / 是 git 仓库 / 未在 worktree 内)+ repoRoot/currentBranch;+ // - list-branches:工作端返回本地分支列表 + 当前分支,供控制端选择 sourceBranch;// - suggest-name:工作端按仓库上下文生成 worktree 名;// - create:两步建会话第一步——同预生成 sessionId 先建 worktree 拿路径,再以该路径调// maker:create-session(与桌面控制端 NewMakerDraftRoute 的远程流程同构);@@ -367,6 +372,7 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [// INVOKE_TIMEOUT_OVERRIDES_MS,移动端 invoke 必须带同一映射)。// 老被控端无这些 channel → CHANNEL_NOT_ALLOWED → 手机端按「worktree 不可用」降级。'worktree:detect-cwd',+ 'worktree:list-branches','worktree:suggest-name','worktree:create','worktree:discard-precreated',