From ef461007ea7e8aa3b2e4554f87b70c0c5008943b Mon Sep 17 00:00:00 2001 From: Rahul Sharma Date: Wed, 18 Nov 2026 16:31:02 +0530 Subject: [PATCH] feat: add optional periodic config sync (autoSync) --- README.md | 22 +++++ src/sync/config.test.ts | 18 ++++ src/sync/config.ts | 35 ++++++++ src/sync/repo.ts | 2 +- src/sync/service.test.ts | 184 ++++++++++++++++++++++++++++++++++++++- src/sync/service.ts | 159 +++++++++++++++++++++++++++++++++ 6 files changed, 415 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d371aee..5777336 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ Create `~/.config/opencode/opencode-synced.jsonc`: "includeModelFavorites": true, "includeOpencodeSkills": true, "includeAgentsDir": true, + "autoSync": { "enabled": false, "intervalSec": 300, "push": true, "pull": true }, "extraSecretPaths": [], "extraConfigPaths": [], } @@ -155,6 +156,27 @@ Create `~/.config/opencode/opencode-synced.jsonc`: Review it before syncing, keep the sync repository private when needed, or set `"includeAgentsDir": false` to opt out. +### Automatic sync + +By default config is synced when opencode starts (and when you run pull or push). On a long-running +opencode server that can leave machines diverged for days. Set `autoSync` to also sync on a timer: + +```jsonc +{ + "autoSync": { "enabled": true, "intervalSec": 300, "push": true, "pull": true } +} +``` + +- `intervalSec` defaults to 300 and is clamped to at least 30. +- `push`: commit and push local config changes. `pull`: apply remote changes. +- A pass never overwrites unpushed local edits. It stages your local config first, and if the remote + also changed it stops, leaves your files alone, and shows one notice asking you to run pull or push + yourself. Resolve it and the next pass continues. +- It does nothing while another sync is running, and pulled changes still need an opencode restart. +- `opencode-synced.jsonc` is itself synced, so enabling this on one machine enables it on the others + at their next pull. +- The Turso `syncIntervalSec` setting is separate and only applies to session sync. + Disable default directory sync by setting: - `"includeOpencodeSkills": false` to skip `~/.config/opencode/skills/` - `"includeAgentsDir": false` to skip `~/.agents/` diff --git a/src/sync/config.test.ts b/src/sync/config.test.ts index 7e4ff1c..3e994a2 100644 --- a/src/sync/config.test.ts +++ b/src/sync/config.test.ts @@ -152,6 +152,24 @@ describe('normalizeSyncConfig', () => { expect(normalized.includeAgentsDir).toBe(false); }); + it('normalizes autoSync with a disabled default and a minimum interval', () => { + expect(normalizeSyncConfig({}).autoSync).toEqual({ + enabled: false, + intervalSec: 300, + push: true, + pull: true, + }); + expect( + normalizeSyncConfig({ autoSync: { enabled: true, intervalSec: 5, push: false } }).autoSync + ).toEqual({ enabled: true, intervalSec: 30, push: false, pull: true }); + expect(normalizeSyncConfig({ autoSync: { enabled: 'yes' as never } }).autoSync.enabled).toBe( + false + ); + expect(normalizeSyncConfig({ autoSync: { intervalSec: 120.9 } }).autoSync.intervalSec).toBe( + 120 + ); + }); + it('defaults extra path lists when omitted', () => { const normalized = normalizeSyncConfig({ includeSecrets: true }); expect(normalized.extraSecretPaths).toEqual([]); diff --git a/src/sync/config.ts b/src/sync/config.ts index d22e1cc..1146d1d 100644 --- a/src/sync/config.ts +++ b/src/sync/config.ts @@ -26,6 +26,23 @@ export interface SecretsBackendConfig { export type SessionBackendType = 'git' | 'turso'; +export interface AutoSyncSettings { + enabled?: boolean; + intervalSec?: number; + push?: boolean; + pull?: boolean; +} + +export interface NormalizedAutoSyncSettings { + enabled: boolean; + intervalSec: number; + push: boolean; + pull: boolean; +} + +export const DEFAULT_AUTO_SYNC_INTERVAL_SEC = 300; +export const MIN_AUTO_SYNC_INTERVAL_SEC = 30; + export interface TursoSessionBackendSettings { database?: string; url?: string; @@ -61,6 +78,7 @@ export interface SyncConfig { includeModelFavorites?: boolean; includeOpencodeSkills?: boolean; includeAgentsDir?: boolean; + autoSync?: AutoSyncSettings; secretsBackend?: SecretsBackendConfig; extraSecretPaths?: string[]; extraConfigPaths?: string[]; @@ -75,6 +93,7 @@ export interface NormalizedSyncConfig extends SyncConfig { includeModelFavorites: boolean; includeOpencodeSkills: boolean; includeAgentsDir: boolean; + autoSync: NormalizedAutoSyncSettings; secretsBackend?: SecretsBackendConfig; extraSecretPaths: string[]; extraConfigPaths: string[]; @@ -168,6 +187,21 @@ export function normalizeSessionBackend( }; } +export function normalizeAutoSync(input: unknown): NormalizedAutoSyncSettings { + const settings = isPlainObject(input) ? input : {}; + const intervalRaw = settings.intervalSec; + const intervalSec = + typeof intervalRaw === 'number' && Number.isFinite(intervalRaw) && intervalRaw > 0 + ? Math.max(MIN_AUTO_SYNC_INTERVAL_SEC, Math.floor(intervalRaw)) + : DEFAULT_AUTO_SYNC_INTERVAL_SEC; + return { + enabled: settings.enabled === true, + intervalSec, + push: settings.push !== false, + pull: settings.pull !== false, + }; +} + export function isTursoSessionBackend(config: SyncConfig | NormalizedSyncConfig): boolean { if (!config.includeSessions) return false; const normalized = normalizeSessionBackend(config.sessionBackend); @@ -188,6 +222,7 @@ export function normalizeSyncConfig(config: SyncConfig): NormalizedSyncConfig { includeModelFavorites, includeOpencodeSkills, includeAgentsDir, + autoSync: normalizeAutoSync(config.autoSync), secretsBackend: normalizeSecretsBackend(config.secretsBackend), extraSecretPaths: Array.isArray(config.extraSecretPaths) ? config.extraSecretPaths : [], extraConfigPaths: Array.isArray(config.extraConfigPaths) ? config.extraConfigPaths : [], diff --git a/src/sync/repo.ts b/src/sync/repo.ts index 78600a9..7afc01d 100644 --- a/src/sync/repo.ts +++ b/src/sync/repo.ts @@ -402,7 +402,7 @@ export async function hasAnyRemoteBranches($: Shell, repoDir: string): Promise ({}) }, config: { get: async () => ({ data: {} }) }, @@ -72,7 +73,12 @@ function createClient(): PluginInput['client'] { prompt: async () => ({ data: null }), status: async () => ({ data: {} }), }, - tui: { showToast: async () => ({}) }, + tui: { + showToast: async (input: { body?: { message?: string } }) => { + toasts.push(input?.body?.message ?? ''); + return {}; + }, + }, } as unknown as PluginInput['client']; } @@ -362,3 +368,173 @@ describe('explicit Git remote service flow', () => { }); }, 30_000); }); + +describe('auto sync', () => { + const noopOptions = { + ensureAuthFilesNotTracked: async () => {}, + runSecretsPullIfConfigured: async () => {}, + }; + + async function enableAutoSync( + locations: ReturnType, + autoSync: { push?: boolean; pull?: boolean; intervalSec?: number } = {} + ): Promise { + const config = await loadSyncConfig(locations); + if (!config) throw new Error('Expected sync config.'); + await writeSyncConfig(locations, { ...config, autoSync: { enabled: true, ...autoSync } }); + } + + async function runCycle( + root: string, + machine: string, + toasts: string[] = [], + state: { lastConflictHead?: string } = {} + ): Promise { + useIsolatedHome(path.join(root, machine)); + const locations = resolveSyncLocations(); + const config = await loadSyncConfig(locations); + if (!config) throw new Error('Expected sync config.'); + const client = createClient(toasts); + return await runAutoSyncCycle( + { client, $: createTestShell() }, + locations, + config, + createLogger(client), + state, + noopOptions + ); + } + + it('pushes local edits, pulls remote edits, and never overwrites unpushed local edits', async () => { + await withIsolatedEnvironment(async (root) => { + const testShell = createTestShell(); + const remotePath = path.join(root, 'sync-remote.git'); + await testShell`git init --bare ${remotePath}`.quiet(); + const remoteHead = async (): Promise => + (await testShell`git --git-dir ${remotePath} rev-parse main`.text()).trim(); + + useIsolatedHome(path.join(root, 'machine-a')); + const aLocations = resolveSyncLocations(); + await fs.mkdir(aLocations.configRoot, { recursive: true }); + const aConfig = path.join(aLocations.configRoot, 'opencode.json'); + await fs.writeFile(aConfig, '{"theme":"base"}\n', 'utf8'); + const aService = createSyncService({ client: createClient(), $: testShell }); + await aService.init({ repo: remotePath, branch: 'main' }); + // opencode-synced.jsonc is itself synced, so the autoSync setting roams to other machines. + await enableAutoSync(aLocations); + expect(await runCycle(root, 'machine-a')).toBe('pushed'); + + useIsolatedHome(path.join(root, 'machine-b')); + const bLocations = resolveSyncLocations(); + const bConfig = path.join(bLocations.configRoot, 'opencode.json'); + await createSyncService({ client: createClient(), $: testShell }).link({ + repo: remotePath, + branch: 'main', + }); + expect((await loadSyncConfig(bLocations))?.autoSync.enabled).toBe(true); + + expect(await runCycle(root, 'machine-b')).toBe('idle'); + + await fs.writeFile(bConfig, '{"theme":"from-b"}\n', 'utf8'); + const headBeforePush = await remoteHead(); + expect(await runCycle(root, 'machine-b')).toBe('pushed'); + expect(await remoteHead()).not.toBe(headBeforePush); + + expect(await runCycle(root, 'machine-a')).toBe('pulled'); + await expect(fs.readFile(aConfig, 'utf8')).resolves.toContain('from-b'); + expect(await runCycle(root, 'machine-a')).toBe('idle'); + + await fs.writeFile(bConfig, '{"theme":"b-again"}\n', 'utf8'); + expect(await runCycle(root, 'machine-b')).toBe('pushed'); + const headWithBothSides = await remoteHead(); + + await fs.writeFile(aConfig, '{"theme":"a-local-edit"}\n', 'utf8'); + const toasts: string[] = []; + const state: { lastConflictHead?: string } = {}; + expect(await runCycle(root, 'machine-a', toasts, state)).toBe('conflict'); + expect(await runCycle(root, 'machine-a', toasts, state)).toBe('conflict'); + await expect(fs.readFile(aConfig, 'utf8')).resolves.toContain('a-local-edit'); + expect(await remoteHead()).toBe(headWithBothSides); + expect(toasts.filter((message) => message.includes('both changed'))).toHaveLength(1); + const cloneStatus = + await testShell`git -C ${aLocations.defaultRepoDir} status --porcelain`.text(); + expect(cloneStatus.trim()).toBe(''); + }); + }, 90_000); + + it('respects the pull and push switches', async () => { + await withIsolatedEnvironment(async (root) => { + const testShell = createTestShell(); + const remotePath = path.join(root, 'sync-remote.git'); + await testShell`git init --bare ${remotePath}`.quiet(); + + useIsolatedHome(path.join(root, 'machine-a')); + const aLocations = resolveSyncLocations(); + await fs.mkdir(aLocations.configRoot, { recursive: true }); + const aConfig = path.join(aLocations.configRoot, 'opencode.json'); + await fs.writeFile(aConfig, '{"theme":"base"}\n', 'utf8'); + await createSyncService({ client: createClient(), $: testShell }).init({ + repo: remotePath, + branch: 'main', + }); + + useIsolatedHome(path.join(root, 'machine-b')); + const bLocations = resolveSyncLocations(); + const bConfig = path.join(bLocations.configRoot, 'opencode.json'); + await createSyncService({ client: createClient(), $: testShell }).link({ + repo: remotePath, + branch: 'main', + }); + await enableAutoSync(bLocations, { push: false }); + await fs.writeFile(bConfig, '{"theme":"b-edit"}\n', 'utf8'); + expect(await runCycle(root, 'machine-b')).toBe('idle'); + const clonedStatus = + await testShell`git -C ${bLocations.defaultRepoDir} status --porcelain`.text(); + expect(clonedStatus.trim()).toBe(''); + + await fs.writeFile(bConfig, '{"theme":"base"}\n', 'utf8'); + useIsolatedHome(path.join(root, 'machine-a')); + await fs.writeFile(aConfig, '{"theme":"a-edit"}\n', 'utf8'); + await createSyncService({ client: createClient(), $: testShell }).push(); + + useIsolatedHome(path.join(root, 'machine-b')); + await enableAutoSync(bLocations, { pull: false }); + expect(await runCycle(root, 'machine-b')).toBe('skipped'); + await expect(fs.readFile(bConfig, 'utf8')).resolves.toContain('base'); + }); + }, 90_000); + + it('schedules a timer only when enabled and clears it on dispose', async () => { + await withIsolatedEnvironment(async (root) => { + const testShell = createTestShell(); + const remotePath = path.join(root, 'sync-remote.git'); + await testShell`git init --bare ${remotePath}`.quiet(); + + useIsolatedHome(path.join(root, 'machine-a')); + const locations = resolveSyncLocations(); + await fs.mkdir(locations.configRoot, { recursive: true }); + await fs.writeFile(path.join(locations.configRoot, 'opencode.json'), '{}\n', 'utf8'); + const service = createSyncService({ client: createClient(), $: testShell }); + await service.init({ repo: remotePath, branch: 'main' }); + + const setIntervalSpy = vi.spyOn(globalThis, 'setInterval'); + const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval'); + try { + await service.startupSync(); + expect(setIntervalSpy).not.toHaveBeenCalled(); + + await enableAutoSync(locations, { intervalSec: 45 }); + await service.startupSync(); + expect(setIntervalSpy).toHaveBeenCalledTimes(1); + expect(setIntervalSpy.mock.calls[0]?.[1]).toBe(45_000); + + service.dispose(); + expect(clearIntervalSpy).toHaveBeenCalled(); + } finally { + service.dispose(); + setIntervalSpy.mockRestore(); + clearIntervalSpy.mockRestore(); + } + }); + }, 60_000); +}); diff --git a/src/sync/service.ts b/src/sync/service.ts index ba27d7a..2e24f53 100644 --- a/src/sync/service.ts +++ b/src/sync/service.ts @@ -34,6 +34,7 @@ import { ensureRepoPrivate, fetchAndFastForward, findSyncRepo, + getAheadBehind, getAuthenticatedUser, getRepoStatus, hasAnyRemoteBranches, @@ -137,6 +138,9 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { process.env.OPENCODE_SYNC_E2E_DISABLE_AUTO_REPO_DISCOVERY === '1' || strictLinkRepo !== null; let tursoSyncTimer: ReturnType | null = null; let tursoSyncIntervalSec = 15; + let autoSyncTimer: ReturnType | null = null; + let autoSyncIntervalSec = 0; + const autoSyncState: AutoSyncState = {}; const activeSessionIds = new Set(); const pendingTursoSyncReasons = new Set(); let tursoIdleFlushTimer: ReturnType | null = null; @@ -307,6 +311,50 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { } }; + const stopAutoSyncLoop = (): void => { + if (!autoSyncTimer) return; + clearInterval(autoSyncTimer); + autoSyncTimer = null; + autoSyncIntervalSec = 0; + }; + + const runAutoSyncTick = async (): Promise => { + let latest: NormalizedSyncConfig | null = null; + try { + latest = await loadSyncConfig(locations); + } catch (error) { + log.warn('Auto sync could not load config', { error: formatError(error) }); + return; + } + if (!latest?.autoSync.enabled) { + stopAutoSyncLoop(); + return; + } + try { + assertValidSecretsBackend(latest); + await runAutoSyncCycle(ctx, locations, latest, log, autoSyncState, { + ensureAuthFilesNotTracked, + runSecretsPullIfConfigured, + }); + } catch (error) { + log.warn('Auto sync cycle failed', { error: formatError(error) }); + } + }; + + const ensureAutoSyncLoop = (config: NormalizedSyncConfig): void => { + if (!config.autoSync.enabled) { + stopAutoSyncLoop(); + return; + } + if (autoSyncTimer && autoSyncIntervalSec === config.autoSync.intervalSec) return; + stopAutoSyncLoop(); + autoSyncIntervalSec = config.autoSync.intervalSec; + autoSyncTimer = setInterval(() => { + void skipIfBusy(runAutoSyncTick); + }, autoSyncIntervalSec * 1000); + autoSyncTimer.unref?.(); + }; + const sleep = async (ms: number): Promise => await new Promise((resolve) => { setTimeout(resolve, ms); @@ -625,6 +673,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { } if (!config) { stopTursoSyncLoop(); + stopAutoSyncLoop(); await showToast( ctx.client, 'Configure opencode-synced with /sync-init or link to an existing repo with /sync-link', @@ -649,6 +698,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { runSecretsPullIfConfigured, }); ensureTursoSyncLoop(config); + ensureAutoSyncLoop(config); if (tursoWarning) { log.warn(tursoWarning); await showToast(ctx.client, tursoWarning, 'warning'); @@ -1415,6 +1465,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { }), dispose: () => { stopTursoSyncLoop(); + stopAutoSyncLoop(); }, }; } @@ -1444,6 +1495,114 @@ function toRepoRelativePath(repoRoot: string, absolutePath: string): string { return path.relative(repoRoot, absolutePath).split(path.sep).join('/'); } +export interface AutoSyncState { + /** Remote head that was last reported as conflicting, so the notice is shown once. */ + lastConflictHead?: string; +} + +export type AutoSyncResult = 'idle' | 'pulled' | 'pushed' | 'conflict' | 'skipped'; + +/** + * One periodic sync pass. Unlike the startup flow it never overwrites unpushed local edits: local + * config is staged first, and if the remote also changed the pass stops and asks for a manual + * `pull`/`push` instead. + */ +export async function runAutoSyncCycle( + ctx: SyncServiceContext, + locations: ReturnType, + config: NormalizedSyncConfig, + log: Logger, + state: AutoSyncState, + options: { + ensureAuthFilesNotTracked: (repoRoot: string, config: NormalizedSyncConfig) => Promise; + runSecretsPullIfConfigured: (config: NormalizedSyncConfig) => Promise; + } +): Promise { + const repoRoot = resolveRepoRoot(config, locations); + await ensureRepoCloned(ctx.$, config, repoRoot); + await ensureSensitiveSyncPolicy(ctx, locations, config); + await options.ensureAuthFilesNotTracked(repoRoot, config); + const branch = await resolveBranch(ctx, config, repoRoot); + + if (await hasLocalChanges(ctx.$, repoRoot)) { + log.warn('Auto sync skipped: the sync repo has uncommitted changes', { repoRoot }); + return 'skipped'; + } + + try { + await ctx.$`git -C ${repoRoot} fetch --prune`.quiet(); + } catch (error) { + log.debug('Auto sync skipped: fetch failed', { error: formatError(error) }); + return 'skipped'; + } + const remoteExists = await hasRemoteBranch(ctx.$, repoRoot, branch); + const { behind } = remoteExists + ? await getAheadBehind(ctx.$, repoRoot, `origin/${branch}`) + : { behind: 0 }; + if (behind > 0 && !config.autoSync.pull) return 'skipped'; + if (behind === 0 && !config.autoSync.push) return 'idle'; + + const overrides = await loadOverrides(locations); + const plan = buildSyncPlan(config, locations, repoRoot); + await syncLocalToRepo(plan, overrides, { + overridesPath: locations.overridesPath, + allowMcpSecrets: canCommitMcpSecrets(config), + }); + const localChanged = await hasLocalChanges(ctx.$, repoRoot); + + if (behind > 0) { + if (localChanged) { + await discardCloneChanges(ctx.$, repoRoot); + const remoteHead = await readRemoteHead(ctx.$, repoRoot, branch); + if (remoteHead !== state.lastConflictHead) { + state.lastConflictHead = remoteHead; + await showToast( + ctx.client, + 'Local and remote opencode config both changed. Auto sync paused: run pull or push manually.', + 'warning' + ); + } + return 'conflict'; + } + const update = await fetchAndFastForward(ctx.$, repoRoot, branch); + if (!update.updated) return 'idle'; + log.info('Auto sync pulled remote changes', { branch }); + await syncRepoToLocal(plan, overrides); + await options.runSecretsPullIfConfigured(config); + await updateState(locations, { + lastPull: new Date().toISOString(), + lastRemoteUpdate: new Date().toISOString(), + }); + await showToast(ctx.client, 'Config updated. Restart opencode to apply.', 'info'); + return 'pulled'; + } + + if (!localChanged) return 'idle'; + await assertNoOversizedUnpushedHistory(ctx.$, repoRoot, branch); + const message = await generateCommitMessage( + { client: ctx.client, $: ctx.$, ai: ctx.ai }, + repoRoot + ); + log.info('Auto sync pushing local changes', { message }); + await commitAll(ctx.$, repoRoot, message); + await pushBranch(ctx.$, repoRoot, branch); + await updateState(locations, { lastPush: new Date().toISOString() }); + return 'pushed'; +} + +async function discardCloneChanges($: Shell, repoRoot: string): Promise { + await $`git -C ${repoRoot} reset --hard HEAD`.quiet(); + await $`git -C ${repoRoot} clean -fd`.quiet(); +} + +async function readRemoteHead($: Shell, repoRoot: string, branch: string): Promise { + try { + return (await $`git -C ${repoRoot} rev-parse ${`origin/${branch}`}`.quiet().text()).trim(); + } catch { + return ''; + } +} + async function runStartup( ctx: SyncServiceContext, locations: ReturnType,