Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(worktree): 支持手动对齐远程分支与选择远程主分支
fmfsaisaic07afaf078b5
diff --git a/apps/desktop/scripts/fixtures/branch-sync/branch-sync-fixture.tsx b/apps/desktop/scripts/fixtures/branch-sync/branch-sync-fixture.tsxnew file mode 100644index 0000000000..65157cf2bd--- /dev/null+++ b/apps/desktop/scripts/fixtures/branch-sync/branch-sync-fixture.tsx@@ -0,0 +1,59 @@+import { useState } from 'react';+import { BranchWorktreeChip } from '../../../src/renderer/components/new-chat/WorktreeChipsRow';+import { mountPage, type UiPageContext } from '../../ui-page/harness';+import type { BranchSyncRequest, BranchSyncStatus } from '../../../src/shared/worktreeBranchSync';+const branches = ['main', 'feature/search', 'origin/main'];+function Fixture({ ctx }: { ctx: UiPageContext }) {+ const [branch, setBranch] = useState('main');+ const [checked, setChecked] = useState(ctx.case !== 'unchecked');+ return (+ <main className="p-6 pt-16">+ <BranchWorktreeChip+ baseRepo="/projects/cindy"+ branchLabel={branch}+ deviceId={ctx.case === 'old-host' ? 'old-pc' : undefined}+ remoteDefaultBranch={ctx.case === 'old-host' ? undefined : 'refs/remotes/origin/main'}+ branches={branches}+ branchesLoading={false}+ branchesFailed={false}+ onRetryBranches={() => {}}+ checked={checked}+ branchSourceSelected+ branchInteractive+ onPick={setBranch}+ onOpenRequested={() => {}}+ onToggle={setChecked}+ compact={ctx.case === 'worker'}+ branchOnly={ctx.case === 'worker'}+ />+ </main>+ );+}+mountPage({+ host: (ctx) => {+ const read = (req: BranchSyncRequest): BranchSyncStatus => ({+ branch: req.branch,+ remote: 'origin',+ remoteBranch: 'main',+ remoteOnly: req.branch.startsWith('refs/'),+ ahead: ctx.case === 'diverged' ? 2 : 0,+ behind: 3,+ dirtyFiles: 3,+ checkoutPath: '/projects/cindy',+ ...(ctx.case === 'diverged' || ctx.case === 'conflict' ? { blocked: ctx.case } : {}),+ });+ return {+ deviceLink: {+ invoke: async () => {+ throw new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] Old host');+ },+ },+ worktreeBranchSyncStatus: async (req: BranchSyncRequest) => read(req),+ worktreeSyncBranch: async (req: BranchSyncRequest) => ({+ status: { ...read(req), behind: 0 },+ updated: 3,+ }),+ };+ },+ render: (ctx) => <Fixture ctx={ctx} />,+});diff --git a/apps/desktop/scripts/fixtures/branch-sync/ui-page.mjs b/apps/desktop/scripts/fixtures/branch-sync/ui-page.mjsnew file mode 100644index 0000000000..29bfe52980--- /dev/null+++ b/apps/desktop/scripts/fixtures/branch-sync/ui-page.mjs@@ -0,0 +1,70 @@+import assert from 'node:assert/strict';+export default {+ name: 'branch-sync',+ entry: './branch-sync-fixture.tsx',+ viewport: { width: 560, height: 400 },+ real: 'BranchWorktreeChip, sync hook, grouped combobox, tooltip, themes and locale strings',+ notCovered:+ 'Git processes, device-link transport and native task creation; covered by unit and Git integration tests',+ cases: {+ default: {+ about: 'Main-task capsule, selected-branch details, remote group and successful fetch',+ },+ worker: { about: 'Compact Worker branch-only capsule', viewport: { width: 360, height: 400 } },+ unchecked: { about: 'Unchecked main-task worktree excludes remote sources' },+ conflict: { about: 'Disabled sync remains focusable and explains overlapping changes' },+ diverged: { about: 'Diverged branches keep local source and explain why sync is unavailable' },+ 'old-host': { about: 'Old controlled host has neither refresh button nor remote group' },+ },+ async check(page, ui) {+ const trigger = page.getByRole('button', {+ name: await ui.t('newChat.branchChip.label'),+ exact: true,+ });+ await trigger.waitFor();+ await ui.capture('capsule');+ if (ui.case === 'conflict' || ui.case === 'diverged') {+ const action = page.getByRole('button', {+ name: await ui.t(`newChat.branchSync.${ui.case}`, {+ branch: 'main',+ remote: 'origin',+ remoteBranch: 'main',+ }),+ exact: true,+ });+ assert.equal(await action.isDisabled(), true);+ await action.locator('..').hover();+ await page.getByRole('tooltip').waitFor();+ await ui.capture('disabled-reason');+ }+ await trigger.click();+ await page.getByRole('combobox').waitFor();+ const remote = page.getByRole('group', {+ name: await ui.t('newChat.branchSync.remoteGroup'),+ exact: true,+ });+ assert.equal(await remote.count(), ['unchecked', 'old-host'].includes(ui.case) ? 0 : 1);+ await ui.capture('branches');+ if (ui.case === 'default' || ui.case === 'worker') {+ await page.getByRole('combobox').fill('origin/main');+ assert.equal(await page.getByRole('option').count(), 2);+ await page.keyboard.press('Enter');+ assert.match(await trigger.textContent(), /origin\/main/);+ const action = page.getByRole('button', {+ name: await ui.t('newChat.branchSync.remoteAction', {+ remote: 'origin',+ remoteBranch: 'main',+ }),+ exact: false,+ });+ await action.click();+ await page+ .getByRole('button', {+ name: await ui.t('newChat.branchSync.updated', { count: 3 }),+ exact: true,+ })+ .waitFor();+ await ui.capture('updated');+ }+ },+};diff --git a/apps/desktop/scripts/fixtures/orca-worker-project/worker-project-fixture.tsx b/apps/desktop/scripts/fixtures/orca-worker-project/worker-project-fixture.tsxindex 6d7c3a899f..bd6a7ed347 100644--- a/apps/desktop/scripts/fixtures/orca-worker-project/worker-project-fixture.tsx+++ b/apps/desktop/scripts/fixtures/orca-worker-project/worker-project-fixture.tsx@@ -191,7 +191,10 @@ void mountPage({},},},+ worktreeBranchSyncStatus: async ({ branch }: { branch: string }) => ({ branch, remote: 'origin', remoteBranch: branch, remoteOnly: false, ahead: 0, behind: 3, dirtyFiles: 2, checkoutPath: inherited.directory }),+ worktreeSyncBranch: async ({ branch }: { branch: string }) => ({ updated: 3, status: { branch, remote: 'origin', remoteBranch: branch, remoteOnly: false, ahead: 0, behind: 0, dirtyFiles: 2 } }),worktreeListBranches: async () => ({+ remoteDefaultBranch: 'refs/remotes/origin/main',branches: ['main', 'feat/worker-project-picker', 'release/v2'],}),}),diff --git a/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.tsindex 9721143eed..5aa9b29566 100644--- a/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.ts@@ -176,20 +176,20 @@ describe('device-link host dispatch (runInvoke) — real gate + async fs guard +// 远程 worktree:worktree:create 的 baseRepo 与 create-session 的 workingDir 同口径收敛// (决定在被控端哪个仓库下跑 git worktree add)。- it('worktree:create 的 baseRepo 是真实存在目录 → 放行到 handler', async () => {- const handler = registerHandler('worktree:create', () => ({ ok: true }));+ it.each(['worktree:create', 'worktree:sync-branch'])('%s 的 baseRepo 是真实存在目录 → 放行到 handler', async (channel) => {+ const handler = registerHandler(channel, () => ({ ok: true }));const res = (await runInvoke(SRC, {- channel: 'worktree:create',+ channel,args: [{ sessionId: 's-wt', baseRepo: TMP_DIR, name: 'auto-x1', sourceBranch: 'main' }],})) as Extract<InvokeResultPayload, { ok: true }>;expect(res.ok).toBe(true);expect(handler).toHaveBeenCalledTimes(1);});- it('worktree:create 的 baseRepo 不存在 → 结构化拒绝,不落到 handler', async () => {- const handler = registerHandler('worktree:create', () => ({ ok: true }));+ it.each(['worktree:create', 'worktree:sync-branch'])('%s 的 baseRepo 不存在 → 结构化拒绝,不落到 handler', async (channel) => {+ const handler = registerHandler(channel, () => ({ ok: true }));const res = (await runInvoke(SRC, {- channel: 'worktree:create',+ channel,args: [{ sessionId: 's-wt', baseRepo: '/definitely/not/a/real/repo/xyz123', name: 'auto-x1', sourceBranch: 'main' }],})) as Extract<InvokeResultPayload, { ok: false }>;expect(res.ok).toBe(false);diff --git a/apps/desktop/src/main/__tests__/worktreeReveal.test.ts b/apps/desktop/src/main/__tests__/worktreeReveal.test.tsindex bae3131cbd..3c029eea6e 100644--- a/apps/desktop/src/main/__tests__/worktreeReveal.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeReveal.test.ts@@ -14,6 +14,13 @@ import { extractIpcError } from '../../renderer/utils/ipcError';const showItemInFolderMock = vi.fn();const suggestNameMock = vi.fn();const detectCwdMock = vi.fn();+const listBranchesMock = vi.fn();+const readOriginDefaultBranchMock = vi.fn();+vi.mock('../worktree/branchSync', () => ({+ readOriginDefaultBranch: (...args: unknown[]) => readOriginDefaultBranchMock(...args),+ readBranchSyncStatus: vi.fn(),+ syncBranch: vi.fn(),+}));type Handler = (event: unknown, req: unknown) => unknown | Promise<unknown>;const handlers = new Map<string, Handler>();const ipcMainMock = {@@ -46,7 +53,7 @@ vi.mock('../worktree/WorktreeManager', () => ({getForSession: vi.fn(),listAll: vi.fn(),suggestName: (...args: unknown[]) => suggestNameMock(...args),- listBranches: vi.fn(),+ listBranches: (...args: unknown[]) => listBranchesMock(...args),}));let registerWorktreeIpc: typeof import('../worktree/index').registerWorktreeIpc;@@ -55,6 +62,8 @@ beforeEach(async () => {showItemInFolderMock.mockReset();suggestNameMock.mockReset();detectCwdMock.mockReset();+ listBranchesMock.mockReset();+ readOriginDefaultBranchMock.mockReset();getAllPathsMock.mockReset();handlers.clear();if (!registerWorktreeIpc) {@@ -163,3 +172,20 @@ describe('worktree:reveal whitelist (I-3 fix)', () => {expect(showItemInFolderMock).not.toHaveBeenCalled();});});++// F1 regression (unit): optional remote grouping must not make the existing branch+// list fail. Existing reveal/probe cases never exercise this enrichment; the+// minimal failure is an origin lookup timeout after a successful local list.+describe('worktree:list-branches optional remote group', () => {+ it.each([false, true])('preserves local branches when remote lookup fails: %s', async (fails) => {+ const baseRepo = path.resolve('/repo');+ const local = { branches: ['main'], current: 'main' };+ listBranchesMock.mockResolvedValue(local);+ if (fails) readOriginDefaultBranchMock.mockRejectedValue(new Error('Git timed out'));+ else readOriginDefaultBranchMock.mockResolvedValue('refs/remotes/origin/main');+ const result = await handlers.get('worktree:list-branches')!({}, { baseRepo });+ expect(result).toEqual({ ...local, remoteDefaultBranch: fails ? undefined : 'refs/remotes/origin/main' });+ expect(listBranchesMock).toHaveBeenCalledExactlyOnceWith(baseRepo);+ expect(readOriginDefaultBranchMock).toHaveBeenCalledExactlyOnceWith(baseRepo);+ });+});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 7baebfc7e1..c131fac60c 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -356,6 +356,7 @@ const PATH_GUARDED_CHANNELS: ReadonlyMap<string, 'workingDir' | 'baseRepo'> = ne// 协同远端 Worker 指定本机目录时同口径收敛;不指定则由本机分配任务目录。[ORCA_REMOTE_WORKER_OPEN_CHANNEL, 'workingDir'],['worktree:create', 'baseRepo'],+ ['worktree:sync-branch', 'baseRepo'],]);type RemoteWorkingDirGuardValue = boolean | RemoteWorkingDirCheckResult;diff --git a/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts b/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.tsnew file mode 100644index 0000000000..db79ce4274--- /dev/null+++ b/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts@@ -0,0 +1,216 @@+/** Test value: real branchSync entry points must fetch one ref and only fast-forward.+ * No previous suite covers this manual action. Minimal inputs: one bare remote,+ * two diverging commits / an overlapping dirty file / a branch in another checkout.+ * Tier: git-integration (real Git ref/index/worktree semantics, no network).+ */+import { execFileSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterAll, beforeAll, expect, it, vi } from 'vitest';+import { readBranchSyncStatus, readOriginDefaultBranch, syncBranch } from '../branchSync';+import * as gitModule from '../gitExec';+vi.mock('../../logger', () => ({+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),+}));+let root: string;+let remote: string;+let seed: string;+let sequence = 0;+function git(cwd: string, ...args: string[]) {+ return execFileSync(+ 'git',+ [+ '-c',+ 'user.name=Cindy Test',+ '-c',+ '[email protected]',+ '-c',+ 'commit.gpgsign=false',+ ...args,+ ],+ {+ cwd,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, GIT_CONFIG_GLOBAL: os.devNull, GIT_CONFIG_NOSYSTEM: '1' },+ },+ ).trim();+}+function commit(cwd: string, file: string, content: string) {+ fs.writeFileSync(path.join(cwd, file), content);+ git(cwd, 'add', '--', file);+ git(cwd, 'commit', '-m', file);+ return git(cwd, 'rev-parse', 'HEAD');+}+beforeAll(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-branch-sync-'));+ seed = path.join(root, 'seed');+ remote = path.join(root, 'remote.git');+ fs.mkdirSync(seed);+ git(seed, 'init', '-b', 'main');+ commit(seed, 'base', 'base');+ git(root, 'clone', '--bare', seed, remote);+ git(seed, 'remote', 'add', 'origin', remote);+});+afterAll(() => fs.rmSync(root, { recursive: true, force: true }));+function fixture() {+ const branch = `case-${++sequence}`;+ const repo = path.join(root, branch);+ git(root, 'clone', remote, repo);+ git(repo, 'checkout', '-b', branch);+ git(repo, 'push', '-u', 'origin', branch);+ git(seed, 'checkout', '-B', branch, 'main');+ return {+ repo,+ branch,+ req: { baseRepo: repo, branch },+ advance: (file = 'base') => {+ const sha = commit(seed, file, `remote-${branch}`);+ git(seed, 'push', 'origin', branch);+ return sha;+ },+ };+}+it('fetches and fast-forwards the checked-out branch while preserving unrelated dirty files', async () => {+ const f = fixture();+ const sha = f.advance();+ fs.writeFileSync(path.join(f.repo, 'keep'), 'uncommitted');+ const result = await syncBranch(f.req);+ expect(result.updated).toBe(1);+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(sha);+ expect(fs.readFileSync(path.join(f.repo, 'base'), 'utf8')).toBe(`remote-${f.branch}`);+ expect(fs.readFileSync(path.join(f.repo, 'keep'), 'utf8')).toBe('uncommitted');+ expect(result.status.dirtyFiles).toBe(1);+});+it('updates an unchecked local ref without changing the current checkout', async () => {+ const f = fixture();+ const sha = f.advance();+ git(f.repo, 'checkout', 'main');+ const before = git(f.repo, 'rev-parse', 'HEAD');+ expect((await syncBranch(f.req)).updated).toBe(1);+ expect(git(f.repo, 'rev-parse', f.branch)).toBe(sha);+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(before);+});+it('fast-forwards the directory where the selected branch is checked out, including linked worktrees', async () => {+ const f = fixture();+ git(f.repo, 'checkout', 'main');+ const checkout = path.join(root, 'linked');+ git(f.repo, 'worktree', 'add', checkout, f.branch);+ const sha = f.advance();+ const result = await syncBranch(f.req);+ expect(result.status.checkoutPath).toBe(fs.realpathSync(checkout).replaceAll('\\', '/'));+ expect(git(checkout, 'rev-parse', 'HEAD')).toBe(sha);+ expect(fs.readFileSync(path.join(checkout, 'base'), 'utf8')).toBe(`remote-${f.branch}`);+});+it('leaves divergent branches unchanged', async () => {+ const f = fixture();+ const local = commit(f.repo, 'local', 'local');+ f.advance();+ const result = await syncBranch(f.req);+ expect(result.status).toMatchObject({ blocked: 'diverged', ahead: 1, behind: 1 });+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(local);+});+it.each(['tracked', 'untracked'])(+ 'blocks overlapping %s changes and keeps their bytes',+ async (kind) => {+ const f = fixture();+ const file = kind === 'tracked' ? 'base' : 'new-file';+ f.advance(file);+ fs.writeFileSync(path.join(f.repo, file), 'user changes');+ const before = git(f.repo, 'rev-parse', 'HEAD');+ expect((await syncBranch(f.req)).status.blocked).toBe('conflict');+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(before);+ expect(fs.readFileSync(path.join(f.repo, file), 'utf8')).toBe('user changes');+ },+);+it('retains unpushed local commits and reports already-current on the next fetch', async () => {+ const f = fixture();+ const local = commit(f.repo, 'local', 'local');+ expect(await syncBranch(f.req)).toMatchObject({ updated: 0, status: { ahead: 1, behind: 0 } });+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(local);+ git(f.repo, 'push');+ expect(await syncBranch(f.req)).toMatchObject({ updated: 0, status: { ahead: 0, behind: 0 } });+});+it('fetches a remote-only source without touching a same-named local branch', async () => {+ const f = fixture();+ const before = git(f.repo, 'rev-parse', 'HEAD');+ git(f.repo, 'branch', `origin/${f.branch}`);+ const sha = f.advance();+ const result = await syncBranch({ baseRepo: f.repo, branch: `refs/remotes/origin/${f.branch}` });+ expect(result.updated).toBe(1);+ expect(git(f.repo, 'rev-parse', `refs/remotes/origin/${f.branch}`)).toBe(sha);+ expect(git(f.repo, 'rev-parse', `refs/heads/origin/${f.branch}`)).toBe(before);+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(before);+});+it('honors a configured tracking remote and branch rather than origin/same-name', async () => {+ const f = fixture();+ const sha = f.advance();+ git(f.repo, 'remote', 'rename', 'origin', 'upstream');+ git(f.repo, 'branch', '-m', 'renamed');+ const result = await syncBranch({ baseRepo: f.repo, branch: 'renamed' });+ expect(result.status).toMatchObject({ remote: 'upstream', remoteBranch: f.branch });+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(sha);+});+it('falls back to origin/same-name without upstream configuration; disables missing refs and remotes', async () => {+ const f = fixture();+ git(f.repo, 'branch', '--unset-upstream');+ expect(await readBranchSyncStatus(f.req)).toMatchObject({+ remote: 'origin',+ remoteBranch: f.branch,+ });+ git(f.repo, 'update-ref', '-d', `refs/remotes/origin/${f.branch}`);+ expect((await readBranchSyncStatus(f.req)).blocked).toBeUndefined();+ expect((await syncBranch(f.req)).status.blocked).toBeUndefined();+ git(f.repo, 'push', 'origin', '--delete', f.branch);+ expect((await syncBranch(f.req)).status.blocked).toBe('missing-remote');+ git(f.repo, 'remote', 'remove', 'origin');+ fs.writeFileSync(path.join(f.repo, 'dirty-without-remote'), 'user changes');+ expect((await syncBranch(f.req)).status).toMatchObject({ blocked: 'no-remote', dirtyFiles: 1 });+});+it('uses a valid origin/HEAD, otherwise main then master, and never upstream', async () => {+ const f = fixture();+ git(f.repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', `refs/remotes/origin/${f.branch}`);+ expect(await readOriginDefaultBranch(f.repo)).toBe(`refs/remotes/origin/${f.branch}`);+ git(f.repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/missing');+ expect(await readOriginDefaultBranch(f.repo)).toBe('refs/remotes/origin/main');+ git(f.repo, 'symbolic-ref', '--delete', 'refs/remotes/origin/HEAD');+ expect(await readOriginDefaultBranch(f.repo)).toBe('refs/remotes/origin/main');+ git(f.repo, 'update-ref', 'refs/remotes/origin/master', 'HEAD');+ git(f.repo, 'update-ref', '-d', 'refs/remotes/origin/main');+ expect(await readOriginDefaultBranch(f.repo)).toBe('refs/remotes/origin/master');+ git(f.repo, 'update-ref', '-d', 'refs/remotes/origin/master');+ git(f.repo, 'update-ref', 'refs/remotes/upstream/main', 'HEAD');+ expect(await readOriginDefaultBranch(f.repo)).toBeUndefined();+});++it('keeps HEAD, staged content and dirty bytes when Git discovers an overlap after the preflight', async () => {+ const f = fixture();+ f.advance();+ const before = git(f.repo, 'rev-parse', 'HEAD');+ fs.writeFileSync(path.join(f.repo, 'staged'), 'staged change');+ git(f.repo, 'add', 'staged');+ git(f.repo, 'config', 'merge.autostash', 'true');+ const index = git(f.repo, 'ls-files', '--stage');+ const realGit = gitModule.gitExec;+ const spy = vi.spyOn(gitModule, 'gitExec').mockImplementation(async (args, cwd, opts) => {+ if (args[0] === 'merge') fs.writeFileSync(path.join(f.repo, 'base'), 'arrived during fetch');+ return realGit(args, cwd, opts);+ });+ try {+ expect((await syncBranch(f.req)).status.blocked).toBe('conflict');+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(before);+ expect(git(f.repo, 'ls-files', '--stage')).toBe(index);+ expect(fs.readFileSync(path.join(f.repo, 'base'), 'utf8')).toBe('arrived during fetch');+ expect(fs.readFileSync(path.join(f.repo, 'staged'), 'utf8')).toBe('staged change');+ expect(git(f.repo, 'stash', 'list')).toBe('');+ } finally {+ spy.mockRestore();+ }+});+it('disables a branch with no upstream when only a non-origin remote is configured', async () => {+ const f = fixture();+ git(f.repo, 'branch', '--unset-upstream');+ git(f.repo, 'remote', 'rename', 'origin', 'upstream');+ expect((await readBranchSyncStatus(f.req)).blocked).toBe('no-remote');+});diff --git a/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts b/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.tsnew file mode 100644index 0000000000..db878986e7--- /dev/null+++ b/apps/desktop/src/main/worktree/__tests__/branchSyncHandlers.test.ts@@ -0,0 +1,59 @@+/** Test value: new privileged IPC endpoints must reject untrusted frames and invalid+ * payloads before invoking Git, and never leak credential-bearing Git stderr.+ * No existing handler covers this capability. Minimal inputs: untrusted event,+ * option-shaped ref, credential URL in failure. Tier: unit, injected identity.+ */+import path from 'node:path';+import { beforeEach, expect, it, vi } from 'vitest';+import { createBranchSyncHandlers } from '../branchSyncHandlers';+import { GitExecError } from '../gitExec';+const calls = vi.hoisted(() => ({ status: vi.fn(), sync: vi.fn() }));+vi.mock('../branchSync', () => ({ readBranchSyncStatus: calls.status, syncBranch: calls.sync }));+const assertSender = vi.fn();+const remote = vi.fn();+const handlers = createBranchSyncHandlers({+ assertTrustedAppRendererEvent: assertSender,+ isDeviceLinkInvoke: remote,+});+const req = { baseRepo: path.resolve('/repo'), branch: 'main' };+beforeEach(() => {+ vi.resetAllMocks();+ remote.mockReturnValue(false);+});+it('rejects an untrusted frame before reading or mutating any repository', () => {+ assertSender.mockImplementation(() => {+ throw new Error('[PERMISSION_DENIED] Untrusted frame');+ });+ for (const handler of [handlers.status, handlers.sync])+ expect(() => handler({}, req)).toThrow('PERMISSION_DENIED');+ expect(calls.status).not.toHaveBeenCalled();+ expect(calls.sync).not.toHaveBeenCalled();+});+it.each([+ { baseRepo: 'relative', branch: 'main' },+ { ...req, branch: '--help' },+ { ...req, branch: 'main:other' },+ null,+])('rejects malformed payloads without side effects: %j', (body) => {+ expect(() => handlers.sync({}, body)).toThrow('INVALID_PARAMS');+ expect(calls.sync).not.toHaveBeenCalled();+});+it('accepts the authenticated device-link context without treating its synthetic event as a local frame', async () => {+ remote.mockReturnValue(true);+ calls.sync.mockResolvedValue({ updated: 2 });+ expect(await handlers.sync({}, req)).toEqual({ updated: 2 });+ expect(assertSender).not.toHaveBeenCalled();+ expect(calls.sync).toHaveBeenCalledWith(req);+});+it('returns a readable reason without leaking Git credentials or output', async () => {+ calls.sync.mockRejectedValue(+ new GitExecError({+ args: ['fetch'],+ exitCode: 128,+ stdout: '',+ stderr: 'Authentication failed for https://name:[email protected]/repo',+ }),+ );+ await expect(handlers.sync({}, req)).rejects.toThrow('branch-sync:auth');+ await expect(handlers.sync({}, req)).rejects.not.toThrow('secret');+});diff --git a/apps/desktop/src/main/worktree/branchSync.ts b/apps/desktop/src/main/worktree/branchSync.tsnew file mode 100644index 0000000000..50cbc57689--- /dev/null+++ b/apps/desktop/src/main/worktree/branchSync.ts@@ -0,0 +1,222 @@+import path from 'node:path';+import { gitExec, GitExecError } from './gitExec';+import { boundedNetworkGitOpts } from './freshBase';+import type {+ BranchSyncRequest,+ BranchSyncResult,+ BranchSyncStatus,+} from '../../shared/worktreeBranchSync';++const localOpts = { timeoutMs: 5_000, extraEnv: { LC_ALL: 'C' } };+async function git(cwd: string, ...args: string[]): Promise<string> {+ return (await gitExec(args, cwd, localOpts)).stdout.trim();+}+async function optional(cwd: string, ...args: string[]): Promise<string | undefined> {+ try {+ return await git(cwd, ...args);+ } catch (error) {+ if (error instanceof GitExecError && !error.timedOut && error.exitCode !== null)+ return undefined;+ throw error;+ }+}++/** Local refs only: a dangling origin/HEAD must not hide the main/master fallback. */+export async function readOriginDefaultBranch(cwd: string): Promise<string | undefined> {+ const symbolic = await optional(cwd, 'symbolic-ref', 'refs/remotes/origin/HEAD');+ for (const ref of [symbolic, 'refs/remotes/origin/main', 'refs/remotes/origin/master']) {+ if (+ ref?.startsWith('refs/remotes/origin/') &&+ (await optional(cwd, 'rev-parse', '--verify', `${ref}^{commit}`))+ )+ return ref;+ }+ return undefined;+}++function dirtyPaths(porcelain: string): { paths: string[]; files: number } {+ const fields = porcelain.split('\0');+ const paths: string[] = [];+ let files = 0;+ for (let i = 0; i < fields.length; i++) {+ const row = fields[i];+ if (!row) continue;+ files++;+ paths.push(row.slice(3));+ if (/[RC]/.test(row.slice(0, 2)) && fields[i + 1]) paths.push(fields[++i]);+ }+ return { paths, files };+}+function overlaps(a: string, b: string): boolean {+ return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);+}++/** Validate refs even for direct main callers; never pass an option-shaped ref to Git. */+async function validate(req: BranchSyncRequest): Promise<void> {+ if (+ !req ||+ typeof req.baseRepo !== 'string' ||+ !path.isAbsolute(req.baseRepo) ||+ typeof req.branch !== 'string' ||+ req.branch.length > 1024 ||+ req.branch.startsWith('-')+ ) {+ throw new Error('Invalid branch sync request');+ }+ await git(+ req.baseRepo,+ 'check-ref-format',+ req.branch.startsWith('refs/remotes/origin/') ? req.branch : `refs/heads/${req.branch}`,+ );+}++export async function readBranchSyncStatus(req: BranchSyncRequest): Promise<BranchSyncStatus> {+ await validate(req);+ const { baseRepo, branch } = req;+ const remoteOnly = branch.startsWith('refs/remotes/origin/');+ const status: BranchSyncStatus = { branch, remoteOnly, ahead: 0, behind: 0, dirtyFiles: 0 };+ const remotes = (await git(baseRepo, 'remote')).split(/\r?\n/).filter(Boolean);+ let remote = 'origin';+ let remoteBranch = remoteOnly ? branch.slice('refs/remotes/origin/'.length) : branch;+ const localRef = `refs/heads/${branch}`;+ if (!remoteOnly) {+ if (!(await optional(baseRepo, 'rev-parse', '--verify', `${localRef}^{commit}`)))+ return { ...status, blocked: 'not-local' };+ const configuredRemote = await optional(baseRepo, 'config', '--get', `branch.${branch}.remote`);+ const configuredRef = await optional(baseRepo, 'config', '--get', `branch.${branch}.merge`);+ if (configuredRemote && configuredRef?.startsWith('refs/heads/')) {+ remote = configuredRemote;+ remoteBranch = configuredRef.slice('refs/heads/'.length);+ }+ // -z preserves checkout paths containing newlines and non-ASCII characters.+ const worktrees = (+ await gitExec(['worktree', 'list', '--porcelain', '-z'], baseRepo, localOpts)+ ).stdout;+ for (const block of worktrees.split('\0\0')) {+ const fields = block.split('\0');+ if (fields.includes(`branch ${localRef}`)) {+ status.checkoutPath = fields.find((s) => s.startsWith('worktree '))?.slice(9);+ break;+ }+ }+ }+ const dirty = status.checkoutPath+ ? dirtyPaths(+ (+ await gitExec(+ ['status', '--porcelain', '-z', '--untracked-files=all'],+ status.checkoutPath,+ localOpts,+ )+ ).stdout,+ )+ : { paths: [], files: 0 };+ status.dirtyFiles = dirty.files;+ if (!remotes.includes(remote)) return { ...status, blocked: 'no-remote' };+ Object.assign(status, {+ remote,+ remoteBranch,+ remoteRef: `refs/remotes/${remote}/${remoteBranch}`,+ });+ // A missing local tracking ref is unknown, not evidence the remote branch is absent.+ if (!(await optional(baseRepo, 'rev-parse', '--verify', `${status.remoteRef}^{commit}`)))+ return status;+ if (remoteOnly) return status;+ const counts = (+ await git(baseRepo, 'rev-list', '--left-right', '--count', `${localRef}...${status.remoteRef}`)+ )+ .split(/\s+/)+ .map(Number);+ [status.ahead, status.behind] = counts;+ if (status.ahead && status.behind) return { ...status, blocked: 'diverged' };+ if (status.behind && dirty.paths.length) {+ const changes = (+ await gitExec(['diff', '--name-only', '-z', localRef, status.remoteRef!], baseRepo, localOpts)+ ).stdout+ .split('\0')+ .filter(Boolean);+ if (dirty.paths.some((p) => changes.some((other) => overlaps(p, other))))+ return { ...status, blocked: 'conflict' };+ }+ return status;+}++// Serialize this UI's mutations per repository; no coupling to task creation or sends.+const syncing = new Map<string, Promise<BranchSyncResult>>();+export async function syncBranch(req: BranchSyncRequest): Promise<BranchSyncResult> {+ await validate(req);+ const key = await git(req.baseRepo, 'rev-parse', '--path-format=absolute', '--git-common-dir');+ if (syncing.has(key)) throw new Error('A branch update is already running');+ const operation = syncBranchOnce(req);+ syncing.set(key, operation);+ try {+ return await operation;+ } finally {+ syncing.delete(key);+ }+}+async function syncBranchOnce(req: BranchSyncRequest): Promise<BranchSyncResult> {+ let status = await readBranchSyncStatus(req);+ if (status.blocked) return { status, updated: 0 };+ const { remote, remoteBranch, remoteRef } = status;+ const oldRemote = await optional(req.baseRepo, 'rev-parse', '--verify', `${remoteRef}^{commit}`);+ try {+ await gitExec(+ [+ 'fetch',+ '--no-tags',+ '--recurse-submodules=no',+ '--',+ remote!,+ `+refs/heads/${remoteBranch}:${remoteRef}`,+ ],+ req.baseRepo,+ {+ ...boundedNetworkGitOpts(30_000),+ extraEnv: { ...boundedNetworkGitOpts(30_000).extraEnv, LC_ALL: 'C' },+ },+ );+ } catch (error) {+ if (+ error instanceof GitExecError &&+ /couldn't find remote ref|could not find remote ref/i.test(error.stderr)+ ) {+ return { status: { ...status, blocked: 'missing-remote' }, updated: 0 };+ }+ throw error;+ }+ status = await readBranchSyncStatus(req);+ if (status.blocked) return { status, updated: 0 };+ if (status.remoteOnly) {+ const updated = Number(+ await git(+ req.baseRepo,+ 'rev-list',+ '--count',+ oldRemote ? `${oldRemote}..${remoteRef}` : remoteRef!,+ ),+ );+ return { status, updated };+ }+ if (!status.behind) return { status, updated: 0 };+ const old = await git(req.baseRepo, 'rev-parse', '--verify', `refs/heads/${req.branch}^{commit}`);+ const next = await git(req.baseRepo, 'rev-parse', '--verify', `${remoteRef}^{commit}`);+ await git(req.baseRepo, 'merge-base', '--is-ancestor', old, next);+ const updated = status.behind;+ if (status.checkoutPath) {+ if ((await git(status.checkoutPath, 'symbolic-ref', 'HEAD')) !== `refs/heads/${req.branch}`)+ throw new Error('The checked-out branch changed; retry');+ try {+ await git(status.checkoutPath, 'merge', '--ff-only', '--no-autostash', next);+ } catch (error) {+ const refreshed = await readBranchSyncStatus(req);+ if (refreshed.blocked) return { status: refreshed, updated: 0 };+ if (error instanceof GitExecError && /would be overwritten|local changes/i.test(error.stderr))+ return { status: { ...refreshed, blocked: 'conflict' }, updated: 0 };+ throw error;+ }+ } else {+ await git(req.baseRepo, 'update-ref', `refs/heads/${req.branch}`, next, old);+ }+ return { status: await readBranchSyncStatus(req), updated };+}diff --git a/apps/desktop/src/main/worktree/branchSyncHandlers.ts b/apps/desktop/src/main/worktree/branchSyncHandlers.tsnew file mode 100644index 0000000000..517dea179a--- /dev/null+++ b/apps/desktop/src/main/worktree/branchSyncHandlers.ts@@ -0,0 +1,67 @@+import path from 'node:path';+import { readBranchSyncStatus, syncBranch } from './branchSync';+import { GitExecError } from './gitExec';+import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate';+import {+ BRANCH_SYNC_ERROR_PREFIX,+ type BranchSyncRequest,+ type BranchSyncFailureReason,+} from '../../shared/worktreeBranchSync';++/** Small IPC boundary, testable without loading Electron or the WorktreeManager. */+export function createBranchSyncHandlers<Event>(deps: {+ assertTrustedAppRendererEvent(event: Event): void;+ isDeviceLinkInvoke(): boolean;+}) {+ function request(event: Event, input: unknown): BranchSyncRequest {+ // Remote invokes already passed the same-account device-link allowlist.+ if (!deps.isDeviceLinkInvoke()) deps.assertTrustedAppRendererEvent(event);+ const body = requireObject(input);+ const baseRepo = requireString(body.baseRepo, 'baseRepo');+ const branch = requireString(body.branch, 'branch');+ if (+ !path.isAbsolute(baseRepo) ||+ baseRepo.length > 32768 ||+ baseRepo.includes('\0') ||+ branch.length > 1024 ||+ /[\x00-\x20~^:?*\\\[]/.test(branch) ||+ branch.startsWith('-') ||+ branch.includes('..')+ ) {+ throwIpcError('INVALID_PARAMS', 'Invalid repository or branch');+ }+ return { baseRepo, branch };+ }+ async function run<T>(operation: () => Promise<T>): Promise<T> {+ try {+ return await operation();+ } catch (error) {+ // Do not return raw Git output: remote URLs may contain credentials.+ let reason: BranchSyncFailureReason = 'git';+ if (error instanceof GitExecError) {+ if (error.timedOut) reason = 'timeout';+ else if (/auth|credential|permission denied|could not read Username/i.test(error.stderr))+ reason = 'auth';+ else if (/could not resolve|unable to access|connect|network/i.test(error.stderr))+ reason = 'network';+ else if (/couldn.t find remote ref/i.test(error.stderr)) reason = 'missing';+ else if (/lock|expected/i.test(error.stderr)) reason = 'busy';+ }+ if (error instanceof Error && error.message === 'A branch update is already running')+ reason = 'busy';+ if (error instanceof Error && error.message === 'The checked-out branch changed; retry')+ reason = 'changed';+ throwIpcError('INTERNAL', BRANCH_SYNC_ERROR_PREFIX + reason);+ }+ }+ return {+ status: (event: Event, input: unknown) => {+ const req = request(event, input);+ return run(() => readBranchSyncStatus(req));+ },+ sync: (event: Event, input: unknown) => {+ const req = request(event, input);+ return run(() => syncBranch(req));+ },+ };+}diff --git a/apps/desktop/src/main/worktree/index.ts b/apps/desktop/src/main/worktree/index.tsindex 73ea840a37..a8b3e0c8ed 100644--- a/apps/desktop/src/main/worktree/index.ts+++ b/apps/desktop/src/main/worktree/index.ts@@ -7,6 +7,10 @@*/import path from 'node:path';+import { readOriginDefaultBranch } from './branchSync';+import { createBranchSyncHandlers } from './branchSyncHandlers';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';+import { isDeviceLinkInvoke } from '../device-link/invoke-context';import { ipcMain as ipcMainType, type IpcMain, shell } from 'electron';import * as WorktreeManager from './WorktreeManager';@@ -49,6 +53,10 @@ export * from './types';* 调用方保证只调一次。*/export function registerWorktreeIpc(ipcMain: IpcMain = ipcMainType): void {+ const branchSync = createBranchSyncHandlers({ assertTrustedAppRendererEvent, isDeviceLinkInvoke });+ ipcMain.handle('worktree:branch-sync-status', branchSync.status);+ ipcMain.handle('worktree:sync-branch', branchSync.sync);+ipcMain.handle('worktree:create', (_e, req: CreateWorktreeReq) =>WorktreeManager.createWorktree(req),);@@ -110,9 +118,12 @@ export function registerWorktreeIpc(ipcMain: IpcMain = ipcMainType): void {name: await WorktreeManager.suggestName(req.baseRepo),}));- ipcMain.handle('worktree:list-branches', (_e, req: ListBranchesReq) =>- WorktreeManager.listBranches(req.baseRepo),- );+ ipcMain.handle('worktree:list-branches', async (_e, req: ListBranchesReq) => {+ const branches = await WorktreeManager.listBranches(req.baseRepo);+ // Optional UI enrichment must never affect creation or the local branch list.+ const remoteDefaultBranch = await readOriginDefaultBranch(req.baseRepo).catch(() => undefined);+ return { ...branches, remoteDefaultBranch };+ });// ── P1: 删除确认预检 + 回收后恢复 ──────────────────────────────────────────// removal-preview 是只读查询,允许 device-link 控制端在被控端执行;restore 仍是diff --git a/apps/desktop/src/main/worktree/types.ts b/apps/desktop/src/main/worktree/types.tsindex d9bcd0d789..a1b73df0e7 100644--- a/apps/desktop/src/main/worktree/types.ts+++ b/apps/desktop/src/main/worktree/types.ts@@ -99,6 +99,8 @@ export interface ListBranchesReq {}export interface ListBranchesResp {+ /** Full ref, never a local branch named origin/main. */+ remoteDefaultBranch?: string;branches: string[];current: string;}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex ace0a54e98..c6f7212af2 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5250,6 +5250,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('worktree:reveal', req),worktreeSuggestName: (req: { baseRepo: string }): Promise<unknown> =>ipcRenderer.invoke('worktree:suggest-name', req),+ worktreeBranchSyncStatus: (req: import('../shared/worktreeBranchSync').BranchSyncRequest): Promise<import('../shared/worktreeBranchSync').BranchSyncStatus> => ipcRenderer.invoke('worktree:branch-sync-status', req),+ worktreeSyncBranch: (req: import('../shared/worktreeBranchSync').BranchSyncRequest): Promise<import('../shared/worktreeBranchSync').BranchSyncResult> => ipcRenderer.invoke('worktree:sync-branch', req),worktreeListBranches: (req: { baseRepo: string }): Promise<unknown> =>ipcRenderer.invoke('worktree:list-branches', req),// P1: 删除/归档确认预检(有无 worktree、是否有未提交更改)diff --git a/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx b/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsxindex 5be10ddf4f..3bc4fc3f22 100644--- a/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx+++ b/apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx@@ -36,7 +36,15 @@ import {useId,type KeyboardEvent,} from 'react';-import { GitBranch, ChevronDown, Folder, MessageCircle, Search } from 'lucide-react';+import {+ GitBranch,+ ChevronDown,+ Folder,+ MessageCircle,+ Search,+ RefreshCw,+ Check,+} from 'lucide-react';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';@@ -48,6 +56,7 @@ import {type FolderPickerOption,type FolderPickerSelectSource,} from './FolderPickerPopover';+import { useBranchSync } from '@/hooks/useBranchSync';import { resolveBranchPick } from './branchPick';import { useBranches, useDetectCwd, useSuggestName } from '@/hooks/useWorktreeQueries';import { getProjectPickerDisplayName } from '@/hooks/useProjectPickerOptions';@@ -248,9 +257,7 @@ export function WorktreeChipsRow({// 确认不合格(2026-08-07 裁决)→ 整条控件隐藏,勾选记忆保留、发送侧放行普通会话;// 探测中/失败(confirmedIneligible === null)时已 ON 仍显示,由上层 fail closed。const showBranchChip =- !advancedHidden- && confirmedIneligible !== true- && (enabled || !!detect.data?.isGitRepo);+ !advancedHidden && confirmedIneligible !== true && (enabled || !!detect.data?.isGitRepo);// 分支选择与 checkbox 是两条独立轴;仅环境不具备 worktree 资格或创建在途时禁用。const branchInteractive =!(disabled || branchDisabled || environmentDisabled) && baseRepo !== null;@@ -268,6 +275,9 @@ export function WorktreeChipsRow({const branchWorktree = showBranchChip ? (<BranchWorktreeChip+ baseRepo={baseRepo ?? undefined}+ deviceId={deviceLinkDeviceId}+ remoteDefaultBranch={branches.remoteDefaultBranch}branchLabel={branchLabel}branches={branches.branches}branchesLoading={branches.loading}@@ -417,8 +427,11 @@ function FolderChipBig({// ── [分支 │ ☑ worktree] 联合控件(对齐 Claude Code,2026-07-29 用户裁决) ──────export function BranchWorktreeChip({+ baseRepo,+ deviceId,+ remoteDefaultBranch,branchLabel,- branchDisplayLabel = branchLabel,+ branchDisplayLabel = branchLabel.replace(/^refs\/remotes\//, ''),branchOnly = false,branches,branchesLoading,@@ -434,6 +447,9 @@ export function BranchWorktreeChip({onToggle,compact,}: {+ baseRepo?: string;+ deviceId?: string | null;+ remoteDefaultBranch?: string;branchLabel: string;/** Display text only; branchLabel remains the selection value. */branchDisplayLabel?: string;@@ -460,14 +476,25 @@ export function BranchWorktreeChip({}) {const { t } = useTranslation();+ const sync = useBranchSync(baseRepo, branchLabel, deviceId);+ const allBranches = useMemo(+ () =>+ (checked || branchOnly) && remoteDefaultBranch+ ? [remoteDefaultBranch, ...branches]+ : branches,+ [checked, branchOnly, remoteDefaultBranch, branches],+ );+ const displayBranch = (value: string) =>+ value === remoteDefaultBranch ? value.replace(/^refs\/remotes\//, '') : value;+// 分支菜单内搜索词(2026-08-20 用户裁决:对齐 Codex 分支选择器,菜单顶部加搜索框)。// 菜单关闭即清空——搜索只是本次挑选的临时过滤,不是需要记忆的偏好。const [branchMenuOpen, setBranchMenuOpen] = useState(false);const [branchQuery, setBranchQuery] = useState('');const normalizedBranchQuery = branchQuery.trim().toLowerCase();const visibleBranches = normalizedBranchQuery- ? branches.filter((b) => b.toLowerCase().includes(normalizedBranchQuery))- : branches;+ ? allBranches.filter((b) => displayBranch(b).toLowerCase().includes(normalizedBranchQuery))+ : allBranches;// 组合框键盘导航(2026-09-08 Codex review:改用 aria-activedescendant 组合框结构):// 焦点始终留在输入框,方向键只移动高亮项,Enter 选中高亮项——不再依赖菜单@@ -490,9 +517,9 @@ export function BranchWorktreeChip({// 输入搜索词时接管,避免打断已经在筛选/用方向键挑选的操作。useEffect(() => {if (!branchMenuOpen || normalizedBranchQuery) return;- const current = branches.indexOf(branchLabel);+ const current = allBranches.indexOf(branchLabel);setActiveBranchIndex(current >= 0 ? current : 0);- }, [branchMenuOpen, branches, branchLabel, normalizedBranchQuery]);+ }, [branchMenuOpen, allBranches, branchLabel, normalizedBranchQuery]);const pickBranch = (branch: string) => {onPick(branch);@@ -557,7 +584,9 @@ export function BranchWorktreeChip({aria-label={t('newChat.branchChip.label')}><GitBranch size={compact ? 12 : 15} className="shrink-0" />- <span className="min-w-0 truncate" title={branchDisplayLabel}>{branchDisplayLabel}</span>+ <span className="min-w-0 truncate" title={branchDisplayLabel}>+ {branchDisplayLabel}+ </span>{branchInteractive && (<ChevronDownsize={12}@@ -586,6 +615,7 @@ export function BranchWorktreeChip({setBranchMenuOpen(open);if (open) {onOpenRequested();+ void sync.refresh();// 高亮定位交给上面的 useEffect(依赖 branches,分支异步到达/刷新时// 会自动重新定位到当前源分支,不再只在“打开那一刻”算一次)。} else {@@ -609,7 +639,7 @@ export function BranchWorktreeChip({<div className="px-3 py-1.5 text-13 text-muted-foreground">{t('newChat.branchChip.loading')}</div>- ) : branchesFailed || branches.length === 0 ? (+ ) : branchesFailed || allBranches.length === 0 ? (/* 失败与空列表都给重试入口(空列表也可能是隧道/瞬时问题);点击不关闭弹层,重试期间留在原地显示 loading。 */<button@@ -669,27 +699,48 @@ export function BranchWorktreeChip({</div></div><div role="listbox" id={listboxId} aria-label={t('newChat.branchChip.label')}>- {visibleBranches.map((b, index) => (- <div- key={b}- ref={(el) => {- optionRefs.current[index] = el;- }}- id={`${listboxId}-option-${index}`}- role="option"- aria-selected={b === branchLabel}- onMouseMove={() => setActiveBranchIndex(index)}- onClick={() => pickBranch(b)}- className={cn(- 'cursor-pointer rounded-[8px] px-3 py-1.5 text-13 text-foreground',- index === clampedActiveIndex- ? 'bg-accent text-accent-foreground'- : b === branchLabel && 'bg-accent/60',- )}- >- {b}- </div>- ))}+ {['remote', 'local'].map((group) => {+ const values = visibleBranches.filter(+ (b) => (b === remoteDefaultBranch) === (group === 'remote'),+ );+ if (!values.length) return null;+ return (+ <div key={group} role="group" aria-label={t(`newChat.branchSync.${group}Group`)}>+ {(checked || branchOnly) && remoteDefaultBranch && (+ <div className="px-3 py-1 text-12 text-muted-foreground">+ {t(`newChat.branchSync.${group}Group`)}+ </div>+ )}+ {values.map((b) => {+ const index = visibleBranches.indexOf(b);+ return (+ <div+ key={b}+ ref={(el) => {+ optionRefs.current[index] = el;+ }}+ id={`${listboxId}-option-${index}`}+ role="option"+ aria-selected={b === branchLabel}+ onMouseMove={() => setActiveBranchIndex(index)}+ onClick={() => pickBranch(b)}+ className={cn(+ 'cursor-pointer rounded-[8px] px-3 py-1.5 text-13 text-foreground',+ index === clampedActiveIndex+ ? 'bg-accent text-accent-foreground'+ : b === branchLabel && 'bg-accent/60',+ )}+ >+ {displayBranch(b)}+ {b === branchLabel && sync.details && (+ <div className="text-12 text-muted-foreground">{sync.details}</div>+ )}+ </div>+ );+ })}+ </div>+ );+ })}</div>{/* 常驻播报区域,让过滤为空时的文本更新可被读屏感知;列表关联始终保留。 */}<div@@ -793,17 +844,59 @@ export function BranchWorktreeChip({)}>{branchArea}- {!branchOnly && <>- {/* 悬停激活任一半区时分隔线隐去,让 hover 填充看起来是一体的(对齐 Claude Code)。 */}- <span- aria-hidden- className={cn(- 'w-px shrink-0 self-center transition-opacity group-hover:opacity-0',- compact ? 'h-[14px] bg-[var(--create-agent-control-border)]' : 'h-[18px] bg-border',- )}- />- {checkboxArea}- </>}+ {sync.visible && (+ <Tooltip.Root>+ <Tooltip.Trigger asChild>+ <span+ className="inline-flex h-full"+ tabIndex={sync.disabled ? 0 : undefined}+ onMouseEnter={sync.onHover}+ onFocus={sync.onHover}+ >+ <button+ type="button"+ disabled={sync.disabled}+ aria-disabled={sync.disabled}+ aria-label={sync.hint}+ onClick={() => void sync.sync()}+ className={cn(+ 'inline-flex h-full w-8 shrink-0 items-center justify-center text-muted-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50',+ compact+ ? 'hover:bg-[var(--create-agent-control-bg-hover)] active:bg-[var(--create-agent-control-bg-pressed)]'+ : 'hover:bg-sidebar-item-hover',+ branchOnly && 'pr-1',+ )}+ >+ {sync.done ? (+ <Check size={14} aria-hidden />+ ) : (+ <RefreshCw+ size={14}+ aria-hidden+ className={sync.busy ? 'animate-spin' : undefined}+ />+ )}+ </button>+ </span>+ </Tooltip.Trigger>+ <Tooltip.Content side="top" className="max-w-[320px] whitespace-pre-line">+ {sync.hint}+ </Tooltip.Content>+ </Tooltip.Root>+ )}+ {!branchOnly && (+ <>+ {/* 悬停激活任一半区时分隔线隐去,让 hover 填充看起来是一体的(对齐 Claude Code)。 */}+ <span+ aria-hidden+ className={cn(+ 'w-px shrink-0 self-center transition-opacity group-hover:opacity-0',+ compact ? 'h-[14px] bg-[var(--create-agent-control-border)]' : 'h-[18px] bg-border',+ )}+ />+ {checkboxArea}+ </>+ )}</div>);}diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/BranchWorktreeChip.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/BranchWorktreeChip.test.tsxnew file mode 100644index 0000000000..d29c8c9811--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/BranchWorktreeChip.test.tsx@@ -0,0 +1,214 @@+// @vitest-environment jsdom+/** Test value: shared capsule is a new interactive protocol consumer. Verify real+ * component selection values, stale responses, retry and old-host fallback.+ * Previously only source-text guards covered the capsule. Minimal inputs: one+ * remote ref and a local origin/main namesake, an unresolved fetch, missing caps.+ * Tier: unit; mocked bridge only, no Git or real timers.+ */+import React from 'react';+import {+ act,+ cleanup,+ fireEvent,+ render as rtlRender,+ screen,+ waitFor,+} from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { BranchWorktreeChip } from '../WorktreeChipsRow';+import { Tooltip } from '@/components/ui/tooltip';+const render = (element: React.ReactElement) =>+ rtlRender(element, {+ wrapper: ({ children }) => <Tooltip.Provider>{children}</Tooltip.Provider>,+ });+const mocks = vi.hoisted(() => ({+ toast: vi.fn(),+ t: (key: string, args?: object) => key + (args ? JSON.stringify(args) : ''),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: mocks.t }) }));+vi.mock('@/lib/toast', () => ({ toast: { error: mocks.toast } }));+vi.mock('../FolderPickerPopover', () => ({+ FolderPickerPopover: () => null,+ addRecentFolder: vi.fn(),+}));+vi.mock('@/hooks/useProjectPickerOptions', () => ({ getProjectPickerDisplayName: () => '' }));+const baseStatus = {+ branch: 'main',+ remote: 'origin',+ remoteBranch: 'main',+ remoteOnly: false,+ ahead: 0,+ behind: 3,+ dirtyFiles: 2,+ checkoutPath: '/repo',+};+const status = vi.fn();+const sync = vi.fn();+const invoke = vi.fn();+const props = {+ baseRepo: '/repo',+ branchLabel: 'main',+ branches: ['main', 'origin/main'],+ branchesLoading: false,+ branchesFailed: false,+ onRetryBranches: vi.fn(),+ checked: true,+ branchSourceSelected: true,+ branchInteractive: true,+ onPick: vi.fn(),+ onOpenRequested: vi.fn(),+ onToggle: vi.fn(),+ remoteDefaultBranch: 'refs/remotes/origin/main',+};+beforeEach(() => {+ vi.clearAllMocks();+ status.mockResolvedValue(baseStatus);+ sync.mockResolvedValue({ status: { ...baseStatus, behind: 0 }, updated: 3 });+ Object.assign(window, {+ electronAPI: {+ worktreeBranchSyncStatus: status,+ worktreeSyncBranch: sync,+ deviceLink: { invoke },+ },+ });+ Element.prototype.scrollIntoView = vi.fn();+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});+const branchButton = () => screen.getByRole('button', { name: 'newChat.branchChip.label' });+const refreshButton = () => screen.getByRole('button', { name: /newChat.branchSync.action/ });+it('shares counts with the selected row and keeps full remote refs distinct during keyboard search', async () => {+ render(<BranchWorktreeChip {...props} />);+ await waitFor(() => expect(status).toHaveBeenCalledOnce());+ await act(async () => {+ fireEvent.click(branchButton());+ });+ expect(screen.getByRole('group', { name: 'newChat.branchSync.remoteGroup' })).toBeTruthy();+ expect(screen.getByText(/newChat.branchSync.behind/).textContent).toContain(+ 'newChat.branchSync.dirty',+ );+ const input = screen.getByRole('combobox');+ fireEvent.change(input, { target: { value: 'origin/main' } });+ expect(screen.getAllByRole('option')).toHaveLength(2);+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(props.onPick).toHaveBeenCalledWith('refs/remotes/origin/main');+ await act(async () => {+ fireEvent.click(branchButton());+ });+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'origin/main' } });+ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'ArrowDown' });+ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Enter' });+ expect(props.onPick).toHaveBeenLastCalledWith('origin/main');+});+it('shows remote sources only when worktree is checked or branchOnly is used', async () => {+ const view = render(<BranchWorktreeChip {...props} checked={false} />);+ await waitFor(() => expect(refreshButton().hasAttribute('disabled')).toBe(false));+ await act(async () => {+ fireEvent.click(branchButton());+ });+ expect(screen.queryByRole('group', { name: 'newChat.branchSync.remoteGroup' })).toBeNull();+ view.rerender(<BranchWorktreeChip {...props} checked={false} branchOnly />);+ expect(screen.getByRole('group', { name: 'newChat.branchSync.remoteGroup' })).toBeTruthy();+});+it('hides the action when an old controlled host rejects the status channel', async () => {+ invoke.mockRejectedValue(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] Old host'));+ render(<BranchWorktreeChip {...props} remoteDefaultBranch={undefined} deviceId="old-pc" />);+ await waitFor(() =>+ expect(screen.queryByRole('button', { name: /newChat.branchSync/ })).toBeNull(),+ );+ expect(status).not.toHaveBeenCalled();+ expect(invoke).toHaveBeenCalledWith('old-pc', 'worktree:branch-sync-status', [+ { baseRepo: '/repo', branch: 'main' },+ ]);+ expect(sync).not.toHaveBeenCalled();+});+it('blocks duplicate refresh clicks while leaving branch selection usable', async () => {+ let resolve!: (value: unknown) => void;+ sync.mockReturnValue(+ new Promise((r) => {+ resolve = r;+ }),+ );+ render(<BranchWorktreeChip {...props} />);+ await waitFor(() => expect(refreshButton().hasAttribute('disabled')).toBe(false));+ fireEvent.click(refreshButton());+ fireEvent.click(screen.getByRole('button', { name: /newChat.branchSync.fetching/ }));+ await act(async () => {+ fireEvent.click(branchButton());+ });+ expect(screen.getByRole('combobox')).toBeTruthy();+ expect(sync).toHaveBeenCalledOnce();+ await act(async () => resolve({ status: baseStatus, updated: 3 }));+ expect(screen.getByRole('button', { name: /newChat.branchSync.updated/ })).toBeTruthy();+});+it('explains a disabled conflict, then rechecks locally on hover', async () => {+ status.mockResolvedValueOnce({ ...baseStatus, blocked: 'conflict' });+ render(<BranchWorktreeChip {...props} />);+ const button = await screen.findByRole('button', { name: /newChat.branchSync.conflict/ });+ expect(button.getAttribute('aria-disabled')).toBe('true');+ expect(button.parentElement?.tabIndex).toBe(0);+ vi.useFakeTimers();+ fireEvent.mouseEnter(button.parentElement!);+ await act(async () => vi.advanceTimersByTime(250));+ expect(status).toHaveBeenCalledTimes(2);+ expect(refreshButton().hasAttribute('disabled')).toBe(false);+});+it('reports failed fetches in a toast and permits retry without selecting anything', async () => {+ sync.mockRejectedValueOnce(new Error('[INTERNAL] Authentication failed'));+ render(<BranchWorktreeChip {...props} />);+ await waitFor(() => expect(refreshButton().hasAttribute('disabled')).toBe(false));+ fireEvent.click(refreshButton());+ const retry = await screen.findByRole('button', { name: /newChat.branchSync.failed/ });+ expect(mocks.toast).toHaveBeenCalledOnce();+ expect(retry.hasAttribute('disabled')).toBe(false);+ fireEvent.click(retry);+ await screen.findByRole('button', { name: /newChat.branchSync.updated/ });+ expect(props.onPick).not.toHaveBeenCalled();+});+it('routes to the selected device and discards a late status from the previous branch', async () => {+ let resolve!: (value: unknown) => void;+ invoke+ .mockReturnValueOnce(+ new Promise((r) => {+ resolve = r;+ }),+ )+ .mockResolvedValue({ ...baseStatus, branch: 'next' });+ const view = render(<BranchWorktreeChip {...props} deviceId="pc" />);+ view.rerender(<BranchWorktreeChip {...props} deviceId="pc" branchLabel="next" />);+ await waitFor(() =>+ expect(invoke).toHaveBeenLastCalledWith('pc', 'worktree:branch-sync-status', [+ { baseRepo: '/repo', branch: 'next' },+ ]),+ );+ await act(async () => resolve({ ...baseStatus, blocked: 'conflict' }));+ expect(screen.queryByRole('button', { name: /newChat.branchSync.conflict/ })).toBeNull();+ fireEvent.click(refreshButton());+ await waitFor(() =>+ expect(invoke).toHaveBeenLastCalledWith('pc', 'worktree:sync-branch', [+ { baseRepo: '/repo', branch: 'next' },+ ]),+ );+ expect(status).not.toHaveBeenCalled();+});++it('keeps a fetched missing-remote result disabled across local rechecks, but clears it after changing branch', async () => {+ sync.mockResolvedValue({ status: { ...baseStatus, blocked: 'missing-remote' }, updated: 0 });+ const view = render(<BranchWorktreeChip {...props} />);+ await waitFor(() => expect(refreshButton().hasAttribute('disabled')).toBe(false));+ fireEvent.click(refreshButton());+ await screen.findByRole('button', { name: /newChat.branchSync.missing-remote/ });+ await act(async () => {+ fireEvent.click(branchButton());+ });+ await waitFor(() => expect(status).toHaveBeenCalledTimes(2));+ expect(+ screen+ .getByRole('button', { name: /newChat.branchSync.missing-remote/ })+ .hasAttribute('disabled'),+ ).toBe(true);+ view.rerender(<BranchWorktreeChip {...props} branchLabel="other" />);+ await waitFor(() => expect(refreshButton().hasAttribute('disabled')).toBe(false));+});diff --git a/apps/desktop/src/renderer/features/cc-agent/WorkerProjectField.tsx b/apps/desktop/src/renderer/features/cc-agent/WorkerProjectField.tsxindex 29dd3d5ec7..01e262f3f7 100644--- a/apps/desktop/src/renderer/features/cc-agent/WorkerProjectField.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/WorkerProjectField.tsx@@ -135,6 +135,7 @@ export function WorkerProjectField({const [branchSnapshot, setBranchSnapshot] = useState<{base: string;values: string[];+ remoteDefaultBranch?: string;failed?: boolean;}>();const [branchLoading, setBranchLoading] = useState(false);@@ -155,7 +156,11 @@ export function WorkerProjectField({.then((value) => {if (request === branchRequest.current)- setBranchSnapshot({ base, values: value.branches });+ setBranchSnapshot({+ base,+ values: value.branches,+ remoteDefaultBranch: value.remoteDefaultBranch,+ });},() => {if (request === branchRequest.current)@@ -177,7 +182,9 @@ export function WorkerProjectField({? t('orca.workerProject.detachedHead', { sha: context.selected.branch?.slice(0, 8) }): (context?.selected.branch ?? '—');const sourceBranchLabel =- detached && branch === context?.selected.branch ? currentBranchLabel : branch;+ detached && branch === context?.selected.branch+ ? currentBranchLabel+ : branch.replace(/^refs\/remotes\//, '');return (<div className="mb-4 space-y-2 text-12 text-[var(--text-secondary)]"><div className="font-medium text-[var(--text-tertiary)]">{t('orca.workerProject.label')}</div>@@ -272,6 +279,12 @@ export function WorkerProjectField({branchOnlycompactbranchLabel={branch}+ baseRepo={base}+ remoteDefaultBranch={+ branchSnapshot?.base === base+ ? branchSnapshot.remoteDefaultBranch+ : undefined+ }branchDisplayLabel={sourceBranchLabel}branches={branchSnapshot?.base === base ? branchSnapshot.values : []}branchesLoading={branchLoading}diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsxindex 5022c0f658..232fb0285d 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx@@ -6,6 +6,7 @@ import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react';import { useState } from 'react';+import { Tooltip } from '@/components/ui/tooltip';import userEvent from '@testing-library/user-event';import { renderToString } from 'react-dom/server';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -2219,7 +2220,7 @@ describe('local Worker project selection', () => {beforeEach(() => {Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() });projectContext.mockReset().mockResolvedValue(context);- (window as unknown as {electronAPI: unknown}).electronAPI = {localDb: {orcaWorkflows: {projectContext}}};+ (window as unknown as {electronAPI: unknown}).electronAPI = {localDb: {orcaWorkflows: {projectContext}}, worktreeListBranches: vi.fn().mockResolvedValue({branches: ['main']})};});afterEach(() => {cleanup(); Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView'); delete (window as unknown as {electronAPI?: unknown}).electronAPI;});// Native picker cancellation does not select a project. Rejected IPC must also leave@@ -2272,7 +2273,7 @@ describe('local Worker project selection', () => {const missing = {...project, directory: '/gone', baseRepo: null, branch: null, exists: false};projectContext.mockResolvedValue({...context, selected: missing});const onCreate = vi.fn();- render(<ProjectForm onCreate={onCreate} />);+ render(<Tooltip.Provider><ProjectForm onCreate={onCreate} /></Tooltip.Provider>);await screen.findByText('orca.workerProject.missingDirectory');expect(screen.queryByText('orca.workerProject.notGit /gone')).toBeNull();expect(screen.queryByRole('checkbox')).toBeNull();@@ -2285,7 +2286,7 @@ describe('local Worker project selection', () => {const empty = {...project, branch: null, headState: 'unborn'};projectContext.mockResolvedValue({...context, inherited: empty, selected: empty});const onCreate = vi.fn();- render(<ProjectForm onCreate={onCreate} />);+ render(<Tooltip.Provider><ProjectForm onCreate={onCreate} /></Tooltip.Provider>);await screen.findByText('orca.workerProject.emptyRepo /repo');expect(screen.queryByRole('checkbox')).toBeNull();fireEvent.click(screen.getByRole('button', {name: 'Create'}));@@ -2297,7 +2298,7 @@ describe('local Worker project selection', () => {projectContext.mockResolvedValue({...context, selected: detached});window.electronAPI.worktreeListBranches = vi.fn().mockResolvedValue({branches: ['main']});const onCreate = vi.fn();- render(<ProjectForm onCreate={onCreate} />);+ render(<Tooltip.Provider><ProjectForm onCreate={onCreate} /></Tooltip.Provider>);await screen.findByText('orca.workerProject.directDetached other orca.workerProject.detachedHead abcdef01');fireEvent.click(screen.getByRole('checkbox'));const branchButton = screen.getByRole('button', {name: 'newChat.branchChip.label'});@@ -2311,6 +2312,24 @@ describe('local Worker project selection', () => {expect(onCreate).toHaveBeenLastCalledWith(expect.objectContaining({worktree: {sourceBranch: 'main'}}));expect(branchButton.textContent).toBe('main');});+ it('displays the remote source as origin/main but submits its full ref without fetching', async () => {+ window.electronAPI.worktreeListBranches = vi.fn().mockResolvedValue({branches: ['main'], remoteDefaultBranch: 'refs/remotes/origin/main'});+ window.electronAPI.worktreeBranchSyncStatus = vi.fn().mockResolvedValue({branch: 'main', remote: 'origin', remoteBranch: 'main', remoteOnly: false, ahead: 0, behind: 0, dirtyFiles: 0});+ window.electronAPI.worktreeSyncBranch = vi.fn();+ const onCreate = vi.fn();+ render(<Tooltip.Provider><ProjectForm onCreate={onCreate} /></Tooltip.Provider>);+ await screen.findByRole('checkbox');+ fireEvent.click(screen.getByRole('checkbox'));+ const branchButton = screen.getByRole('button', {name: 'newChat.branchChip.label'});+ expect(window.electronAPI.worktreeListBranches).not.toHaveBeenCalled();+ fireEvent.click(branchButton);+ fireEvent.click(await screen.findByRole('option', {name: 'origin/main'}));+ expect(branchButton.textContent).toBe('origin/main');+ expect(screen.getByText('orca.workerProject.splitWarning origin/main')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', {name: 'Create'}));+ expect(onCreate).toHaveBeenLastCalledWith({worktree: {sourceBranch: 'refs/remotes/origin/main'}});+ expect(window.electronAPI.worktreeSyncBranch).not.toHaveBeenCalled();+ });it('omits workingDir for unchanged inheritance and resets worktree choice on reopening', async () => {const {result, rerender} = renderHook(({open}) => useWorkerProjectSelection(open, 'lead', true), {initialProps: {open: true}});await waitFor(() => expect(result.current.ready).toBe(true));@@ -2374,7 +2393,7 @@ describe('local Worker project selection', () => {? {...project, directory: dir, branch: 'selected-branch'} : opening);window.electronAPI.showOpenDirectoryDialog = vi.fn().mockResolvedValue({canceled: false, path: directory});const onCreate = vi.fn();- render(<ProjectForm onCreate={onCreate} />);+ render(<Tooltip.Provider><ProjectForm onCreate={onCreate} /></Tooltip.Provider>);fireEvent.click(await screen.findByRole('button', {name: 'orca.workerProject.current'}));fireEvent.click(screen.getByRole('button', {name: 'newChat.folderPicker.browseProjectFolder'}));await waitFor(() => expect(projectContext).toHaveBeenLastCalledWith('lead', directory));diff --git a/apps/desktop/src/renderer/hooks/useBranchSync.ts b/apps/desktop/src/renderer/hooks/useBranchSync.tsnew file mode 100644index 0000000000..1188bebbd0--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useBranchSync.ts@@ -0,0 +1,188 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import {+ BRANCH_SYNC_ERROR_PREFIX,+ type BranchSyncStatus,+ type BranchSyncResult,+} from '../../shared/worktreeBranchSync';+import { extractIpcError } from '@/utils/ipcError';+import { toast } from '@/lib/toast';++/** One state source for the capsule action and the selected branch's status row. */+export function useBranchSync(+ baseRepo: string | undefined,+ branch: string,+ deviceId?: string | null,+) {+ const { t } = useTranslation();+ const key = JSON.stringify([baseRepo, branch, deviceId]);+ const currentKey = useRef(key);+ currentKey.current = key;+ const [snapshot, setSnapshot] = useState<{+ key: string;+ status?: BranchSyncStatus;+ busy?: boolean;+ result?: BranchSyncResult;+ error?: string;+ missingRemote?: boolean;+ unsupported?: boolean;+ }>({ key });+ const request = useRef(0);+ const busy = useRef(false);+ const hoverTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ const doneTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ const invoke = useCallback(+ (sync: boolean) => {+ const req = { baseRepo: baseRepo!, branch };+ if (deviceId)+ return window.electronAPI.deviceLink.invoke(+ deviceId,+ sync ? 'worktree:sync-branch' : 'worktree:branch-sync-status',+ [req],+ );+ return sync+ ? window.electronAPI.worktreeSyncBranch(req)+ : window.electronAPI.worktreeBranchSyncStatus(req);+ },+ [baseRepo, branch, deviceId],+ );+ const refresh = useCallback(async () => {+ if (!baseRepo || busy.current) return;+ const id = ++request.current;+ try {+ const status = (await invoke(false)) as BranchSyncStatus;+ if (currentKey.current === key && id === request.current)+ setSnapshot((old) => ({+ ...old,+ key,+ status:+ old.key === key && old.missingRemote+ ? { ...status, blocked: 'missing-remote' }+ : status,+ }));+ } catch (error) {+ if (+ currentKey.current === key &&+ id === request.current &&+ deviceId &&+ extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED'+ ) {+ setSnapshot({ key, unsupported: true });+ return;+ }+ if (currentKey.current === key && id === request.current)+ setSnapshot((old) =>+ old.key === key && old.missingRemote+ ? old+ : {+ key,+ error:+ extractIpcError(error)?.message ??+ (error instanceof Error ? error.message : String(error)),+ },+ );+ }+ }, [baseRepo, invoke, key, deviceId]);+ useEffect(() => {+ busy.current = false;+ setSnapshot({ key });+ void refresh();+ return () => {+ ++request.current;+ clearTimeout(hoverTimer.current);+ clearTimeout(doneTimer.current);+ };+ }, [key, refresh]);+ const sync = async () => {+ if (!baseRepo || busy.current) return;+ busy.current = true;+ const id = ++request.current;+ setSnapshot((old) => ({ ...old, key, busy: true, error: undefined, result: undefined }));+ try {+ const result = (await invoke(true)) as BranchSyncResult;+ if (currentKey.current !== key || id !== request.current) return;+ setSnapshot({+ key,+ status: result.status,+ result,+ missingRemote: result.status.blocked === 'missing-remote',+ });+ clearTimeout(doneTimer.current);+ doneTimer.current = setTimeout(() => {+ if (currentKey.current === key) setSnapshot((old) => ({ ...old, result: undefined }));+ }, 2_000);+ } catch (error) {+ if (currentKey.current !== key || id !== request.current) return;+ const message =+ extractIpcError(error)?.message ?? (error instanceof Error ? error.message : String(error));+ setSnapshot((old) => ({ ...old, busy: false, error: message }));+ toast.error(+ t('newChat.branchSync.failed', {+ reason: message.startsWith(BRANCH_SYNC_ERROR_PREFIX)+ ? t(`newChat.branchSync.errors.${message.slice(BRANCH_SYNC_ERROR_PREFIX.length)}`)+ : message,+ }),+ );+ } finally {+ if (currentKey.current === key && id === request.current) busy.current = false;+ }+ };+ const state = snapshot.key === key ? snapshot : { key };+ const status = state.status;+ const vars = {+ branch,+ remote: status?.remote ?? 'origin',+ remoteBranch: status?.remoteBranch ?? branch,+ };+ const errorText = state.error?.startsWith(BRANCH_SYNC_ERROR_PREFIX)+ ? t(`newChat.branchSync.errors.${state.error.slice(BRANCH_SYNC_ERROR_PREFIX.length)}`)+ : state.error;+ let hint = t('newChat.branchSync.action', vars);+ if (status?.remoteOnly) hint = t('newChat.branchSync.remoteAction', vars);+ if (status?.checkoutPath)+ hint += `\n${t('newChat.branchSync.checkedOut', { ...vars, directory: status.checkoutPath.split(/[\\/]/).filter(Boolean).at(-1) })}`;+ if (status?.blocked) hint = t(`newChat.branchSync.${status.blocked}`, vars);+ if (state.result && !status?.blocked)+ hint = state.result.updated+ ? t('newChat.branchSync.updated', { count: state.result.updated })+ : status?.ahead+ ? t('newChat.branchSync.keptAhead', { count: status.ahead })+ : t('newChat.branchSync.current');+ if (state.error) hint = t('newChat.branchSync.failed', { reason: errorText });+ if (state.busy) hint = t('newChat.branchSync.fetching', vars);+ const details = [+ status?.ahead+ ? t('newChat.branchSync.ahead', {+ ...vars,+ remote: `${vars.remote}/${vars.remoteBranch}`,+ count: status.ahead,+ })+ : '',+ status?.behind+ ? t('newChat.branchSync.behind', {+ ...vars,+ remote: `${vars.remote}/${vars.remoteBranch}`,+ count: status.behind,+ })+ : '',+ status?.checkoutPath && status.dirtyFiles+ ? t('newChat.branchSync.dirty', { count: status.dirtyFiles })+ : '',+ ]+ .filter(Boolean)+ .join(' · ');+ return {+ visible: !!baseRepo && !state.unsupported && status?.blocked !== 'not-local',+ disabled: !!state.busy || !!status?.blocked || (!status && !state.error),+ busy: !!state.busy,+ done: !!state.result && !status?.blocked,+ hint,+ details,+ sync,+ refresh,+ onHover: () => {+ clearTimeout(hoverTimer.current);+ hoverTimer.current = setTimeout(() => void refresh(), 250);+ },+ };+}diff --git a/apps/desktop/src/renderer/hooks/useWorktreeQueries.ts b/apps/desktop/src/renderer/hooks/useWorktreeQueries.tsindex f30904829f..a95215fff0 100644--- a/apps/desktop/src/renderer/hooks/useWorktreeQueries.ts+++ b/apps/desktop/src/renderer/hooks/useWorktreeQueries.ts@@ -144,6 +144,7 @@ export function useDetectCwd(}interface BranchesState {+ remoteDefaultBranch?: string;branches: string[];current: string | null;loading: boolean;@@ -176,8 +177,8 @@ export function branchesStateForTarget() {return { branches: [], current: null, loading: true, failed: false };}- const { branches, current, loading, failed } = snapshot;- return { branches, current, loading, failed };+ const { branches, current, loading, failed, remoteDefaultBranch } = snapshot;+ return { branches, current, loading, failed, remoteDefaultBranch };}/**@@ -232,6 +233,7 @@ export function useBranches(if (cancelled) return;setSnapshot({target: requestTarget,+ remoteDefaultBranch: res.remoteDefaultBranch,branches: res.branches ?? [],current: res.current ?? null,loading: false,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex eb03ab5c97..492ffdda8d 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -11365,6 +11365,35 @@"prompt": "Draft a reply to this email, taking the conversation and my thoughts into account. Don't send it yet."}}+ },+ "branchSync": {+ "action": "Fetch the latest commits for {{remoteBranch}} from {{remote}} and update local {{branch}}",+ "remoteAction": "Fetch the latest commits for {{remoteBranch}} from {{remote}}",+ "checkedOut": "{{branch}} is checked out in “{{directory}}”. Its files will also update; your uncommitted changes will be preserved.",+ "fetching": "Fetching from {{remote}}…",+ "updated": "Updated by {{count}} commits",+ "current": "Already up to date",+ "keptAhead": "Keeping the local version with {{count}} unpushed commits",+ "failed": "Last fetch failed: {{reason}}. Click to retry.",+ "diverged": "Local {{branch}} and {{remote}}/{{remoteBranch}} have diverged and cannot update automatically. The new worktree will use local {{branch}}.",+ "conflict": "Your uncommitted changes overlap the remote updates. Commit them or use git stash before updating.",+ "missing-remote": "{{remoteBranch}} does not exist on {{remote}}",+ "no-remote": "This project has no remote repository",+ "not-local": "Select a local branch or the remote default branch",+ "ahead": "{{count}} commits ahead of {{remote}}",+ "behind": "{{count}} commits behind {{remote}}",+ "dirty": "{{count}} uncommitted files",+ "remoteGroup": "Remote",+ "localGroup": "Local branches",+ "errors": {+ "git": "Git could not update the branch. Check repository access and retry.",+ "timeout": "Git timed out. Check the connection and retry.",+ "auth": "Git authentication failed. Check remote credentials.",+ "network": "Could not connect to the remote repository. Check the connection.",+ "missing": "The remote branch no longer exists.",+ "busy": "The repository changed or is busy. Retry after the other Git operation finishes.",+ "changed": "The checked-out branch changed. Retry."+ }}},"onboarding": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a53ff7f519..4a22b0644b 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -11330,6 +11330,35 @@"prompt": "このメールへの返信の下書きを作って。これまでのやり取りと私の考えを踏まえて、まだ送信しないで。"}}+ },+ "branchSync": {+ "action": "{{remote}} から {{remoteBranch}} の最新コミットを取得し、ローカルの {{branch}} を更新",+ "remoteAction": "{{remote}} から {{remoteBranch}} の最新コミットを取得",+ "checkedOut": "{{branch}} は「{{directory}}」で使用中です。そのファイルも更新されます。未コミットの変更は保持されます。",+ "fetching": "{{remote}} から取得中…",+ "updated": "{{count}} コミット更新しました",+ "current": "すでに最新です",+ "keptAhead": "未プッシュの {{count}} コミットを含むローカル版を保持します",+ "failed": "前回の取得に失敗:{{reason}}。クリックして再試行。",+ "diverged": "ローカルの {{branch}} と {{remote}}/{{remoteBranch}} は分岐しており、自動更新できません。新しい worktree はローカルの {{branch}} を使用します。",+ "conflict": "未コミットの変更とリモートの更新が同じファイルにあります。先にコミットするか、git stash で変更を退避してください。",+ "missing-remote": "{{remote}} に {{remoteBranch}} がありません",+ "no-remote": "このプロジェクトにリモートリポジトリはありません",+ "not-local": "ローカルブランチまたはリモートの既定ブランチを選択してください",+ "ahead": "{{remote}} より {{count}} コミット先行",+ "behind": "{{remote}} より {{count}} コミット遅れ",+ "dirty": "未コミットのファイル {{count}} 件",+ "remoteGroup": "リモート",+ "localGroup": "ローカルブランチ",+ "errors": {+ "git": "Git でブランチを更新できません。リポジトリへのアクセスを確認して再試行してください。",+ "timeout": "Git がタイムアウトしました。接続を確認して再試行してください。",+ "auth": "Git の認証に失敗しました。リモートの認証情報を確認してください。",+ "network": "リモートリポジトリに接続できません。接続を確認してください。",+ "missing": "リモートブランチは存在しません。",+ "busy": "リポジトリが変更されたか使用中です。他の Git 操作の完了後に再試行してください。",+ "changed": "チェックアウト中のブランチが変更されました。再試行してください。"+ }}},"onboarding": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b926f5632e..93e3e33218 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -11330,6 +11330,35 @@"prompt": "이 메일의 답장 초안을 써 줘. 주고받은 메일과 내 생각을 반영하고, 아직 보내지는 마."}}+ },+ "branchSync": {+ "action": "{{remote}}에서 {{remoteBranch}}의 최신 커밋을 가져와 로컬 {{branch}} 업데이트",+ "remoteAction": "{{remote}}에서 {{remoteBranch}}의 최신 커밋 가져오기",+ "checkedOut": "{{branch}}은(는) “{{directory}}”에서 사용 중입니다. 해당 파일도 업데이트되며 커밋하지 않은 변경 사항은 유지됩니다.",+ "fetching": "{{remote}}에서 가져오는 중…",+ "updated": "커밋 {{count}}개 업데이트됨",+ "current": "이미 최신 상태입니다",+ "keptAhead": "푸시하지 않은 커밋 {{count}}개가 있는 로컬 버전을 유지합니다",+ "failed": "마지막 가져오기 실패: {{reason}}. 클릭하여 다시 시도하세요.",+ "diverged": "로컬 {{branch}}와 {{remote}}/{{remoteBranch}} 양쪽에 새 커밋이 있어 자동 업데이트할 수 없습니다. 새 worktree는 로컬 {{branch}}을(를) 사용합니다.",+ "conflict": "커밋하지 않은 변경 사항과 원격 업데이트가 같은 파일에 있습니다. 먼저 커밋하거나 git stash로 변경 사항을 보관하세요.",+ "missing-remote": "{{remote}}에 {{remoteBranch}}이(가) 없습니다",+ "no-remote": "이 프로젝트에 원격 저장소가 설정되지 않았습니다",+ "not-local": "로컬 브랜치 또는 원격 기본 브랜치를 선택하세요",+ "ahead": "{{remote}}보다 커밋 {{count}}개 앞섬",+ "behind": "{{remote}}보다 커밋 {{count}}개 뒤처짐",+ "dirty": "커밋하지 않은 파일 {{count}}개",+ "remoteGroup": "원격",+ "localGroup": "로컬 브랜치",+ "errors": {+ "git": "Git이 브랜치를 업데이트하지 못했습니다. 저장소 접근 권한을 확인하고 다시 시도하세요.",+ "timeout": "Git 작업 시간이 초과되었습니다. 연결을 확인하고 다시 시도하세요.",+ "auth": "Git 인증에 실패했습니다. 원격 인증 정보를 확인하세요.",+ "network": "원격 저장소에 연결할 수 없습니다. 연결을 확인하세요.",+ "missing": "원격 브랜치가 더 이상 존재하지 않습니다.",+ "busy": "저장소가 변경되었거나 사용 중입니다. 다른 Git 작업이 끝난 후 다시 시도하세요.",+ "changed": "체크아웃된 브랜치가 변경되었습니다. 다시 시도하세요."+ }}},"onboarding": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 215d56cdcb..c8c818d7bd 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -11330,6 +11330,35 @@"prompt": "帮我为这封邮件写一份回复草稿,结合邮件往来和我的想法,先不发送。"}}+ },+ "branchSync": {+ "action": "从 {{remote}} 拉取 {{remoteBranch}} 的最新提交,并更新本地 {{branch}}",+ "remoteAction": "从 {{remote}} 拉取 {{remoteBranch}} 的最新提交",+ "checkedOut": "{{branch}} 正在「{{directory}}」里使用,那里的文件会一起更新,你没提交的改动不受影响",+ "fetching": "正在从 {{remote}} 拉取…",+ "updated": "已更新 {{count}} 个提交",+ "current": "已是最新",+ "keptAhead": "本地有 {{count}} 个提交还没推送,保留本地版本",+ "failed": "上次拉取失败:{{reason}},点击重试",+ "diverged": "本地 {{branch}} 和 {{remote}} 上的 {{remoteBranch}} 各有新提交,没法自动更新。新 worktree 会用本地 {{branch}}",+ "conflict": "你还没提交的改动和远程的更新涉及同一批文件,没法更新。可以先提交,或者用 git stash 把改动收起来",+ "missing-remote": "{{remote}} 上没有 {{remoteBranch}}",+ "no-remote": "这个项目没有设置远程仓库",+ "not-local": "请先选择本地分支或远程主分支",+ "ahead": "领先 {{remote}} {{count}} 个提交",+ "behind": "落后 {{remote}} {{count}} 个提交",+ "dirty": "未提交 {{count}} 个文件",+ "remoteGroup": "远程",+ "localGroup": "本地分支",+ "errors": {+ "git": "Git 无法更新分支,请检查仓库访问权限后重试",+ "timeout": "Git 操作超时,请检查网络连接后重试",+ "auth": "Git 认证失败,请检查远程仓库凭证",+ "network": "无法连接远程仓库,请检查网络连接",+ "missing": "远程分支已不存在",+ "busy": "仓库正在更新或已发生变化,请等其它 Git 操作完成后重试",+ "changed": "检出的分支已变化,请重试"+ }}},"onboarding": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 0e823f9a27..a3937013be 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -11330,6 +11330,35 @@"prompt": "幫我為這封郵件寫一份回覆草稿,結合郵件往來和我的想法,先不寄送。"}}+ },+ "branchSync": {+ "action": "從 {{remote}} 取得 {{remoteBranch}} 的最新提交,並更新本機 {{branch}}",+ "remoteAction": "從 {{remote}} 取得 {{remoteBranch}} 的最新提交",+ "checkedOut": "{{branch}} 正在「{{directory}}」中使用,那裡的檔案會一起更新,你尚未提交的變更不受影響",+ "fetching": "正在從 {{remote}} 取得更新…",+ "updated": "已更新 {{count}} 個提交",+ "current": "已是最新",+ "keptAhead": "本機有 {{count}} 個提交尚未推送,保留本機版本",+ "failed": "上次取得更新失敗:{{reason}},點擊重試",+ "diverged": "本機 {{branch}} 和 {{remote}} 上的 {{remoteBranch}} 各有新提交,無法自動更新。新 worktree 會使用本機 {{branch}}",+ "conflict": "尚未提交的變更與遠端更新涉及相同檔案,無法更新。請先提交,或使用 git stash 收起變更",+ "missing-remote": "{{remote}} 上沒有 {{remoteBranch}}",+ "no-remote": "這個專案沒有設定遠端儲存庫",+ "not-local": "請先選擇本機分支或遠端主分支",+ "ahead": "領先 {{remote}} {{count}} 個提交",+ "behind": "落後 {{remote}} {{count}} 個提交",+ "dirty": "尚未提交 {{count}} 個檔案",+ "remoteGroup": "遠端",+ "localGroup": "本機分支",+ "errors": {+ "git": "Git 無法更新分支,請檢查儲存庫存取權限後重試",+ "timeout": "Git 操作逾時,請檢查網路連線後重試",+ "auth": "Git 認證失敗,請檢查遠端儲存庫憑證",+ "network": "無法連線至遠端儲存庫,請檢查網路連線",+ "missing": "遠端分支已不存在",+ "busy": "儲存庫正在更新或已變更,請等其他 Git 操作完成後重試",+ "changed": "檢出的分支已變更,請重試"+ }}},"onboarding": {diff --git a/apps/desktop/src/renderer/lib/worktree.types.ts b/apps/desktop/src/renderer/lib/worktree.types.tsindex 3e7dc1b65b..311318224f 100644--- a/apps/desktop/src/renderer/lib/worktree.types.ts+++ b/apps/desktop/src/renderer/lib/worktree.types.ts@@ -69,6 +69,8 @@ export interface DetectCwdResp {}export interface ListBranchesResp {+ /** Full ref, never a local branch named origin/main. */+ remoteDefaultBranch?: string;branches: string[];/** 当前 HEAD 所在分支名(用于默认值)。 */current: string;diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex fe0f3298e8..58176516ef 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4409,6 +4409,8 @@ interface ElectronAPI {worktreeSuggestName: (req: {baseRepo: string;}) => Promise<import('@/lib/worktree.types').SuggestNameResp>;+ worktreeBranchSyncStatus: (req: import('../shared/worktreeBranchSync').BranchSyncRequest) => Promise<import('../shared/worktreeBranchSync').BranchSyncStatus>;+ worktreeSyncBranch: (req: import('../shared/worktreeBranchSync').BranchSyncRequest) => Promise<import('../shared/worktreeBranchSync').BranchSyncResult>;worktreeListBranches: (req: {baseRepo: string;}) => Promise<import('@/lib/worktree.types').ListBranchesResp>;diff --git a/apps/desktop/src/shared/worktreeBranchSync.ts b/apps/desktop/src/shared/worktreeBranchSync.tsnew file mode 100644index 0000000000..ba8a974779--- /dev/null+++ b/apps/desktop/src/shared/worktreeBranchSync.ts@@ -0,0 +1,25 @@+/** Append-only desktop/device-link contract; creation never waits for branch sync. */+export interface BranchSyncRequest {+ baseRepo: string;+ branch: string;+}+export interface BranchSyncStatus {+ branch: string;+ remote?: string;+ remoteBranch?: string;+ remoteRef?: string;+ remoteOnly: boolean;+ ahead: number;+ behind: number;+ dirtyFiles: number;+ checkoutPath?: string;+ blocked?: 'no-remote' | 'missing-remote' | 'diverged' | 'conflict' | 'not-local';+}+export interface BranchSyncResult {+ status: BranchSyncStatus;+ updated: number;+}++export const BRANCH_SYNC_ERROR_PREFIX = 'branch-sync:';+export type BranchSyncFailureReason =+ 'git' | 'timeout' | 'auth' | 'network' | 'missing' | 'busy' | 'changed';diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex b705b4b59c..71c91e7abf 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,22 @@# 跨端协议兼容+## 手动对齐 worktree 源分支++`worktree:list-branches` 的 IPC 响应可选追加 `remoteDefaultBranch`+(完整的 `refs/remotes/origin/*` 引用);仅 UI 查询补充,失败不影响本地分支列表,+创建使用的 `listBranches()` 保持原样。列表仍按原有约定懒加载。+本地支持刷新;控制端查询 `worktree:branch-sync-status`,旧被控端返回+`DEVICE_LINK_CHANNEL_NOT_ALLOWED` 时隐藏刷新按钮,缺少可选字段时不显示远程分组,+本地分支选择与创建保持原行为。新被控端继续接受旧请求。+状态查询只读本地 Git;缺本地 tracking ref 不代表远程分支不存在,仍允许拉取。+仅拉取确认远程分支不存在后,在本次胶囊选择内置灰;换分支或重新挂载即重新判断。+同步仅由用户点击触发,按配置的 tracking remote/ref(否则 origin 同名分支)拉取一个显式+refspec,再按需快进本地分支。+设备互联对单次同步预留 90 秒(网络 Git 30 秒及清理、本地探测),失败不重放写请求、+不重置 peer 或 relay;创建和发送不等待同步,不改用其它源引用。手机本轮不提供入口。+实现见 `apps/desktop/src/main/worktree/branchSync.ts`;真实 Git 回归在+`branchSync.git-integration.test.ts`。+## IM 状态表情由客户端声明官方 Slack / Telegram 的 `hello` 新增可选 `statusReactions`:`queued`、`error` 为diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex 75e30e4faf..60178c070e 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -281,6 +281,8 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {for (const ch of ['worktree:detect-cwd','worktree:list-branches',+ 'worktree:branch-sync-status',+ 'worktree:sync-branch','worktree:suggest-name','worktree:create','worktree:discard-precreated',diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 015c2b2f44..0d07d0e22d 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -678,6 +678,10 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [// 老被控端无这些 channel → CHANNEL_NOT_ALLOWED → 控制端按对应能力降级。'worktree:detect-cwd','worktree:list-branches',+ // Sync status is local-only; sync mutates only by explicit fetch + fast-forward.+ // sync-branch baseRepo also passes dispatch PATH_GUARDED_CHANNELS.+ 'worktree:branch-sync-status',+ 'worktree:sync-branch','worktree:suggest-name','worktree:create','worktree:discard-precreated',@@ -863,6 +867,8 @@ export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {// 被控端 worktree:create 含 git worktree add(--no-checkout)+ 白名单文件选择性// checkout + .claude/.sivi 拷贝;大仓库 / 慢盘上可能超默认 30s,给足执行预算 + 回程余量。'worktree:create': 60_000,+ // User-triggered fetch (30s) plus local probes and process cleanup. Never replay.+ 'worktree:sync-branch': 90_000,// 可能先等待同 sessionId 的晚到 create 释放互斥锁,再执行 git worktree remove。'worktree:discard-precreated': 60_000,'worktree:cancel-precreated': 60_000,