diff --git a/README.md b/README.md index d371aee..fc9939e 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ Create `~/.config/opencode/opencode-synced.jsonc`: "includeModelFavorites": true, "includeOpencodeSkills": true, "includeAgentsDir": true, + "openChamber": { "enabled": false }, "extraSecretPaths": [], "extraConfigPaths": [], } @@ -155,6 +156,43 @@ Create `~/.config/opencode/opencode-synced.jsonc`: Review it before syncing, keep the sync repository private when needed, or set `"includeAgentsDir": false` to opt out. +### OpenChamber preferences + +If you use [OpenChamber](https://github.com/openchamber/openchamber) as the opencode UI, its settings +can be synced too. This is off by default: + +```jsonc +{ + "openChamber": { + "enabled": true, + // optional: replace the default field list, "*" at the end is a prefix wildcard + "include": ["darkThemeId", "lightThemeId", "notifyOn*", "favoriteModels", "fontSize"], + // optional: never sync these + "exclude": ["customProviderIcons"], + // optional: defaults to /openchamber/preferences.json + "path": "~/.config/openchamber/preferences.json" + } +} +``` + +OpenChamber stores `preferences.json` as `{ "fields": { "": { "value": ..., "updatedAt": ... } } }`. +Fields are merged one by one and the **newest `updatedAt` wins**, in both directions, so two machines never +overwrite each other's unrelated settings. + +- Default fields: themes, notification settings, favourite and hidden models, favourite agents, + collapsed model providers, custom provider icons, and a few behaviour toggles. Selected and recent + models, projects and everything else stay local unless you add them to `include`. +- Field names that look like credentials (`token`, `secret`, `password`, `credential`, `private`, + `api key`, `vapid`, `identity`) are never synced, even if listed in `include`. +- Per-device `surfaces` data (for example a theme imported on one machine) is never written to the repo + and is preserved locally on pull. +- The repo copy lives at `config/openchamber/preferences.json`. The local file is only changed when a + repo field is newer; it is written atomically, keeps its permissions, and a one-time + `preferences.json.pre-opencode-synced` backup is kept. A missing local file is never created, a + malformed file is skipped, and a `version` mismatch skips the merge. +- Other OpenChamber files (relay identity, GitHub auth, git identities, projects, chat history, + search index) are never read. + Disable default directory sync by setting: - `"includeOpencodeSkills": false` to skip `~/.config/opencode/skills/` - `"includeAgentsDir": false` to skip `~/.agents/` diff --git a/src/sync/apply.test.ts b/src/sync/apply.test.ts index 1d881c1..441c166 100644 --- a/src/sync/apply.test.ts +++ b/src/sync/apply.test.ts @@ -902,3 +902,59 @@ describe('MCP secret scrub round trip', () => { }); }); }); + +describe('OpenChamber preferences in the sync flow', () => { + it('pushes allowlisted fields to the repo and pulls newer ones back', async () => { + await withTempDir(async (root) => { + const repoRoot = path.join(root, 'repo'); + const homeDir = path.join(root, 'home'); + const plan = createPlan(repoRoot, homeDir, []); + const localPath = path.join(homeDir, '.config', 'openchamber', 'preferences.json'); + const repoPath = path.join(repoRoot, 'config', 'openchamber', 'preferences.json'); + const openChamber = { localPath, repoPath, include: [], exclude: [] }; + await fs.mkdir(path.dirname(localPath), { recursive: true }); + await fs.writeFile( + localPath, + JSON.stringify({ + version: 1, + fields: { + darkThemeId: { value: 'dark-a', updatedAt: 1 }, + lastSelectedModel: { value: 'private/model', updatedAt: 1 }, + }, + }), + 'utf8' + ); + + await syncLocalToRepo(plan, null, { openChamber }); + const pushed = JSON.parse(await fs.readFile(repoPath, 'utf8')); + expect(Object.keys(pushed.fields)).toEqual(['darkThemeId']); + + pushed.fields.darkThemeId = { value: 'dark-b', updatedAt: 5 }; + await fs.writeFile(repoPath, JSON.stringify(pushed), 'utf8'); + await syncRepoToLocal(plan, null, { openChamber }); + const pulled = JSON.parse(await fs.readFile(localPath, 'utf8')); + expect(pulled.fields.darkThemeId.value).toBe('dark-b'); + expect(pulled.fields.lastSelectedModel.value).toBe('private/model'); + }); + }); + + it('leaves OpenChamber alone when no plan is passed', async () => { + await withTempDir(async (root) => { + const repoRoot = path.join(root, 'repo'); + const homeDir = path.join(root, 'home'); + const localPath = path.join(homeDir, '.config', 'openchamber', 'preferences.json'); + await fs.mkdir(repoRoot, { recursive: true }); + await fs.mkdir(path.dirname(localPath), { recursive: true }); + await fs.writeFile( + localPath, + '{"version":1,"fields":{"darkThemeId":{"value":"x","updatedAt":1}}}' + ); + + await syncLocalToRepo(createPlan(repoRoot, homeDir, []), null); + + await expect( + fs.access(path.join(repoRoot, 'config', 'openchamber', 'preferences.json')) + ).rejects.toThrow(); + }); + }); +}); diff --git a/src/sync/apply.ts b/src/sync/apply.ts index 0e0e9f7..e7a032b 100644 --- a/src/sync/apply.ts +++ b/src/sync/apply.ts @@ -22,6 +22,11 @@ import { mergeOverrides, stripOverrideKeys, } from './mcp-secrets.js'; +import { + type OpenChamberPlan, + pullOpenChamberPreferences, + pushOpenChamberPreferences, +} from './openchamber.js'; import type { ExtraPathPlan, SyncItem, SyncPlan } from './paths.js'; import { fromPortablePath, normalizePath, toPortablePath } from './paths.js'; @@ -51,7 +56,7 @@ interface ExtraPathManifest { export async function syncRepoToLocal( plan: SyncPlan, overrides: Record | null, - options: { chunkOptions?: ChunkOptions } = {} + options: { chunkOptions?: ChunkOptions; openChamber?: OpenChamberPlan | null } = {} ): Promise { for (const item of plan.items) { if (item.chunkLargeFiles) { @@ -64,6 +69,10 @@ export async function syncRepoToLocal( await applyExtraPaths(plan, plan.extraConfigs); await applyExtraPaths(plan, plan.extraSecrets); + if (options.openChamber) { + await pullOpenChamberPreferences(options.openChamber); + } + if (overrides && Object.keys(overrides).length > 0) { await applyOverridesToLocalConfig(plan, overrides); } @@ -93,6 +102,7 @@ export async function syncLocalToRepo( overridesPath?: string; allowMcpSecrets?: boolean; chunkOptions?: ChunkOptions; + openChamber?: OpenChamberPlan | null; } = {} ): Promise { const configItems = plan.items.filter((item) => item.isConfigFile); @@ -148,6 +158,9 @@ export async function syncLocalToRepo( await writeExtraPathManifest(plan, plan.extraConfigs); await writeExtraPathManifest(plan, plan.extraSecrets); + if (options.openChamber) { + await pushOpenChamberPreferences(options.openChamber); + } await cleanupUnreferencedChunkStores(plan.repoRoot); } diff --git a/src/sync/config.ts b/src/sync/config.ts index d22e1cc..0b7447d 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 OpenChamberSettings { + enabled?: boolean; + /** Override for the local preferences file. Defaults to `/openchamber/preferences.json`. */ + path?: string; + /** Field names (a trailing `*` is a prefix wildcard) to sync instead of the default list. */ + include?: string[]; + /** Field names (a trailing `*` is a prefix wildcard) that are never synced. */ + exclude?: string[]; +} + +export interface NormalizedOpenChamberSettings { + enabled: boolean; + path?: string; + include: string[]; + exclude: string[]; +} + export interface TursoSessionBackendSettings { database?: string; url?: string; @@ -61,6 +78,7 @@ export interface SyncConfig { includeModelFavorites?: boolean; includeOpencodeSkills?: boolean; includeAgentsDir?: boolean; + openChamber?: OpenChamberSettings; secretsBackend?: SecretsBackendConfig; extraSecretPaths?: string[]; extraConfigPaths?: string[]; @@ -75,6 +93,7 @@ export interface NormalizedSyncConfig extends SyncConfig { includeModelFavorites: boolean; includeOpencodeSkills: boolean; includeAgentsDir: boolean; + openChamber: NormalizedOpenChamberSettings; secretsBackend?: SecretsBackendConfig; extraSecretPaths: string[]; extraConfigPaths: string[]; @@ -168,6 +187,22 @@ export function normalizeSessionBackend( }; } +function normalizeStringList(input: unknown): string[] { + if (!Array.isArray(input)) return []; + return input.filter((item): item is string => typeof item === 'string' && item.trim() !== ''); +} + +export function normalizeOpenChamber(input: unknown): NormalizedOpenChamberSettings { + const settings = isPlainObject(input) ? input : {}; + const customPath = typeof settings.path === 'string' ? settings.path.trim() : ''; + return { + enabled: settings.enabled === true, + path: customPath || undefined, + include: normalizeStringList(settings.include), + exclude: normalizeStringList(settings.exclude), + }; +} + export function isTursoSessionBackend(config: SyncConfig | NormalizedSyncConfig): boolean { if (!config.includeSessions) return false; const normalized = normalizeSessionBackend(config.sessionBackend); @@ -188,6 +223,7 @@ export function normalizeSyncConfig(config: SyncConfig): NormalizedSyncConfig { includeModelFavorites, includeOpencodeSkills, includeAgentsDir, + openChamber: normalizeOpenChamber(config.openChamber), secretsBackend: normalizeSecretsBackend(config.secretsBackend), extraSecretPaths: Array.isArray(config.extraSecretPaths) ? config.extraSecretPaths : [], extraConfigPaths: Array.isArray(config.extraConfigPaths) ? config.extraConfigPaths : [], diff --git a/src/sync/openchamber.test.ts b/src/sync/openchamber.test.ts new file mode 100644 index 0000000..6868cf9 --- /dev/null +++ b/src/sync/openchamber.test.ts @@ -0,0 +1,258 @@ +import { promises as fs } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { normalizeOpenChamber, normalizeSyncConfig } from './config.js'; +import { + isSyncableField, + type OpenChamberPlan, + pullOpenChamberPreferences, + pushOpenChamberPreferences, +} from './openchamber.js'; +import { resolveOpenChamberPlan, resolveSyncLocations } from './paths.js'; + +async function withTempDir(run: (root: string) => Promise): Promise { + const root = await fs.mkdtemp(path.join(tmpdir(), 'opencode-sync-openchamber-')); + try { + await run(root); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +} + +function entry(value: unknown, updatedAt: number, extra: Record = {}) { + return { value, updatedAt, ...extra }; +} + +async function writeJson(filePath: string, data: unknown, mode = 0o600): Promise { + await fs.mkdir(path.dirname(filePath), { recursive: true }); + await fs.writeFile(filePath, `${JSON.stringify(data, null, 2)}\n`, { mode }); +} + +interface StoredEntry { + value?: unknown; + updatedAt?: number; + surfaces?: unknown; +} + +async function readJson( + filePath: string +): Promise<{ version?: number; fields: Record }> { + return JSON.parse(await fs.readFile(filePath, 'utf8')); +} + +function planFor(root: string, overrides: Partial = {}): OpenChamberPlan { + return { + localPath: path.join(root, 'local', 'preferences.json'), + repoPath: path.join(root, 'repo', 'config', 'openchamber', 'preferences.json'), + include: [], + exclude: [], + ...overrides, + }; +} + +describe('isSyncableField', () => { + it('allows the default list and nothing else', () => { + expect(isSyncableField('darkThemeId', [], [])).toBe(true); + expect(isSyncableField('lastSelectedModel', [], [])).toBe(false); + expect(isSyncableField('recentModels', [], [])).toBe(false); + }); + + it('supports include lists with prefix wildcards and exclude lists', () => { + expect(isSyncableField('notifyOnError', ['notifyOn*'], [])).toBe(true); + expect(isSyncableField('darkThemeId', ['notifyOn*'], [])).toBe(false); + expect(isSyncableField('notifyOnError', ['notifyOn*'], ['notifyOnError'])).toBe(false); + expect(isSyncableField('favoriteModels', [], ['favorite*'])).toBe(false); + }); + + it('refuses credential-like names even when explicitly included', () => { + for (const name of ['githubToken', 'apiKey', 'vapidKeys', 'sessionSecret', 'relayIdentity']) { + expect(isSyncableField(name, [name, '*'], [])).toBe(false); + } + }); +}); + +describe('normalizeOpenChamber', () => { + it('is disabled by default and cleans invalid values', () => { + expect(normalizeSyncConfig({}).openChamber).toEqual({ + enabled: false, + path: undefined, + include: [], + exclude: [], + }); + expect( + normalizeOpenChamber({ + enabled: true, + path: ' ~/x.json ', + include: ['a', 1, ''], + exclude: 'b', + }) + ).toEqual({ enabled: true, path: '~/x.json', include: ['a'], exclude: [] }); + expect(normalizeOpenChamber({ enabled: 'yes' }).enabled).toBe(false); + }); +}); + +describe('pushOpenChamberPreferences', () => { + it('copies only allowlisted fields, drops surfaces, and sorts the output', async () => { + await withTempDir(async (root) => { + const plan = planFor(root); + await writeJson(plan.localPath, { + version: 1, + fields: { + lastSelectedModel: entry('provider/model', 5), + darkThemeId: entry('dark', 10, { + surfaces: { desktop: { value: 'imported-local-theme', updatedAt: 9 } }, + }), + apiToken: entry('secret', 10), + favoriteModels: entry([{ providerID: 'p', modelID: 'm' }], 7), + }, + }); + + expect(await pushOpenChamberPreferences(plan)).toBe('changed'); + + const repo = await readJson(plan.repoPath); + expect(Object.keys(repo.fields)).toEqual(['darkThemeId', 'favoriteModels']); + expect(repo.fields.darkThemeId).toEqual({ value: 'dark', updatedAt: 10 }); + expect(JSON.stringify(repo)).not.toContain('secret'); + expect(JSON.stringify(repo)).not.toContain('imported-local-theme'); + }); + }); + + it('keeps the newer value per field and leaves the file alone when nothing is newer', async () => { + await withTempDir(async (root) => { + const plan = planFor(root); + await writeJson(plan.repoPath, { + version: 1, + fields: { darkThemeId: entry('repo-newer', 20), lightThemeId: entry('repo-older', 1) }, + }); + await writeJson(plan.localPath, { + version: 1, + fields: { darkThemeId: entry('local-older', 10), lightThemeId: entry('local-newer', 5) }, + }); + + expect(await pushOpenChamberPreferences(plan)).toBe('changed'); + const repo = await readJson(plan.repoPath); + expect(repo.fields.darkThemeId.value).toBe('repo-newer'); + expect(repo.fields.lightThemeId.value).toBe('local-newer'); + + const before = await fs.stat(plan.repoPath); + expect(await pushOpenChamberPreferences(plan)).toBe('unchanged'); + expect((await fs.stat(plan.repoPath)).mtimeMs).toBe(before.mtimeMs); + }); + }); + + it('skips a missing, malformed or version-mismatched file without throwing', async () => { + await withTempDir(async (root) => { + const plan = planFor(root); + expect(await pushOpenChamberPreferences(plan)).toBe('missing-local'); + + await fs.mkdir(path.dirname(plan.localPath), { recursive: true }); + await fs.writeFile(plan.localPath, '{not json', 'utf8'); + expect(await pushOpenChamberPreferences(plan)).toBe('invalid'); + + await writeJson(plan.localPath, { version: 2, fields: { darkThemeId: entry('x', 1) } }); + await writeJson(plan.repoPath, { version: 1, fields: {} }); + expect(await pushOpenChamberPreferences(plan)).toBe('version-mismatch'); + }); + }); +}); + +describe('pullOpenChamberPreferences', () => { + it('applies newer repo fields, keeps newer local fields and unrelated local fields', async () => { + await withTempDir(async (root) => { + const plan = planFor(root); + await writeJson(plan.repoPath, { + version: 1, + fields: { + darkThemeId: entry('repo-theme', 20), + favoriteModels: entry(['repo'], 3), + apiToken: entry('leak', 99), + }, + }); + await writeJson(plan.localPath, { + version: 1, + fields: { + darkThemeId: entry('local-theme', 10, { + surfaces: { desktop: { value: 'local-surface', updatedAt: 9 } }, + }), + favoriteModels: entry(['local'], 8), + lastSelectedModel: entry('local/model', 4), + }, + }); + + expect(await pullOpenChamberPreferences(plan)).toBe('changed'); + + const local = await readJson(plan.localPath); + expect(local.fields.darkThemeId.value).toBe('repo-theme'); + expect(local.fields.darkThemeId.surfaces).toEqual({ + desktop: { value: 'local-surface', updatedAt: 9 }, + }); + expect(local.fields.favoriteModels.value).toEqual(['local']); + expect(local.fields.lastSelectedModel.value).toBe('local/model'); + expect(local.fields.apiToken).toBeUndefined(); + }); + }); + + it('backs the file up once, keeps its mode, and never creates a missing local file', async () => { + await withTempDir(async (root) => { + const plan = planFor(root); + await writeJson(plan.repoPath, { version: 1, fields: { darkThemeId: entry('a', 20) } }); + expect(await pullOpenChamberPreferences(plan)).toBe('missing-local'); + await expect(fs.access(plan.localPath)).rejects.toThrow(); + + await writeJson( + plan.localPath, + { version: 1, fields: { darkThemeId: entry('orig', 1) } }, + 0o600 + ); + expect(await pullOpenChamberPreferences(plan)).toBe('changed'); + const backupPath = `${plan.localPath}.pre-opencode-synced`; + expect((await readJson(backupPath)).fields.darkThemeId.value).toBe('orig'); + expect((await fs.stat(plan.localPath)).mode & 0o777).toBe(0o600); + + await writeJson(plan.repoPath, { version: 1, fields: { darkThemeId: entry('b', 30) } }); + expect(await pullOpenChamberPreferences(plan)).toBe('changed'); + expect((await readJson(backupPath)).fields.darkThemeId.value).toBe('orig'); + expect(await pullOpenChamberPreferences(plan)).toBe('unchanged'); + }); + }); + + it('does not touch a malformed local file', async () => { + await withTempDir(async (root) => { + const plan = planFor(root); + await writeJson(plan.repoPath, { version: 1, fields: { darkThemeId: entry('a', 20) } }); + await fs.mkdir(path.dirname(plan.localPath), { recursive: true }); + await fs.writeFile(plan.localPath, '{broken', 'utf8'); + + expect(await pullOpenChamberPreferences(plan)).toBe('invalid'); + expect(await fs.readFile(plan.localPath, 'utf8')).toBe('{broken'); + }); + }); +}); + +describe('resolveOpenChamberPlan', () => { + it('returns null when disabled and resolves default and custom paths when enabled', () => { + const locations = resolveSyncLocations(); + const repoRoot = path.join(tmpdir(), 'repo'); + expect(resolveOpenChamberPlan(normalizeSyncConfig({}), locations, repoRoot)).toBeNull(); + + const enabled = resolveOpenChamberPlan( + normalizeSyncConfig({ openChamber: { enabled: true } }), + locations, + repoRoot + ); + expect(enabled?.localPath).toBe( + path.join(locations.xdg.configDir, 'openchamber', 'preferences.json') + ); + expect(enabled?.repoPath).toBe( + path.join(repoRoot, 'config', 'openchamber', 'preferences.json') + ); + + const custom = resolveOpenChamberPlan( + normalizeSyncConfig({ openChamber: { enabled: true, path: '~/oc/prefs.json' } }), + locations, + repoRoot + ); + expect(custom?.localPath).toBe(path.join(locations.xdg.homeDir, 'oc', 'prefs.json')); + }); +}); diff --git a/src/sync/openchamber.ts b/src/sync/openchamber.ts new file mode 100644 index 0000000..fd7b48c --- /dev/null +++ b/src/sync/openchamber.ts @@ -0,0 +1,224 @@ +import { promises as fs } from 'node:fs'; +import path from 'node:path'; + +import { isPlainObject, pathExists } from './config.js'; + +/** + * Syncs a safe subset of OpenChamber's `preferences.json` between machines. + * + * The file looks like `{ "version": 1, "fields": { "": { "value": ..., "updatedAt": 123 } } }`. + * Fields are merged one by one and the newest `updatedAt` wins, so two machines never overwrite each + * other's unrelated settings. Only allowlisted fields are copied, the per-device `surfaces` data is + * never written to the repo, and field names that look like credentials are always refused. + */ + +export interface OpenChamberPlan { + localPath: string; + repoPath: string; + include: string[]; + exclude: string[]; +} + +export type OpenChamberSyncResult = + | 'changed' + | 'unchanged' + | 'missing-local' + | 'missing-repo' + | 'invalid' + | 'version-mismatch'; + +interface PreferenceEntry { + value?: unknown; + updatedAt?: number; + surfaces?: unknown; + [key: string]: unknown; +} + +interface PreferencesDocument { + version?: number; + fields: Record; + [key: string]: unknown; +} + +/** Conservative defaults: appearance, notifications, favourites and behaviour toggles. */ +export const DEFAULT_OPENCHAMBER_FIELDS: readonly string[] = [ + 'lightThemeId', + 'darkThemeId', + 'themeVariant', + 'notifyOnSubtasks', + 'notifyOnCompletion', + 'notifyOnError', + 'notifyOnQuestion', + 'notificationMode', + 'notificationTemplates', + 'favoriteModels', + 'favoriteAgents', + 'hiddenModels', + 'collapsedModelProviders', + 'customProviderIcons', + 'workStatusPanelEnabled', + 'gitmojiEnabled', + 'largeTextPasteBehavior', +]; + +const SENSITIVE_FIELD = /token|secret|password|credential|private|api[-_]?key|vapid|identity/iu; + +function matchesPattern(name: string, pattern: string): boolean { + if (pattern.endsWith('*')) return name.startsWith(pattern.slice(0, -1)); + return name === pattern; +} + +export function isSyncableField(name: string, include: string[], exclude: string[]): boolean { + if (SENSITIVE_FIELD.test(name)) return false; + if (exclude.some((pattern) => matchesPattern(name, pattern))) return false; + const allowed = include.length > 0 ? include : DEFAULT_OPENCHAMBER_FIELDS; + return allowed.some((pattern) => matchesPattern(name, pattern)); +} + +function timestamp(entry: PreferenceEntry | undefined): number { + const value = entry?.updatedAt; + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} + +function isEntry(value: unknown): value is PreferenceEntry { + return isPlainObject(value); +} + +async function readPreferences( + filePath: string +): Promise { + if (!(await pathExists(filePath))) return 'missing'; + try { + const parsed: unknown = JSON.parse(await fs.readFile(filePath, 'utf8')); + if (!isPlainObject(parsed) || !isPlainObject(parsed.fields)) return 'invalid'; + const fields: Record = {}; + for (const [name, entry] of Object.entries(parsed.fields)) { + if (!isEntry(entry)) continue; + Object.defineProperty(fields, name, { + value: entry, + enumerable: true, + writable: true, + configurable: true, + }); + } + return { ...parsed, fields } as PreferencesDocument; + } catch { + return 'invalid'; + } +} + +function serialize(document: PreferencesDocument): string { + const sorted: Record = {}; + for (const name of Object.keys(document.fields).sort()) { + Object.defineProperty(sorted, name, { + value: document.fields[name], + enumerable: true, + writable: true, + configurable: true, + }); + } + return `${JSON.stringify({ ...document, fields: sorted }, null, 2)}\n`; +} + +async function writeAtomically(filePath: string, content: string, mode: number): Promise { + await fs.mkdir(path.dirname(filePath), { recursive: true }); + const temporary = `${filePath}.${process.pid}.tmp`; + try { + await fs.writeFile(temporary, content, { encoding: 'utf8', mode }); + await fs.chmod(temporary, mode); + await fs.rename(temporary, filePath); + } catch (error) { + await fs.rm(temporary, { force: true }); + throw error; + } +} + +function withoutSurfaces(entry: PreferenceEntry): PreferenceEntry { + const { surfaces: _surfaces, ...rest } = entry; + return rest; +} + +/** Copies newer allowlisted fields from the local preferences file into the sync repo. */ +export async function pushOpenChamberPreferences( + plan: OpenChamberPlan +): Promise { + const local = await readPreferences(plan.localPath); + if (local === 'missing') return 'missing-local'; + if (local === 'invalid') return 'invalid'; + + const existing = await readPreferences(plan.repoPath); + if (existing === 'invalid') return 'invalid'; + const repo: PreferencesDocument = + existing === 'missing' ? { version: local.version ?? 1, fields: {} } : existing; + if ( + typeof repo.version === 'number' && + typeof local.version === 'number' && + repo.version !== local.version + ) { + return 'version-mismatch'; + } + + let changed = false; + for (const [name, entry] of Object.entries(local.fields)) { + if (!isSyncableField(name, plan.include, plan.exclude)) continue; + const current = repo.fields[name]; + if (current && timestamp(entry) <= timestamp(current)) continue; + Object.defineProperty(repo.fields, name, { + value: withoutSurfaces(entry), + enumerable: true, + writable: true, + configurable: true, + }); + changed = true; + } + if (!changed) return 'unchanged'; + + await writeAtomically(plan.repoPath, serialize(repo), 0o644); + return 'changed'; +} + +/** Applies newer allowlisted fields from the sync repo to the local preferences file. */ +export async function pullOpenChamberPreferences( + plan: OpenChamberPlan +): Promise { + const repo = await readPreferences(plan.repoPath); + if (repo === 'missing') return 'missing-repo'; + if (repo === 'invalid') return 'invalid'; + const local = await readPreferences(plan.localPath); + if (local === 'missing') return 'missing-local'; + if (local === 'invalid') return 'invalid'; + if ( + typeof repo.version === 'number' && + typeof local.version === 'number' && + repo.version !== local.version + ) { + return 'version-mismatch'; + } + + let changed = false; + for (const [name, entry] of Object.entries(repo.fields)) { + if (!isSyncableField(name, plan.include, plan.exclude)) continue; + const current = local.fields[name]; + if (current && timestamp(entry) <= timestamp(current)) continue; + const merged: PreferenceEntry = { ...withoutSurfaces(entry) }; + if (current?.surfaces !== undefined) { + merged.surfaces = current.surfaces; + } + Object.defineProperty(local.fields, name, { + value: merged, + enumerable: true, + writable: true, + configurable: true, + }); + changed = true; + } + if (!changed) return 'unchanged'; + + const stat = await fs.stat(plan.localPath); + const backupPath = `${plan.localPath}.pre-opencode-synced`; + if (!(await pathExists(backupPath))) { + await fs.copyFile(plan.localPath, backupPath); + } + await writeAtomically(plan.localPath, serialize(local), stat.mode & 0o777); + return 'changed'; +} diff --git a/src/sync/paths.ts b/src/sync/paths.ts index a35f487..acdf6ba 100644 --- a/src/sync/paths.ts +++ b/src/sync/paths.ts @@ -2,6 +2,7 @@ import crypto from 'node:crypto'; import path from 'node:path'; import type { NormalizedSyncConfig, SyncConfig } from './config.js'; import { hasSecretsBackend, isTursoSessionBackend } from './config.js'; +import type { OpenChamberPlan } from './openchamber.js'; export interface XdgPaths { homeDir: string; @@ -206,6 +207,25 @@ export function resolveRepoRoot( return locations.defaultRepoDir; } +export function resolveOpenChamberPlan( + config: NormalizedSyncConfig, + locations: SyncLocations, + repoRoot: string, + platform: NodeJS.Platform = process.platform +): OpenChamberPlan | null { + if (!config.openChamber.enabled) return null; + const pathApi = pathApiFor(platform); + const localPath = config.openChamber.path + ? pathApi.resolve(expandHome(config.openChamber.path, locations.xdg.homeDir, platform)) + : pathApi.join(locations.xdg.configDir, 'openchamber', 'preferences.json'); + return { + localPath, + repoPath: pathApi.join(repoRoot, 'config', 'openchamber', 'preferences.json'), + include: config.openChamber.include, + exclude: config.openChamber.exclude, + }; +} + export function buildSyncPlan( config: NormalizedSyncConfig, locations: SyncLocations, diff --git a/src/sync/service.ts b/src/sync/service.ts index ba27d7a..9aa1041 100644 --- a/src/sync/service.ts +++ b/src/sync/service.ts @@ -27,7 +27,12 @@ import { import { SyncCommandError, SyncConfigMissingError } from './errors.js'; import type { SyncLockInfo } from './lock.js'; import { withSyncLock } from './lock.js'; -import { buildSyncPlan, resolveRepoRoot, resolveSyncLocations } from './paths.js'; +import { + buildSyncPlan, + resolveOpenChamberPlan, + resolveRepoRoot, + resolveSyncLocations, +} from './paths.js'; import { commitAll, ensureRepoCloned, @@ -737,6 +742,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { `Model favorites: ${includeModelFavorites}`, `Skills: ${includeOpencodeSkills}`, `Home .agents: ${includeAgentsDir}`, + `OpenChamber preferences: ${config.openChamber.enabled ? 'enabled' : 'disabled'}`, `Last pull: ${lastPull}`, `Last push: ${lastPush}`, `Working tree: ${changesLabel}`, @@ -809,6 +815,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { await syncLocalToRepo(plan, overrides, { overridesPath: locations.overridesPath, allowMcpSecrets: canCommitMcpSecrets(config), + openChamber: resolveOpenChamberPlan(config, locations, repoRoot), }); await assertNoOversizedUnpushedHistory(ctx.$, repoRoot, branch); @@ -923,7 +930,9 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { const overrides = await loadOverrides(locations); const plan = buildSyncPlan(config, locations, repoRoot); - await syncRepoToLocal(plan, overrides); + await syncRepoToLocal(plan, overrides, { + openChamber: resolveOpenChamberPlan(config, locations, repoRoot), + }); await updateState(locations, { lastPull: new Date().toISOString(), @@ -1020,7 +1029,9 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { const overrides = await loadOverrides(locations); const plan = buildSyncPlan(config, locations, repoRoot); - await syncRepoToLocal(plan, overrides); + await syncRepoToLocal(plan, overrides, { + openChamber: resolveOpenChamberPlan(config, locations, repoRoot), + }); await runSecretsPullIfConfigured(config); await updateState(locations, { @@ -1061,6 +1072,7 @@ export function createSyncService(ctx: SyncServiceContext): SyncService { await syncLocalToRepo(plan, overrides, { overridesPath: locations.overridesPath, allowMcpSecrets: canCommitMcpSecrets(config), + openChamber: resolveOpenChamberPlan(config, locations, repoRoot), }); await assertNoOversizedUnpushedHistory(ctx.$, repoRoot, branch); @@ -1479,7 +1491,9 @@ async function runStartup( log.info('Pulled remote changes', { branch }); const overrides = await loadOverrides(locations); const plan = buildSyncPlan(config, locations, repoRoot); - await syncRepoToLocal(plan, overrides); + await syncRepoToLocal(plan, overrides, { + openChamber: resolveOpenChamberPlan(config, locations, repoRoot), + }); await options.runSecretsPullIfConfigured(config); await updateState(locations, { lastPull: new Date().toISOString(), @@ -1494,6 +1508,7 @@ async function runStartup( await syncLocalToRepo(plan, overrides, { overridesPath: locations.overridesPath, allowMcpSecrets: canCommitMcpSecrets(config), + openChamber: resolveOpenChamberPlan(config, locations, repoRoot), }); await assertNoOversizedUnpushedHistory(ctx.$, repoRoot, branch); const changes = await hasLocalChanges(ctx.$, repoRoot);