Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): keep unsupported worktree exit path
kafeifei0bd835a7239b
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 0f8d0eb708..82f2fd4a33 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -6095,7 +6095,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)logCreateSession: (fields) => log.info('create-session invoked', fields),warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),},- });+ );registerPrecreatedWorktreeDiscardHandler(makerSessionRegistry, {assertCaller: (event) => {diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 8144c9a4af..149f3a4301 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -876,11 +876,13 @@ export default function NewRemoteSessionScreen() {: [],[worktreeBranchList, worktreeBranchListMatchesTarget],);- // worktree 开关行:project + 已选目录才显示;老被控端(unsupported)整行隐藏。+ // 老被控端通常隐藏开关;若工作端旧镜像仍为 ON,则保留显式关闭入口,避免+ // fail-closed 后既不能创建、也不能解除状态。const worktreeRowVisible = shouldShowWorktreeToggle({workspaceKind: draft.workspaceKind,workingDir: draft.workingDir,eligibility: worktreeEligibility,+ enabled: worktreeEnabled,});const worktreePreferenceSaving =selectedDeviceId != null && worktreePreferenceSavingDeviceId === selectedDeviceId;@@ -1655,7 +1657,8 @@ export default function NewRemoteSessionScreen() {}, [draft.agentKind, draft.permissionMode, patchDraft]);// —— worktree 资格探测:目录 / 设备 / 链路变化即重探(seq 防竞态,旧结果作废)。- // CHANNEL_NOT_ALLOWED(老被控端)→ unsupported 整行隐藏;其余失败保留行但禁用。+ // CHANNEL_NOT_ALLOWED(老被控端)→ unsupported;OFF 时隐藏,旧 ON 镜像保留关闭+ // 入口;其余失败保留行但禁用。useEffect(() => {const cwd = draft.workspaceKind === 'project' ? draft.workingDir.trim() : '';const seq = ++worktreeDetectSeqRef.current;@@ -1982,6 +1985,11 @@ export default function NewRemoteSessionScreen() {void applyWorktreePreferenceOnHost({enabled: next,apply: maker.applyNewMakerWorktreePref,+ // unsupported 可能是“有偏好写穿、缺安全 worktree 能力”,也可能是最老端+ // 连偏好 channel 都没有:先写 host;只有后者且用户明确点 OFF 时才清手机+ // 保留的旧 ON 镜像。断连/超时不降级,仍保留 ON + fail closed。+ allowUnsupportedDisableFallback:+ !next && worktreeEligibility.status === 'unsupported',mirror: (enabled) => {if (worktreePreferenceWriteSeqRef.current !== writeSeq) return;// 权威 push 或其它显式操作若已先到,它拥有更新 revision;@@ -1999,7 +2007,13 @@ export default function NewRemoteSessionScreen() {setWorktreePreferenceSavingDeviceId(null);}});- }, [maker, selectedDeviceId, worktreeEnabled, worktreePreferenceSaving]);+ }, [+ maker,+ selectedDeviceId,+ worktreeEnabled,+ worktreePreferenceSaving,+ worktreeEligibility.status,+ ]);useEffect(() => {const tracker = createMobileVoiceDictionaryLearningTracker({diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex aac376d1b8..66a523a142 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -1119,6 +1119,10 @@ describe('new session worktree wiring (source locks)', () => {// 显式点击才写穿工作端记忆;工作端接受后才更新手机镜像。expect(newSource).toContain('applyWorktreePreferenceOnHost({');expect(newSource).toContain('apply: maker.applyNewMakerWorktreePref,');+ expect(newSource).toContain(+ "!next && worktreeEligibility.status === 'unsupported',",+ );+ expect(newSource).toContain('enabled: worktreeEnabled,');expect(newSource).not.toContain('void maker.applyNewMakerWorktreePref(next).catch(() => undefined);',);diff --git a/apps/mobile/src/__tests__/newSessionWorktree.test.ts b/apps/mobile/src/__tests__/newSessionWorktree.test.tsindex 02f86975d2..ae22de0a44 100644--- a/apps/mobile/src/__tests__/newSessionWorktree.test.ts+++ b/apps/mobile/src/__tests__/newSessionWorktree.test.ts@@ -188,7 +188,7 @@ describe('shouldAcceptWorktreeBranchListResult', () => {});describe('worktreeEligibilityFromError', () => {- it('CHANNEL_NOT_ALLOWED(老被控端)→ unsupported(整行隐藏降级)', () => {+ it('CHANNEL_NOT_ALLOWED(老被控端)→ unsupported(由 UI 按镜像状态决定隐藏或退出入口)', () => {// 真实 wire 形状:DeviceLinkError 的 code 在 .code 字段,message **不含**该字面量// (被控端 dispatch 回 "channel '...' not allowed remotely")——必须靠结构化 code 命中。expect(worktreeEligibilityFromError(@@ -258,6 +258,37 @@ describe('applyWorktreePreferenceOnHost', () => {})).rejects.toThrow('offline');expect(mirror).not.toHaveBeenCalled();});++ it('unsupported 老端允许用户显式关闭旧 ON 镜像,但瞬时失败与开启操作不本地降级', async () => {+ const channelNotAllowed = Object.assign(new Error('channel not allowed'), {+ code: 'CHANNEL_NOT_ALLOWED',+ });+ const mirror = vi.fn();+ await applyWorktreePreferenceOnHost({+ enabled: false,+ apply: vi.fn(async () => { throw channelNotAllowed; }),+ mirror,+ allowUnsupportedDisableFallback: true,+ });+ expect(mirror).toHaveBeenCalledWith(false);++ mirror.mockClear();+ await expect(applyWorktreePreferenceOnHost({+ enabled: false,+ apply: vi.fn(async () => { throw new Error('offline'); }),+ mirror,+ allowUnsupportedDisableFallback: true,+ })).rejects.toThrow('offline');+ expect(mirror).not.toHaveBeenCalled();++ await expect(applyWorktreePreferenceOnHost({+ enabled: true,+ apply: vi.fn(async () => { throw channelNotAllowed; }),+ mirror,+ allowUnsupportedDisableFallback: true,+ })).rejects.toThrow('channel not allowed');+ expect(mirror).not.toHaveBeenCalled();+ });});describe('shouldShowWorktreeToggle / caption key', () => {@@ -265,12 +296,13 @@ describe('shouldShowWorktreeToggle / caption key', () => {status: 'eligible', baseRepo: '/repo', sourceBranch: 'main',};- it('project + 已选目录且通道可用才显示;dialogue / 空目录 / unsupported 隐藏', () => {- expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: '/repo', eligibility: eligible })).toBe(true);- expect(shouldShowWorktreeToggle({ workspaceKind: 'dialogue', workingDir: '/repo', eligibility: eligible })).toBe(false);- expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: ' ', eligibility: eligible })).toBe(false);- expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: '/repo', eligibility: { status: 'unsupported' } })).toBe(false);- expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: '/repo', eligibility: { status: 'probing' } })).toBe(true);+ it('project + 已选目录才显示;unsupported 仅在旧 ON 镜像需要退出入口时显示', () => {+ expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: '/repo', eligibility: eligible, enabled: false })).toBe(true);+ expect(shouldShowWorktreeToggle({ workspaceKind: 'dialogue', workingDir: '/repo', eligibility: eligible, enabled: true })).toBe(false);+ expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: ' ', eligibility: eligible, enabled: true })).toBe(false);+ expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: '/repo', eligibility: { status: 'unsupported' }, enabled: false })).toBe(false);+ expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: '/repo', eligibility: { status: 'unsupported' }, enabled: true })).toBe(true);+ expect(shouldShowWorktreeToggle({ workspaceKind: 'project', workingDir: '/repo', eligibility: { status: 'probing' }, enabled: false })).toBe(true);});it('caption key 覆盖探测中 / 三种不合格原因 / 探测失败;eligible 无 caption', () => {@@ -281,7 +313,7 @@ describe('shouldShowWorktreeToggle / caption key', () => {expect(worktreeEligibilityCaptionKey({ status: 'ineligible', reason: 'alreadyInWorktree' })).toBe('session.new.worktreeAlreadyInWorktree');expect(worktreeEligibilityCaptionKey({ status: 'detect-failed' })).toBe('session.new.worktreeDetectFailed');expect(worktreeEligibilityCaptionKey(eligible)).toBeNull();- expect(worktreeEligibilityCaptionKey({ status: 'unsupported' })).toBeNull();+ expect(worktreeEligibilityCaptionKey({ status: 'unsupported' })).toBe('session.new.worktreeUnsupported');});});diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex a563505be5..7d282f311d 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -174,6 +174,7 @@"worktreeNotGitRepo": "Current directory is not a git repository","worktreeAlreadyInWorktree": "Already inside a worktree, nesting is not allowed","worktreeDetectFailed": "Could not check this directory — reselect it later and try again",+ "worktreeUnsupported": "This desktop cannot safely create worktrees. Turn worktree off to continue, or update the desktop app.","worktreeCreateFailed": "Failed to create worktree: {{message}}","worktreeRecoveryStateFailed": "Could not save the worktree recovery state. Try again.","worktreeCleanupPending": "The previous worktree is still awaiting cleanup. Reconnect the device and try again."diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 02e88428be..fb828b111f 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -174,6 +174,7 @@"worktreeNotGitRepo": "現在のディレクトリは git リポジトリではありません","worktreeAlreadyInWorktree": "すでに worktree 内です。ネストは禁止です","worktreeDetectFailed": "ディレクトリ環境を確認できません。後でディレクトリを選び直してもう一度お試しください",+ "worktreeUnsupported": "このデスクトップでは worktree を安全に作成できません。続行するには worktree をオフにするか、デスクトップアプリを更新してください。","worktreeCreateFailed": "worktree の作成に失敗しました:{{message}}","worktreeRecoveryStateFailed": "worktree の復旧状態を保存できませんでした。もう一度お試しください。","worktreeCleanupPending": "前回の worktree はまだクリーンアップ待ちです。デバイスを再接続してから再試行してください。"diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 4fc2bb0e35..0cb886dd21 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -174,6 +174,7 @@"worktreeNotGitRepo": "현재 디렉터리는 git 리포지토리가 아닙니다","worktreeAlreadyInWorktree": "이미 worktree 안에 있어 중첩이 금지됩니다","worktreeDetectFailed": "디렉터리 환경을 확인할 수 없습니다. 나중에 디렉터리를 다시 선택해 시도하세요",+ "worktreeUnsupported": "이 데스크톱에서는 worktree를 안전하게 만들 수 없습니다. 계속하려면 worktree를 끄거나 데스크톱 앱을 업데이트하세요.","worktreeCreateFailed": "worktree 생성 실패: {{message}}","worktreeRecoveryStateFailed": "worktree 복구 상태를 저장할 수 없습니다. 다시 시도하세요.","worktreeCleanupPending": "이전 worktree가 아직 정리 대기 중입니다. 기기를 다시 연결한 후 재시도하세요."diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex d25867c3ac..28e93de42e 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -174,6 +174,7 @@"worktreeNotGitRepo": "当前目录不是 git 仓库","worktreeAlreadyInWorktree": "已在 worktree 中,禁止嵌套","worktreeDetectFailed": "无法检测目录环境,可稍后重选目录再试",+ "worktreeUnsupported": "当前桌面端无法安全创建 worktree,请关闭 worktree 后继续,或升级桌面端。","worktreeCreateFailed": "worktree 创建失败:{{message}}","worktreeRecoveryStateFailed": "无法保存 worktree 恢复状态,请重试。","worktreeCleanupPending": "上一次 worktree 仍待回收,请重新连接设备后再试。"diff --git a/apps/mobile/src/session/newSessionWorktree.ts b/apps/mobile/src/session/newSessionWorktree.tsindex 471da78d84..ea5c115705 100644--- a/apps/mobile/src/session/newSessionWorktree.ts+++ b/apps/mobile/src/session/newSessionWorktree.ts@@ -27,7 +27,7 @@ export type NewSessionWorktreeIneligibleReason =* - recovering:瞬时断连/超时,页面会自动重试 → 开关禁用 + 恢复连接 caption;* - eligible:可用,携带 create 所需的 baseRepo(repoRoot)与 sourceBranch(当前分支);* - ineligible:环境不满足 → 开关禁用 + 原因 caption;- * - unsupported:老被控端无 worktree 通道(CHANNEL_NOT_ALLOWED)→ 整行隐藏;+ * - unsupported:老被控端缺安全 worktree 能力;OFF 时隐藏,旧 ON 镜像保留关闭入口;* - detect-failed:探测失败(断连/超时等非通道原因)→ 开关禁用 + 失败 caption。*/export type NewSessionWorktreeEligibility =@@ -136,8 +136,8 @@ export function resolveWorktreeEligibility(}/**- * detect-cwd 抛错的归并:老被控端 CHANNEL_NOT_ALLOWED → unsupported(整行隐藏,- * 「worktree 不可用」降级);断连/超时 → recovering(页面自动重试);其余未知错误+ * detect-cwd 抛错的归并:老被控端 CHANNEL_NOT_ALLOWED → unsupported;断连/超时+ * → recovering(页面自动重试);其余未知错误* → detect-failed(行保留、开关禁用)。** 真实 wire 形状:被控端 dispatch 回 { code:'CHANNEL_NOT_ALLOWED', message:"channel@@ -147,14 +147,11 @@ export function resolveWorktreeEligibility(* 字符串错误的兜底;同时容忍 relay 包装的 DEVICE_LINK_CHANNEL_NOT_ALLOWED 变体。*/export function worktreeEligibilityFromError(error: unknown): NewSessionWorktreeEligibility {- const code = (error as { code?: unknown } | null | undefined)?.code;- const 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' };+ if (isChannelNotAllowedError(error)) return { status: 'unsupported' };// DEVICE_UNRESPONSIVE 是本机熔断器为了阻止原地重试风暴而产出的快速失败,// 对页面生命周期仍是可恢复状态:Context 的代表性探测会自动关熔断,本页定时// 重探即可,不能把它固化成“目录环境错误”。- if (text.includes('DEVICE_UNRESPONSIVE')) return { status: 'recovering' };+ if (remoteErrorText(error).includes('DEVICE_UNRESPONSIVE')) return { status: 'recovering' };if (isTransientRemoteError(error)) return { status: 'recovering' };return { status: 'detect-failed' };}@@ -173,32 +170,60 @@ export function seedWorktreeEnabled(/*** 手机只是远程控制器:checkbox 偏好先由工作端接受,再更新手机内存镜像。- * apply 失败时 mirror 绝不执行,避免留下一份仅手机生效的假偏好。+ * apply 失败时通常不执行 mirror;唯一例外是老端明确没有偏好 channel,且用户+ * 显式关闭一份阻塞创建的旧 ON 镜像。瞬时错误绝不触发兼容退出。*/export async function applyWorktreePreferenceOnHost(input: {enabled: boolean;apply: (enabled: boolean) => Promise<void>;mirror: (enabled: boolean) => void;+ /**+ * 老工作端连偏好 channel 都没有时,允许用户显式关闭手机保留的旧 ON 镜像。+ * 仅 CHANNEL_NOT_ALLOWED + OFF 生效;瞬时失败仍保留 ON 并继续 fail closed。+ */+ allowUnsupportedDisableFallback?: boolean;}): Promise<void> {- await input.apply(input.enabled);+ try {+ await input.apply(input.enabled);+ } catch (error) {+ if (+ input.enabled+ || input.allowUnsupportedDisableFallback !== true+ || !isChannelNotAllowedError(error)+ ) throw error;+ }input.mirror(input.enabled);}-/** 开关行是否显示:project 模式 + 已选 workingDir,且通道未被判定为不可用。 */+function remoteErrorText(error: unknown): string {+ const code = (error as { code?: unknown } | null | undefined)?.code;+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : String(error);+ return `${typeof code === 'string' ? code : ''} ${message}`;+}++function isChannelNotAllowedError(error: unknown): boolean {+ return remoteErrorText(error).includes('CHANNEL_NOT_ALLOWED');+}++/**+ * 开关行是否显示:正常情况下是 project + workingDir + 通道可用;若老端不支持但+ * 镜像仍为 ON,保留已勾选的关闭入口,不能把用户锁在 fail-closed 状态。+ */export function shouldShowWorktreeToggle(input: {workspaceKind: 'project' | 'dialogue';workingDir: string;eligibility: NewSessionWorktreeEligibility;+ enabled: boolean;}): boolean {return input.workspaceKind === 'project'&& input.workingDir.trim().length > 0- && input.eligibility.status !== 'unsupported';+ && (input.eligibility.status !== 'unsupported' || input.enabled);}/*** checkbox 正在写工作端时不能按旧镜像创建;已勾选且当前目标尚未确认 eligible 时,- * 也不能静默退化为普通目录会话。unsupported 只隐藏老工作端无法操作的控件;- * 若当前镜像仍为已勾选,也必须 fail closed,不能绕过 worktree:create 落到 base repo。+ * 也不能静默退化为普通目录会话。unsupported + ON 仍 fail closed,但保留显式关闭+ * 入口,不能绕过 worktree:create 落到 base repo,也不能把用户永久锁住。*/export function shouldBlockNewSessionCreateForWorktree(input: {/** 当前草稿是否真的会使用 worktree:仅 project + 已选目录。 */@@ -215,7 +240,7 @@ export function shouldBlockNewSessionCreateForWorktree(input: {&& input.eligibility.status !== 'eligible';}-/** 资格未通过时的 caption 文案 key(session.json);eligible/unsupported 无 caption。 */+/** 资格未通过时的 caption 文案 key(session.json);eligible 无 caption。 */export function worktreeEligibilityCaptionKey(eligibility: NewSessionWorktreeEligibility,): string | null {@@ -236,6 +261,8 @@ export function worktreeEligibilityCaptionKey(return null;case 'detect-failed':return 'session.new.worktreeDetectFailed';+ case 'unsupported':+ return 'session.new.worktreeUnsupported';default:return null;}