diff --git a/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts b/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts index 1ac832f4131..34056e67a44 100644 --- a/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts +++ b/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts @@ -1,3 +1,4 @@ +import { randomBytes } from 'node:crypto' import { readFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' @@ -145,15 +146,41 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync { } } + let syncer: string | null = null + /** This computer's stable sync identity (random, not a device fingerprint). */ + function syncerId(): string { + if (syncer) { + return syncer + } + const path = join(deps.userDataPath, 'mcp-sync-syncer-id') + try { + const stored = readFileSync(path, 'utf8').trim() + if (/^[a-f0-9]{16}$/.test(stored)) { + syncer = stored + return stored + } + } catch { + // First sync from this computer. + } + syncer = randomBytes(8).toString('hex') + try { + writeFileAtomically(path, `${syncer}\n`) + } catch { + // Unwritable profile: this run still syncs as itself; the next launch gets a new id. + } + return syncer + } + async function plan(environmentId: string) { const runtime = cloudRuntime(environmentId) const local = await readLocal(runtime?.repoPath ?? null) - return planMcpSync({ + const planned = planMcpSync({ servers: local.servers, excluded: new Set(getPreferences().excluded), repoServerNames: local.repoServerNames, homeDir: homedir() }) + return { ...planned, params: { ...planned.params, syncer: syncerId() } } } function publish(status: McpSyncStatus): McpSyncStatus { diff --git a/src/main/agent-mcp-sync/host/codex-toml-mcp-merge.ts b/src/main/agent-mcp-sync/host/codex-toml-mcp-merge.ts index 93f989362ea..8dd1f7d9ab0 100644 --- a/src/main/agent-mcp-sync/host/codex-toml-mcp-merge.ts +++ b/src/main/agent-mcp-sync/host/codex-toml-mcp-merge.ts @@ -17,13 +17,22 @@ export type CodexMcpMergeResult = { type Block = { before: string; body: string; after: string } -function findBlock(text: string): Block | null { +export type CodexMcpBlockMarkers = { start: string; end: string } + +/** One marked block per syncing computer, so two computers syncing one host never rewrite each other's. */ +export function codexMcpBlockMarkers(syncer: string | undefined): CodexMcpBlockMarkers { + return syncer + ? { start: `${CODEX_MCP_BLOCK_START} [${syncer}]`, end: `${CODEX_MCP_BLOCK_END} [${syncer}]` } + : { start: CODEX_MCP_BLOCK_START, end: CODEX_MCP_BLOCK_END } +} + +function findBlock(text: string, markers: CodexMcpBlockMarkers): Block | null { const lines = text.split('\n') - const start = lines.indexOf(CODEX_MCP_BLOCK_START) + const start = lines.indexOf(markers.start) if (start === -1) { return null } - const end = lines.indexOf(CODEX_MCP_BLOCK_END, start + 1) + const end = lines.indexOf(markers.end, start + 1) if (end === -1) { throw new Error('codex_config_block_unterminated') } @@ -54,12 +63,15 @@ function joinParts(parts: string[]): string { export function mergeCodexMcpServers( text: string | null, desired: Readonly>>, - lastBlockPrint: string | null + lastBlockPrint: string | null, + markers: CodexMcpBlockMarkers = codexMcpBlockMarkers(undefined), + /** Markers of a block this computer is taking over (the pre-per-computer block it wrote). */ + adopt?: CodexMcpBlockMarkers ): CodexMcpMergeResult { const source = text ?? '' // Refuse to edit a file Codex itself could not load. parseToml(source) - const block = findBlock(source) + const block = findBlock(source, markers) ?? (adopt ? findBlock(source, adopt) : null) const handEdited = block !== null && fingerprintMcpValue(block.body) !== lastBlockPrint const outside = block ? handEdited @@ -89,7 +101,7 @@ export function mergeCodexMcpServers( if (!block && !body) { return { text: null, blockPrint: null, outcomes } } - const blockText = body ? `${CODEX_MCP_BLOCK_START}\n${body}\n${CODEX_MCP_BLOCK_END}` : '' + const blockText = body ? `${markers.start}\n${body}\n${markers.end}` : '' const next = block && !handEdited ? joinParts([block.before, blockText, block.after]) diff --git a/src/main/agent-mcp-sync/host/host-mcp-sync.test.ts b/src/main/agent-mcp-sync/host/host-mcp-sync.test.ts index de67eac0aa4..6678f3d3bf1 100644 --- a/src/main/agent-mcp-sync/host/host-mcp-sync.test.ts +++ b/src/main/agent-mcp-sync/host/host-mcp-sync.test.ts @@ -70,4 +70,53 @@ describe('syncHostMcpServers', () => { mine: { command: 'host-only' } }) }) + + it('two computers syncing one shared sandbox keep each other’s servers (no flapping)', async () => { + const a = { + claude: { fromA: { command: 'npx' } }, + codex: { fromA: { command: 'npx' } }, + syncer: 'aaaa' + } + const b = { + claude: { fromB: { command: 'npx' } }, + codex: { fromB: { command: 'npx' } }, + syncer: 'bbbb' + } + await syncHostMcpServers(a, deps()) + await syncHostMcpServers(b, deps()) + const again = await syncHostMcpServers(a, deps()) + expect(again.claude).toEqual({ fromA: 'unchanged' }) + expect(again.codex).toEqual({ fromA: 'unchanged' }) + expect( + Object.keys(JSON.parse(readFileSync(paths.claudeConfig, 'utf8')).mcpServers).sort() + ).toEqual(['fromA', 'fromB']) + const toml = readFileSync(paths.codexConfig, 'utf8') + expect(toml).toContain('[aaaa]') + expect(toml).toContain('[bbbb]') + // A stops syncing fromA: only A's entry goes. + await syncHostMcpServers({ claude: {}, codex: {}, syncer: 'aaaa' }, deps()) + expect(Object.keys(JSON.parse(readFileSync(paths.claudeConfig, 'utf8')).mcpServers)).toEqual([ + 'fromB' + ]) + expect(readFileSync(paths.codexConfig, 'utf8')).not.toContain('fromA') + }) + + it('the first computer with an id takes over what the shared ledger wrote, once', async () => { + await syncHostMcpServers( + { claude: { old: { command: 'npx' } }, codex: { old: { command: 'npx' } } }, + deps() + ) + const adopted = await syncHostMcpServers( + { claude: { old: { command: 'npx' } }, codex: { old: { command: 'npx' } }, syncer: 'cccc' }, + deps() + ) + expect(adopted.claude).toEqual({ old: 'unchanged' }) + expect(adopted.codex).toEqual({ old: 'unchanged' }) + const toml = readFileSync(paths.codexConfig, 'utf8') + expect(toml.match(/mcp_servers\.old/g)).toHaveLength(1) + expect(toml).toContain('[cccc]') + // Removing works through the adopted ledger. + await syncHostMcpServers({ claude: {}, codex: {}, syncer: 'cccc' }, deps()) + expect(JSON.parse(readFileSync(paths.claudeConfig, 'utf8')).mcpServers ?? {}).toEqual({}) + }) }) diff --git a/src/main/agent-mcp-sync/host/host-mcp-sync.ts b/src/main/agent-mcp-sync/host/host-mcp-sync.ts index 2dbf2a16e58..238d6ed9852 100644 --- a/src/main/agent-mcp-sync/host/host-mcp-sync.ts +++ b/src/main/agent-mcp-sync/host/host-mcp-sync.ts @@ -12,8 +12,8 @@ import { writeFileAtomicallyIfUnchanged } from '../../filesystem/atomic-file-pub import { isCommandOnLocalPath } from '../../ipc/command-path/command-path-resolver' import { hostShellEnvironment } from '../../runtime/agent-session/environment/structured-agent-shell-environment' import { mergeClaudeMcpServers } from './claude-json-mcp-merge' -import { mergeCodexMcpServers } from './codex-toml-mcp-merge' -import { parseMcpSyncLedger, type McpSyncLedger } from './mcp-sync-ledger' +import { codexMcpBlockMarkers, mergeCodexMcpServers } from './codex-toml-mcp-merge' +import { EMPTY_MCP_SYNC_LEDGER, parseMcpSyncLedger, type McpSyncLedger } from './mcp-sync-ledger' // Agent configs carry MCP env tokens and headers; keep them owner-only. const PRIVATE_FILE = { mode: 0o600 } as const @@ -33,6 +33,10 @@ export type HostMcpSyncDeps = { resolves?: (hostname: string) => Promise } +export function syncerLedgerPath(sharedLedger: string, syncer: string): string { + return sharedLedger.replace(/\.json$/, `-${syncer}.json`) +} + export function defaultHostMcpSyncPaths(userDataPath: string): HostMcpSyncPaths { const claudeDir = process.env.CLAUDE_CONFIG_DIR?.trim() return { @@ -150,13 +154,21 @@ async function syncClaude( async function syncCodex( paths: HostMcpSyncPaths, desired: Record>, - ledger: McpSyncLedger + ledger: McpSyncLedger, + syncer: string | undefined, + adoptLegacy: boolean ): Promise> { for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) { const text = await readText(paths.codexConfig) let merged: ReturnType try { - merged = mergeCodexMcpServers(text, desired, ledger.codexBlock) + merged = mergeCodexMcpServers( + text, + desired, + ledger.codexBlock, + codexMcpBlockMarkers(syncer), + adoptLegacy ? codexMcpBlockMarkers(undefined) : undefined + ) } catch { return unreadable(desired) } @@ -175,8 +187,17 @@ export async function syncHostMcpServers( ): Promise { const commandExists = deps.commandExists ?? defaultCommandExists const resolves = deps.resolves ?? defaultResolves - const ledgerText = await readText(deps.paths.ledger) - const ledger = parseMcpSyncLedger(ledgerText) + // Each syncing computer has its own ledger: entries another computer wrote are not this one's to + // remove (they read as the host's own), so two computers on one shared sandbox never flap. + const ledgerPath = params.syncer + ? syncerLedgerPath(deps.paths.ledger, params.syncer) + : deps.paths.ledger + const ownText = await readText(ledgerPath) + // The first computer to sync after per-computer ledgers takes over what the shared ledger recorded. + const legacyText = params.syncer && ownText === null ? await readText(deps.paths.ledger) : null + const adoptLegacy = legacyText !== null + const ledgerText = ownText + const ledger = parseMcpSyncLedger(ownText ?? legacyText) const result: AgentMcpSyncResult = {} if (params.claude) { const outcomes: Record = {} @@ -186,11 +207,22 @@ export async function syncHostMcpServers( if (params.codex) { const outcomes: Record = {} const desired = await runnable(params.codex, commandExists, outcomes) - result.codex = { ...outcomes, ...(await syncCodex(deps.paths, desired, ledger)) } + result.codex = { + ...outcomes, + ...(await syncCodex(deps.paths, desired, ledger, params.syncer, adoptLegacy)) + } } const nextLedger = `${JSON.stringify(ledger, null, 2)}\n` if (nextLedger !== ledgerText) { - await writePrivate(deps.paths.ledger, ledgerText, nextLedger) + await writePrivate(ledgerPath, ledgerText, nextLedger) + } + if (adoptLegacy) { + // Claimed: a second computer must not adopt the same entries. + await writePrivate( + deps.paths.ledger, + legacyText, + `${JSON.stringify(EMPTY_MCP_SYNC_LEDGER, null, 2)}\n` + ) } const hostnames = remoteHostnames(params) const reachable = await Promise.all(hostnames.map(resolves)) diff --git a/src/shared/agent-mcp-sync/mcp-sync-contract.ts b/src/shared/agent-mcp-sync/mcp-sync-contract.ts index 33a96e065ba..412739b0d9f 100644 --- a/src/shared/agent-mcp-sync/mcp-sync-contract.ts +++ b/src/shared/agent-mcp-sync/mcp-sync-contract.ts @@ -47,7 +47,12 @@ const ServerSet = z export const AgentMcpSyncParams = z .object({ claude: ServerSet.optional(), - codex: ServerSet.optional() + codex: ServerSet.optional(), + /** Stable id of the syncing computer: each one owns (and only removes) its own entries. */ + syncer: z + .string() + .regex(/^[A-Za-z0-9_-]{1,64}$/) + .optional() }) .strict() export type AgentMcpSyncParams = z.infer