Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(switchdash): fix slow boot from agent-storage migration + restore vanished sessions (CHOO-1440) (#75)

Louis Amaudruz948dd9aa9a2f
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.ts
new file mode 100644
index 000000000..40593d1e1
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.ts
@@ -0,0 +1,23 @@
+import { eq, sql } from 'drizzle-orm';
+import { db } from '@main/db/client';
+import { kv } from '@main/db/schema';
+
+/**
+ * Persisted marker recording that the CHOO-1440 agent-storage migration has
+ * completed a full, error-free pass. Once set, {@link migrateAgentStorage}
+ * short-circuits at boot instead of re-opening every agent's workspace
+ * filesystem (an SSH/SFTP round trip per remote agent) on every launch.
+ */
+const MARKER_KEY = 'agentStorageMigrationComplete';
+
+export async function isAgentStorageMigrationComplete(): Promise<boolean> {
+ const [row] = await db.select().from(kv).where(eq(kv.key, MARKER_KEY)).limit(1);
+ return row?.value === '1';
+}
+
+export async function markAgentStorageMigrationComplete(): Promise<void> {
+ await db
+ .insert(kv)
+ .values({ key: MARKER_KEY, value: '1', updatedAt: sql`CURRENT_TIMESTAMP` })
+ .onConflictDoUpdate({ target: kv.key, set: { value: '1', updatedAt: sql`CURRENT_TIMESTAMP` } });
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts
index 3041c0d79..1f40612fb 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts
@@ -70,6 +70,9 @@ const h = vi.hoisted(() => {
),
discoverLocal: vi.fn(async () => []),
updateAgent: vi.fn(async () => undefined),
+ isComplete: vi.fn(async () => false),
+ markComplete: vi.fn(async () => undefined),
+ backfill: vi.fn(async () => 0),
};
});
@@ -101,6 +104,13 @@ vi.mock('./updateAgent', () => ({ updateAgent: h.updateAgent }));
vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: vi.fn() }));
vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));
vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock('./agent-storage-migration-marker', () => ({
+ isAgentStorageMigrationComplete: h.isComplete,
+ markAgentStorageMigrationComplete: h.markComplete,
+}));
+vi.mock('@main/core/sessions/operations/backfillSessionAgentName', () => ({
+ backfillSessionAgentName: h.backfill,
+}));
import { migrateAgentStorage } from './migrate-agent-storage';
@@ -174,4 +184,75 @@ describe('migrateAgentStorage', () => {
expect(h.writeCredentials).not.toHaveBeenCalled();
expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(false);
});
+
+ it('skips the whole pass (no workspace opened) once the marker is set', async () => {
+ h.isComplete.mockResolvedValueOnce(true);
+ const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;
+
+ await migrateAgentStorage();
+
+ expect(resolveWorkspaceFsFor).not.toHaveBeenCalled();
+ expect(h.writeCredentials).not.toHaveBeenCalled();
+ expect(h.markComplete).not.toHaveBeenCalled();
+ });
+
+ it('latches the marker after a clean pass', async () => {
+ h.state.workspace = fakeFs({
+ '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),
+ '.claude/agents/cc-hoot-main.md': '# def',
+ });
+
+ await migrateAgentStorage();
+
+ expect(h.markComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not latch the marker when an agent migration throws', async () => {
+ h.state.workspace = fakeFs({
+ '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),
+ '.claude/agents/cc-hoot-main.md': '# def',
+ });
+ h.readDefinition.mockRejectedValueOnce(new Error('host unreachable'));
+
+ await migrateAgentStorage();
+
+ expect(h.markComplete).not.toHaveBeenCalled();
+ });
+
+ it('does not latch the marker when an agent name cannot be resolved', async () => {
+ h.state.agents = [{ ...baseAgent, definitionName: null }];
+ h.discoverLocal.mockResolvedValueOnce([]);
+ h.state.workspace = fakeFs({});
+
+ await migrateAgentStorage();
+
+ expect(h.markComplete).not.toHaveBeenCalled();
+ });
+
+ it('backfills session agentName so migrated sessions stay grouped under the agent', async () => {
+ h.state.workspace = fakeFs({
+ '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),
+ '.claude/agents/cc-hoot-main.md': '# def',
+ });
+
+ await migrateAgentStorage();
+
+ expect(h.backfill).toHaveBeenCalledWith('agent-id-1', 'cc-hoot-main');
+ });
+
+ it('backfills even when definitionName was already set (repairs a prior migration)', async () => {
+ // definitionName is already populated (an earlier migration ran) but old
+ // sessions still carry no agentName — the backfill must still repair them.
+ h.state.agents = [{ ...baseAgent, definitionName: 'cc-hoot-main' }];
+ h.backfill.mockResolvedValueOnce(3);
+ h.state.workspace = fakeFs({
+ '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),
+ '.claude/agents/cc-hoot-main.md': '# def',
+ });
+
+ await migrateAgentStorage();
+
+ expect(h.updateAgent).not.toHaveBeenCalled();
+ expect(h.backfill).toHaveBeenCalledWith('agent-id-1', 'cc-hoot-main');
+ });
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts
index d28911ab3..d3abc1521 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts
@@ -1,10 +1,15 @@
import { getLocationById } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
+import { backfillSessionAgentName } from '@main/core/sessions/operations/backfillSessionAgentName';
import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';
import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';
import { getServer } from '@main/core/switch-servers/servers-store';
import { log } from '@main/lib/logger';
import type { Agent } from '@shared/core/agents/agents';
+import {
+ isAgentStorageMigrationComplete,
+ markAgentStorageMigrationComplete,
+} from './agent-storage-migration-marker';
import { resolveWorkspaceFsFor } from './agent-workspace-fs';
import { getAgents } from './getAgents';
import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';
@@ -25,12 +30,21 @@ import { updateAgent } from './updateAgent';
* through the same provider filesystem abstraction.
*/
export async function migrateAgentStorage(): Promise<void> {
+ // Once a full pass has migrated every agent, never re-run: the steady-state
+ // migration re-opens each agent's workspace filesystem (an SSH/SFTP round trip
+ // per remote agent) on every boot for no benefit.
+ if (await isAgentStorageMigrationComplete()) return;
+
const agents = await getAgents();
let migrated = 0;
+ let allComplete = true;
for (const agent of agents) {
try {
- if (await migrateOne(agent)) migrated += 1;
+ const result = await migrateOne(agent);
+ if (result.changed) migrated += 1;
+ if (!result.complete) allComplete = false;
} catch (error) {
+ allComplete = false;
log.warn('migrateAgentStorage: failed to migrate agent', {
agentId: agent.id,
error: String(error),
@@ -40,15 +54,26 @@ export async function migrateAgentStorage(): Promise<void> {
if (migrated > 0) {
log.info('migrateAgentStorage: migrated agents to the neutral storage layout', { migrated });
}
+ // Only latch the marker when every agent reached the final layout this pass.
+ // A transient failure (unreachable host, gateway down) leaves it unset so the
+ // next boot retries — cheaply, since the migration now runs off the boot path.
+ if (allComplete) await markAgentStorageMigrationComplete();
+}
+
+interface MigrateResult {
+ /** Whether this pass wrote anything for the agent. */
+ changed: boolean;
+ /** Whether the agent is now fully in the new layout (nothing left to retry). */
+ complete: boolean;
}
-/** Migrate one agent (local or remote); returns whether anything changed. */
-async function migrateOne(agent: Agent): Promise<boolean> {
+/** Migrate one agent (local or remote). */
+async function migrateOne(agent: Agent): Promise<MigrateResult> {
const behavior = getPlugin(agent.providerId).behavior.repoAgents;
- if (!behavior) return false;
+ if (!behavior) return { changed: false, complete: true };
const location = await getLocationById(agent.locationId);
- if (!location) return false;
+ if (!location) return { changed: false, complete: true };
const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);
try {
@@ -60,7 +85,9 @@ async function migrateOne(agent: Agent): Promise<boolean> {
let name = agent.definitionName;
let description = agent.name;
if (!name) {
- if (!agent.switchAgentId) return false;
+ // No switchAgentId → nothing anchors a real name; leave for a later boot
+ // in case the row is still being populated.
+ if (!agent.switchAgentId) return { changed: false, complete: false };
const discovered = await behavior.discoverLocal(workspace.fs, workspace.homeFs);
const match = discovered.find((d) => d.switchAgentId === agent.switchAgentId);
if (match) {
@@ -73,7 +100,8 @@ async function migrateOne(agent: Agent): Promise<boolean> {
agentId: agent.id,
switchAgentId: agent.switchAgentId,
});
- return false;
+ // Resolution may fail transiently (gateway down); retry next boot.
+ return { changed: false, complete: false };
}
name = registered.name;
description = registered.description;
@@ -136,7 +164,22 @@ async function migrateOne(agent: Agent): Promise<boolean> {
changed = true;
}
- return changed;
+ // 4. Backfill this agent's own pre-existing sessions: they froze no
+ // `agentName` (created before it had a definitionName), so the sidebar —
+ // which pairs a session to its agent by `agentName === definitionName` —
+ // would orphan them once definitionName is set. Idempotent, and run even
+ // when definitionName was already populated so installs that ran an
+ // earlier migration (before this backfill existed) are repaired too.
+ const backfilled = await backfillSessionAgentName(agent.id, name);
+ if (backfilled > 0) {
+ log.info('migrateAgentStorage: backfilled session agentName for migrated agent', {
+ agentId: agent.id,
+ backfilled,
+ });
+ changed = true;
+ }
+
+ return { changed, complete: true };
} finally {
workspace.close();
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/backfillSessionAgentName.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/backfillSessionAgentName.ts
new file mode 100644
index 000000000..3fe588d8f
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/backfillSessionAgentName.ts
@@ -0,0 +1,36 @@
+import { eq } from 'drizzle-orm';
+import { db } from '@main/db/client';
+import { sessions } from '@main/db/schema';
+
+/**
+ * Backfill `config.agentName` on an agent's own pre-existing sessions to match
+ * its definitionName.
+ *
+ * `createSession` freezes a session's `agentName` from its agent's
+ * `definitionName` at creation time, and the sidebar joins a session to its
+ * agent by `agentName === definitionName`. Sessions created before the agent had
+ * a definitionName froze no `agentName`, so once the CHOO-1440 migration
+ * populates `definitionName` those sessions match no agent and vanish from the
+ * tree (they still exist and open via deeplink). This restores the pairing.
+ *
+ * Idempotent: only sessions with no `agentName`/`subagentName` are touched, so
+ * re-running is a no-op and sessions launched as a different definition (a former
+ * subagent) are left alone. Returns the number of sessions updated.
+ */
+export async function backfillSessionAgentName(
+ agentId: string,
+ definitionName: string
+): Promise<number> {
+ const rows = await db.select().from(sessions).where(eq(sessions.agentId, agentId));
+ let updated = 0;
+ for (const row of rows) {
+ const config = row.config ?? {};
+ if (config.agentName || config.subagentName) continue;
+ await db
+ .update(sessions)
+ .set({ config: { ...config, agentName: definitionName } })
+ .where(eq(sessions.id, row.id));
+ updated += 1;
+ }
+ return updated;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/index.ts b/dash/apps/switchdash-desktop/src/main/index.ts
index 809b1a1f6..70266a82a 100644
--- a/dash/apps/switchdash-desktop/src/main/index.ts
+++ b/dash/apps/switchdash-desktop/src/main/index.ts
@@ -121,11 +121,12 @@ void app.whenReady().then(async () => {
log.warn('switch-agents: failed to reconcile agent → server links at boot', { error: e });
}
- try {
- await migrateAgentStorage();
- } catch (e) {
+ // Kept off the boot path: this can open an SSH/SFTP connection per remote
+ // agent, so awaiting it here delayed the window opening. Session relaunch below
+ // waits on it (it needs each agent's definitionName); nothing else does.
+ const migrationReady = migrateAgentStorage().catch((e) => {
log.warn('switch-agents: failed to migrate agent storage layout at boot', { error: e });
- }
+ });
const agentHookReady = agentHookService.initialize().catch((e) => {
log.error('Failed to start agent event service:', e);
@@ -153,7 +154,7 @@ void app.whenReady().then(async () => {
// Restore first so already-live sessions register their room connections,
// then start the auto_session watchers — the watcher's "is a session already
// attending this room?" check relies on those connections being present.
- void Promise.all([agentHookReady, dependenciesReady]).then(async () => {
+ void Promise.all([agentHookReady, dependenciesReady, migrationReady]).then(async () => {
try {
await restoreSwitchRoomSessions();
} catch (e) {