Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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": [],
}
Expand All @@ -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/`
Expand Down
18 changes: 18 additions & 0 deletions src/sync/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([]);
Expand Down
35 changes: 35 additions & 0 deletions src/sync/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -61,6 +78,7 @@ export interface SyncConfig {
includeModelFavorites?: boolean;
includeOpencodeSkills?: boolean;
includeAgentsDir?: boolean;
autoSync?: AutoSyncSettings;
secretsBackend?: SecretsBackendConfig;
extraSecretPaths?: string[];
extraConfigPaths?: string[];
Expand All @@ -75,6 +93,7 @@ export interface NormalizedSyncConfig extends SyncConfig {
includeModelFavorites: boolean;
includeOpencodeSkills: boolean;
includeAgentsDir: boolean;
autoSync: NormalizedAutoSyncSettings;
secretsBackend?: SecretsBackendConfig;
extraSecretPaths: string[];
extraConfigPaths: string[];
Expand Down Expand Up @@ -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);
Expand All @@ -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 : [],
Expand Down
2 changes: 1 addition & 1 deletion src/sync/repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ export async function hasAnyRemoteBranches($: Shell, repoDir: string): Promise<b
}
}

async function getAheadBehind(
export async function getAheadBehind(
$: Shell,
repoDir: string,
remoteRef: string
Expand Down
184 changes: 180 additions & 4 deletions src/sync/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import path from 'node:path';
import { promisify } from 'node:util';

import type { PluginInput } from '@opencode-ai/plugin';
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { loadState, loadSyncConfig, writeState, writeSyncConfig } from './config.js';
import { resolveSyncLocations } from './paths.js';
import { createSyncService } from './service.js';
import { createSyncService, runAutoSyncCycle } from './service.js';
import { createLogger } from './utils.js';

const GIT_CONTEXT_KEYS = [
'GIT_DIR',
Expand Down Expand Up @@ -62,7 +63,7 @@ function shellQuote(value: unknown): string {
return `'${String(value).replaceAll("'", `'\\''`)}'`;
}

function createClient(): PluginInput['client'] {
function createClient(toasts: string[] = []): PluginInput['client'] {
return {
app: { log: async () => ({}) },
config: { get: async () => ({ data: {} }) },
Expand All @@ -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'];
}

Expand Down Expand Up @@ -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<typeof resolveSyncLocations>,
autoSync: { push?: boolean; pull?: boolean; intervalSec?: number } = {}
): Promise<void> {
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<string> {
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<string> =>
(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);
});
Loading
Loading