Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(config): configurable hive/memory home folder with safe move (#8)

Chaitanya Giri4bc038fc465c
diff --git a/src/main/index.ts b/src/main/index.ts
index 54a0056f..08ca0486 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,6 +1,6 @@
import { app, BrowserWindow, clipboard, dialog, ipcMain, shell } from 'electron';
import { spawn } from 'node:child_process';
-import { rmSync, existsSync, readFileSync, readdirSync } from 'node:fs';
+import { rmSync, existsSync, readFileSync, readdirSync, cpSync } from 'node:fs';
import { join, resolve, sep } from 'node:path';
import { PtyManager, type SpawnOptions } from './pty';
import {
@@ -414,6 +414,71 @@ ipcMain.handle('config:ensureHome', (_evt, path: unknown) => {
return ensureHarnessHome(path);
});
+// Change the harnessHome folder. Because every derived path (hive root, palace,
+// sock, agent dirs) resolves lazily through getHome(), the only real work is
+// optionally MOVING the existing hive + palace and relaunching so every service
+// re-binds against the new root. mode: 'move' copies the data (old kept as a
+// safety net), 'fresh' just re-points and bootstraps an empty home.
+ipcMain.handle('config:changeHome', async (_evt, payload: unknown) => {
+ const p = (payload ?? {}) as { newHome?: unknown; mode?: unknown };
+ if (typeof p.newHome !== 'string' || !p.newHome) return { ok: false, error: 'invalid newHome' };
+ const mode: 'move' | 'fresh' = p.mode === 'fresh' ? 'fresh' : 'move';
+ const newHome = resolve(p.newHome);
+ const oldRaw = readConfig().harnessHome;
+ const oldHome = oldRaw ? resolve(oldRaw) : null;
+
+ // Guard against same-folder / nested-folder (a move would self-copy forever).
+ if (oldHome) {
+ if (newHome === oldHome) return { ok: false, error: 'That is already the current home folder.' };
+ const a = newHome + sep, b = oldHome + sep;
+ if (a.startsWith(b) || b.startsWith(a)) {
+ return { ok: false, error: 'Pick a folder that is not inside (or a parent of) the current home.' };
+ }
+ }
+
+ const ensured = ensureHarnessHome(newHome);
+ if (!ensured.ok) return ensured;
+
+ // Tear down everything bound to the OLD root before copying, so nothing writes
+ // mid-copy — a live git commit into hive/.git would otherwise be copied as a
+ // half-written object and corrupt the moved repo.
+ try { clearMissionTimers(); } catch (e) { console.error('[changeHome] clearMissionTimers:', e); }
+ try { hive.stopRouter(); } catch (e) { console.error('[changeHome] stopRouter:', e); }
+ try { hookServer.stop(); } catch (e) { console.error('[changeHome] hookServer.stop:', e); }
+ try { stopSlackServer(); } catch (e) { console.error('[changeHome] slack.stop:', e); }
+ try { memory.stop(); } catch (e) { console.error('[changeHome] memory.stop:', e); }
+ try { reflector.stop(); } catch (e) { console.error('[changeHome] reflector.stop:', e); }
+
+ if (mode === 'move' && oldHome) {
+ try {
+ for (const sub of ['hive', 'palace']) {
+ const src = join(oldHome, sub);
+ if (!existsSync(src)) continue;
+ // cpSync copies the whole tree incl. .git and is cross-device safe (unlike
+ // renameSync, which throws EXDEV across volumes). We COPY, never delete —
+ // the old folder stays as a safety net the user removes manually.
+ cpSync(src, join(newHome, sub), { recursive: true, force: true, dereference: false });
+ }
+ } catch (e) {
+ // Copy failed: recover IN PLACE against the unchanged old home (config never
+ // repointed) so the user loses nothing, and surface the error — no relaunch.
+ bootstrapHiveServices();
+ const cfg = readConfig();
+ if (cfg.slackEnabled && cfg.slackSigningSecret) void startSlackServer();
+ return { ok: false, error: `Could not copy data: ${e instanceof Error ? e.message : String(e)}` };
+ }
+ }
+
+ // Repoint config and relaunch so every service re-bootstraps against newHome.
+ // (Identical recovery path to resetAll — relaunch is the clean re-bind.)
+ allowQuit = true;
+ writeConfig({ harnessHome: newHome });
+ try { ptyManager.killAll(); } catch (e) { console.error('[changeHome] killAll:', e); }
+ app.relaunch();
+ app.exit(0);
+ return { ok: true as const }; // unreachable (process exits) — typed for the renderer
+});
+
// ─── IPC: filesystem (sandboxed to a root) ──────────────────────────────────
ipcMain.handle('fs:listDir', (_evt, root: unknown, rel: unknown) => {
if (typeof root !== 'string' || typeof rel !== 'string') return { ok: false, error: 'invalid args' };
@@ -657,17 +722,23 @@ ipcMain.handle('slack:setConfig', (_evt, patch: unknown) => {
return { ok: true };
});
+/** Start every hive-bound background service against the current harnessHome.
+ * Called on boot, and again to recover in place if a folder-change copy fails
+ * (config:changeHome tears these down before copying). No-op without a home. */
+function bootstrapHiveServices(): void {
+ if (!hive.enabled()) return;
+ hive.ensureHive();
+ hive.startRouter();
+ ensureDefaultMissions(); // one-time: seed the built-in hourly ops standup
+ syncMissions(); // arm recurring auto-dispatch missions now the router is live
+ hookServer.start();
+ memory.start(); // init shared palace + mine loop (no-op without mempalace)
+ reflector.start(); // bound oversized memory.md files on a timer (no-op until threshold)
+}
+
app.whenReady().then(() => {
// Bootstrap the hive (if harnessHome is configured) and start the message router.
- if (hive.enabled()) {
- hive.ensureHive();
- hive.startRouter();
- ensureDefaultMissions(); // one-time: seed the built-in hourly ops standup
- syncMissions(); // arm recurring auto-dispatch missions now the router is live
- hookServer.start();
- memory.start(); // init shared palace + mine loop (no-op without mempalace)
- reflector.start(); // bound oversized memory.md files on a timer (no-op until threshold)
- }
+ bootstrapHiveServices();
createWindow();
// Auto-start the Slack webhook server when configured. Best-effort: a tunnel
// failure (offline) is logged, not fatal. The tunnel URL is ephemeral and
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 4d62a329..1b88ae59 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -201,6 +201,12 @@ const api = {
ipcRenderer.invoke('config:update', patch),
ensureHarnessHome: (path: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('config:ensureHome', path),
+ /** Change the harness home folder. 'move' copies the existing hive + palace
+ * into the new folder (old kept as a safety net); 'fresh' just re-points and
+ * bootstraps an empty home. On success the app relaunches (never resolves);
+ * on failure (e.g. copy error) returns { ok: false, error }. */
+ changeHome: (newHome: string, mode: 'move' | 'fresh'): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('config:changeHome', { newHome, mode }),
// ─── Filesystem (sandboxed to cwd) ───────────────────────────────────────
listDir: (root: string, rel: string): Promise<
diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsx
index 6665e841..d425985a 100644
--- a/src/renderer/src/components/SettingsModal.tsx
+++ b/src/renderer/src/components/SettingsModal.tsx
@@ -54,6 +54,12 @@ function clearLocalState(): void {
export function SettingsModal({ config, onClose }: SettingsModalProps) {
const [confirming, setConfirming] = useState(false);
const [busy, setBusy] = useState(false);
+ // Change-home flow: null until the user picks a new folder, then the sub-modal
+ // confirms move-vs-fresh. Pre-selects 'move' (recommended — keeps the data).
+ const [changeHome, setChangeHome] = useState<string | null>(null);
+ const [changeMode, setChangeMode] = useState<'move' | 'fresh'>('move');
+ const [changeBusy, setChangeBusy] = useState(false);
+ const [changeErr, setChangeErr] = useState('');
// `notifications` is an optional field on the main-process config; the renderer
// mirror type may not declare it yet, so read it defensively.
const [notifications, setNotifications] = useState<boolean>(
@@ -130,8 +136,36 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
await window.cth.resetAll();
};
+ // ─── Change home folder ─────────────────────────────────────────────────────
+ /** Pick a new folder, then open the move-vs-fresh sub-modal. */
+ const pickNewHome = async () => {
+ setChangeErr('');
+ const res = await window.cth.chooseFolder();
+ if (!res.ok) return; // cancelled — no-op
+ setChangeMode('move'); // recommended default
+ setChangeHome(res.path);
+ };
+
+ /** Apply the home-folder change. On success the app relaunches (never resolves);
+ * on failure we surface the error and the existing home keeps running. */
+ const applyChangeHome = async () => {
+ if (!changeHome) return;
+ setChangeBusy(true); setChangeErr('');
+ // Moving copies the hive (incl. its .git) + palace, so the new home owns the
+ // same renderer-side roster — keep localStorage. A 'fresh' home starts empty,
+ // so clear the renderer cache to match.
+ if (changeMode === 'fresh') clearLocalState();
+ try {
+ const res = await window.cth.changeHome(changeHome, changeMode);
+ if (!res.ok) { setChangeErr(res.error ?? 'Could not change the home folder.'); setChangeBusy(false); }
+ // ok === true never returns (the process relaunches).
+ } catch (e) {
+ setChangeErr(e instanceof Error ? e.message : String(e));
+ setChangeBusy(false);
+ }
+ };
+
const rows: Array<[string, string]> = [
- ['Home folder', config.harnessHome ?? '—'],
['Auto mode', config.autoMode ? 'on' : 'off'],
['Semantic memory', config.semanticMemory ? 'on' : 'off'],
['Command', config.defaultCommand]
@@ -148,9 +182,77 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
}}
>
<div onClick={(e) => e.stopPropagation()} style={{ width: 520, maxWidth: '92vw' }}>
- <PixelPanel variant="dialog" title={confirming ? 'RESET EVERYTHING?' : 'SETTINGS'} noPadding>
- {!confirming ? (
+ <PixelPanel
+ variant="dialog"
+ title={changeHome ? 'CHANGE HOME FOLDER' : confirming ? 'RESET EVERYTHING?' : 'SETTINGS'}
+ noPadding
+ >
+ {changeHome ? (
+ <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
+ <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>New home folder</span>
+ <code style={{
+ fontFamily: 'var(--cth-font-mono, monospace)', fontSize: 13,
+ color: 'var(--cth-ink-900)', wordBreak: 'break-all'
+ }}>{changeHome}</code>
+ </div>
+
+ {/* Move vs. fresh — two selectable option rows; move is preselected. */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
+ {([
+ ['move', 'Move existing data (recommended)', 'Copy this harness’s hive (every agent, memory, task) and the semantic-memory palace into the new folder. The old folder is left untouched as a backup you can delete later.'],
+ ['fresh', 'Start fresh', 'Point the harness at the new (empty) folder. Your existing data stays in the old folder, simply unused.']
+ ] as const).map(([value, title, desc]) => {
+ const selected = changeMode === value;
+ return (
+ <button
+ key={value}
+ type="button"
+ onClick={() => setChangeMode(value)}
+ disabled={changeBusy}
+ style={{
+ textAlign: 'left', cursor: changeBusy ? 'default' : 'pointer',
+ padding: '10px 12px', background: 'var(--cth-paper-100)', border: 'none',
+ boxShadow: `inset 0 0 0 ${selected ? 2 : 1}px ${selected ? 'var(--cth-ink-900)' : 'var(--cth-ink-300)'}`,
+ display: 'flex', flexDirection: 'column', gap: 3
+ }}
+ >
+ <span style={{
+ fontSize: 14, lineHeight: '20px',
+ color: 'var(--cth-ink-900)', fontWeight: selected ? 700 : 400
+ }}>
+ {selected ? '◉ ' : '○ '}{title}
+ </span>
+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>{desc}</span>
+ </button>
+ );
+ })}
+ </div>
+
+ {changeErr && (
+ <div style={{ fontSize: 13, lineHeight: '18px', color: '#6E1423' }}>{changeErr}</div>
+ )}
+
+ <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
+ <PixelButton variant="secondary" size="md" onClick={() => { setChangeHome(null); setChangeErr(''); }} disabled={changeBusy}>
+ cancel
+ </PixelButton>
+ <PixelButton variant="primary" size="md" onClick={applyChangeHome} disabled={changeBusy}>
+ {changeBusy ? 'applying…' : (changeMode === 'move' ? 'move & restart' : 'switch & restart')}
+ </PixelButton>
+ </div>
+ </div>
+ ) : !confirming ? (
<div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
+ {/* Home folder — a dedicated row so it can carry a Change… action. */}
+ <div style={{ display: 'flex', gap: 12, fontSize: 14, lineHeight: '20px', alignItems: 'center' }}>
+ <span style={{ width: 140, flexShrink: 0, color: 'var(--cth-ink-500)' }}>Home folder</span>
+ <span style={{
+ flex: 1, color: 'var(--cth-ink-900)', wordBreak: 'break-all',
+ fontFamily: 'var(--cth-font-mono, monospace)'
+ }}>{config.harnessHome ?? '—'}</span>
+ <PixelButton variant="secondary" size="sm" onClick={pickNewHome}>change…</PixelButton>
+ </div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{rows.map(([label, value]) => (
<div key={label} style={{ display: 'flex', gap: 12, fontSize: 14, lineHeight: '20px' }}>