Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(subagents): default auto_session on for newly created subagents (CHOO-1397) (#17)
Louis Amaudruzd9aafc6181e0
diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.tsnew file mode 100644index 000000000..a335f6fa5--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.test.ts@@ -0,0 +1,104 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const getPlugin = vi.hoisted(() => vi.fn());+const getServer = vi.hoisted(() => vi.fn());+const registerSubagentsCore = vi.hoisted(() => vi.fn());+const resolveSubagentWorkspace = vi.hoisted(() => vi.fn());+const applyLocalSubagentAutoSessionState = vi.hoisted(() => vi.fn(async () => {}));+const logWarn = vi.hoisted(() => vi.fn());++vi.mock('@main/core/providers/plugin-registry', () => ({ getPlugin }));+vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer }));+vi.mock('./register-subagents', () => ({ registerSubagentsCore }));+vi.mock('./resolve-workspace', () => ({ resolveSubagentWorkspace }));+vi.mock('./setSubagentAutoSession', () => ({ applyLocalSubagentAutoSessionState }));+vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, error: vi.fn() } }));++const { createSubagent } = await import('./create-subagent');++const behavior = {+ readDefinition: vi.fn(),+ writeDefinition: vi.fn(async () => {}),+ removeLocal: vi.fn(async () => {}),+};++function mockWorkspace(agent: Record<string, unknown>) {+ resolveSubagentWorkspace.mockResolvedValue({ agent, fs: {}, close: vi.fn() });+}++const LOCAL_PARENT = {+ id: 'local-parent',+ providerId: 'claude',+ serverId: 'srv-1',+ switchAgentId: 'sw-parent',+ connection: 'local',+};++const PARAMS = {+ parentAgentId: 'local-parent',+ attributes: { name: 'code-reviewer', description: 'reviews' },+};++describe('createSubagent', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getPlugin.mockReturnValue({ behavior: { subagents: behavior } });+ getServer.mockResolvedValue({ id: 'srv-1', apiUrl: 'https://switch.example.com' });+ behavior.readDefinition.mockResolvedValue(null);+ registerSubagentsCore.mockResolvedValue({ registered: ['code-reviewer'] });+ });++ it('registers with auto_session on and starts the watcher for a local parent', async () => {+ mockWorkspace(LOCAL_PARENT);++ const result = await createSubagent(PARAMS);++ expect(registerSubagentsCore).toHaveBeenCalledWith(+ expect.objectContaining({+ parentSwitchAgentId: 'sw-parent',+ subagents: [{ name: 'code-reviewer', description: 'reviews' }],+ autoSession: true,+ })+ );+ expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledWith(+ 'local-parent',+ 'code-reviewer',+ true+ );+ expect(result).toEqual({ name: 'code-reviewer' });+ });++ it('registers with auto_session off and starts no watcher for a remote parent', async () => {+ mockWorkspace({ ...LOCAL_PARENT, connection: 'remote' });++ await createSubagent(PARAMS);++ expect(registerSubagentsCore).toHaveBeenCalledWith(+ expect.objectContaining({ autoSession: false })+ );+ expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();+ });++ it('does not fail creation when starting the watcher fails', async () => {+ mockWorkspace(LOCAL_PARENT);+ applyLocalSubagentAutoSessionState.mockRejectedValueOnce(new Error('watcher boom'));++ const result = await createSubagent(PARAMS);++ expect(result).toEqual({ name: 'code-reviewer' });+ expect(logWarn).toHaveBeenCalledWith(+ expect.stringContaining('failed to start auto_session watcher'),+ expect.objectContaining({ name: 'code-reviewer' })+ );+ });++ it('removes the written definition when registration fails', async () => {+ mockWorkspace(LOCAL_PARENT);+ registerSubagentsCore.mockRejectedValueOnce(new Error('gateway boom'));++ await expect(createSubagent(PARAMS)).rejects.toThrow('gateway boom');++ expect(behavior.removeLocal).toHaveBeenCalledWith({}, 'code-reviewer');+ expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.tsindex 2f4600fb2..59693d11d 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/create-subagent.ts@@ -1,8 +1,10 @@import type { SubagentAttributes } from '@switchdash/core/agents/plugins';import { getPlugin } from '@main/core/providers/plugin-registry';import { getServer } from '@main/core/switch-servers/servers-store';+import { log } from '@main/lib/logger';import { registerSubagentsCore } from './register-subagents';import { resolveSubagentWorkspace } from './resolve-workspace';+import { applyLocalSubagentAutoSessionState } from './setSubagentAutoSession';export type CreateSubagentParams = {/** The parent agent to create the subagent under. Its provider, Switch server,@@ -52,6 +54,9 @@ export async function createSubagent(params: CreateSubagentParams): Promise<{ naawait behavior.writeDefinition(workspace.fs, params.attributes);+ // Subagents of remote parents register with auto_session off: neither the+ // local watcher (no project path) nor the on-VM sidecar watches subagents.+ const autoSession = agent.connection !== 'remote';try {const server = await getServer(agent.serverId);if (!server) throw new Error(`No Switch server with id ${agent.serverId}`);@@ -61,12 +66,26 @@ export async function createSubagent(params: CreateSubagentParams): Promise<{ naparentSwitchAgentId: agent.switchAgentId,fs: workspace.fs,subagents: [{ name, description }],+ autoSession,});} catch (error) {await behavior.removeLocal(workspace.fs, name);throw error;}+ // Seed the local auto_session mirror + start the watcher so the new+ // subagent begins watching now, without an off→on toggle. Best-effort: a+ // failure must not fail creation (the settings panel reconciles later).+ if (autoSession) {+ await applyLocalSubagentAutoSessionState(params.parentAgentId, name, true).catch((error) => {+ log.warn('createSubagent: failed to start auto_session watcher for new subagent', {+ parentAgentId: params.parentAgentId,+ name,+ error: String(error),+ });+ });+ }+return { name };} finally {workspace.close();diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.tsindex e75c503ef..fb86a4321 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.test.ts@@ -9,6 +9,10 @@ const openRemoteSubagentFs = vi.hoisted(() => vi.fn());const writeSettings = vi.hoisted(() => vi.fn(async () => {}));const remoteClose = vi.hoisted(() => vi.fn());const remoteRead = vi.hoisted(() => vi.fn());+const getAgents = vi.hoisted(() => vi.fn());+const getLocalProjectByPath = vi.hoisted(() => vi.fn());+const applyLocalSubagentAutoSessionState = vi.hoisted(() => vi.fn(async () => {}));+const logWarn = vi.hoisted(() => vi.fn());vi.mock('@main/core/providers/plugin-registry', () => ({ getPlugin }));vi.mock('@main/core/providers/plugin-fs', () => ({ createPluginFs: vi.fn() }));@@ -19,9 +23,12 @@ vi.mock('@main/core/switch-rooms/switch-credentials', () => ({readSwitchAgentCredentials,}));vi.mock('./resolve-workspace', () => ({ openRemoteSubagentFs }));-vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), error: vi.fn() } }));+vi.mock('@main/core/agents/getAgents', () => ({ getAgents }));+vi.mock('@main/core/projects/operations/getProjects', () => ({ getLocalProjectByPath }));+vi.mock('./setSubagentAutoSession', () => ({ applyLocalSubagentAutoSessionState }));+vi.mock('@main/lib/logger', () => ({ log: { warn: logWarn, error: vi.fn() } }));-const { registerSubagentsRemote } = await import('./register-subagents');+const { registerSubagents, registerSubagentsRemote } = await import('./register-subagents');const REMOTE = {providerId: 'claude',@@ -69,8 +76,10 @@ describe('registerSubagentsRemote', () => {{parentAgentId: 'sw-parent',subagents: [{ subagentName: 'code-reviewer', description: 'reviews' }],+ autoSession: false,});+ expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();expect(writeSettings).toHaveBeenCalledWith({ read: remoteRead },expect.objectContaining({@@ -98,3 +107,99 @@ describe('registerSubagentsRemote', () => {expect(remoteClose).toHaveBeenCalledTimes(1);});});++const LOCAL = {+ providerId: 'claude',+ serverId: 'srv-1',+ dir: '/home/dev/r',+};++describe('registerSubagents', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getPlugin.mockReturnValue({ behavior: { subagents: { writeSettings } } });+ getServer.mockResolvedValue({ id: 'srv-1', apiUrl: 'https://switch.example.com' });+ readSwitchAgentCredentials.mockResolvedValue({+ agentId: 'sw-parent',+ apiEndpoint: 'https://switch.example.com',+ token: 'tok',+ });+ });++ it('registers with auto_session on and starts a watcher per new subagent', async () => {+ registerSubagentsBulk.mockResolvedValueOnce([+ { subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },+ { subagentName: 'doc-writer', id: 'child-2', apiKey: 'key-2' },+ ]);+ getLocalProjectByPath.mockResolvedValueOnce({ id: 'proj-1' });+ getAgents.mockResolvedValueOnce([+ { id: 'local-other', switchAgentId: 'sw-other' },+ { id: 'local-parent', switchAgentId: 'sw-parent' },+ ]);++ const result = await registerSubagents({+ ...LOCAL,+ subagents: [+ { name: 'code-reviewer', description: 'reviews' },+ { name: 'doc-writer', description: 'writes docs' },+ ],+ });++ expect(registerSubagentsBulk).toHaveBeenCalledWith(+ expect.objectContaining({ apiUrl: 'https://switch.example.com' }),+ expect.objectContaining({ parentAgentId: 'sw-parent', autoSession: true })+ );+ expect(getLocalProjectByPath).toHaveBeenCalledWith('/home/dev/r');+ expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledTimes(2);+ expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledWith(+ 'local-parent',+ 'code-reviewer',+ true+ );+ expect(applyLocalSubagentAutoSessionState).toHaveBeenCalledWith(+ 'local-parent',+ 'doc-writer',+ true+ );+ expect(result).toEqual({ registered: ['code-reviewer', 'doc-writer'] });+ });++ it('warns instead of failing when no local agent matches the dir', async () => {+ registerSubagentsBulk.mockResolvedValueOnce([+ { subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },+ ]);+ getLocalProjectByPath.mockResolvedValueOnce(undefined);++ const result = await registerSubagents({+ ...LOCAL,+ subagents: [{ name: 'code-reviewer', description: 'reviews' }],+ });++ expect(result).toEqual({ registered: ['code-reviewer'] });+ expect(applyLocalSubagentAutoSessionState).not.toHaveBeenCalled();+ expect(logWarn).toHaveBeenCalledWith(+ expect.stringContaining('no local agent for dir'),+ expect.objectContaining({ dir: '/home/dev/r' })+ );+ });++ it('does not fail registration when starting a watcher fails', async () => {+ registerSubagentsBulk.mockResolvedValueOnce([+ { subagentName: 'code-reviewer', id: 'child-1', apiKey: 'key-1' },+ ]);+ getLocalProjectByPath.mockResolvedValueOnce({ id: 'proj-1' });+ getAgents.mockResolvedValueOnce([{ id: 'local-parent', switchAgentId: 'sw-parent' }]);+ applyLocalSubagentAutoSessionState.mockRejectedValueOnce(new Error('watcher boom'));++ const result = await registerSubagents({+ ...LOCAL,+ subagents: [{ name: 'code-reviewer', description: 'reviews' }],+ });++ expect(result).toEqual({ registered: ['code-reviewer'] });+ expect(logWarn).toHaveBeenCalledWith(+ expect.stringContaining('failed to start auto_session watcher'),+ expect.objectContaining({ name: 'code-reviewer' })+ );+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.tsindex 513456060..03b1e2988 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/register-subagents.ts@@ -1,4 +1,6 @@import type { ISubagentsBehavior, PluginFs } from '@switchdash/core/agents/plugins';+import { getAgents } from '@main/core/agents/getAgents';+import { getLocalProjectByPath } from '@main/core/projects/operations/getProjects';import { createPluginFs } from '@main/core/providers/plugin-fs';import { getPlugin } from '@main/core/providers/plugin-registry';import {@@ -10,6 +12,7 @@ import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { openRemoteSubagentFs } from './resolve-workspace';+import { applyLocalSubagentAutoSessionState } from './setSubagentAutoSession';// Remote hosts are POSIX; use a forward-slash literal rather than path.join// (which emits backslashes on Windows). SshFileSystem normalises separators, but@@ -43,6 +46,10 @@ export async function registerSubagentsCore(params: {parentSwitchAgentId: string;fs: PluginFs;subagents: { name: string; description: string }[];+ /** Register the subagents with `auto_session` on, so a watcher auto-spawns a+ * session when one is addressed. Only pass true for local parents — subagents+ * of remote parents have no watcher (neither here nor in the VM sidecar). */+ autoSession: boolean;}): Promise<{ registered: string[] }> {if (params.subagents.length === 0) return { registered: [] };@@ -52,6 +59,7 @@ export async function registerSubagentsCore(params: {subagentName: s.name,description: s.description,})),+ autoSession: params.autoSession,});for (const result of results) {@@ -67,6 +75,44 @@ export async function registerSubagentsCore(params: {return { registered: results.map((r) => r.subagentName) };}+/**+ * Seed the local auto_session mirror + start the watcher for freshly-registered+ * subagents, so they begin watching now without an off→on toggle (CHOO-1397).+ * The mirror and watcher are keyed by the parent's LOCAL agent id, resolved from+ * the parent's directory — present in the onboarding flow because the project is+ * created before its subagents are registered. Best-effort: a failure here must+ * not fail the registration (the settings panel reconciles from the gateway).+ */+async function startAutoSessionWatchers(+ dir: string,+ parentSwitchAgentId: string,+ names: string[]+): Promise<void> {+ const project = await getLocalProjectByPath(dir);+ const localParent = project+ ? (await getAgents(project.id)).find((a) => a.switchAgentId === parentSwitchAgentId)+ : undefined;+ if (!localParent) {+ log.warn(+ 'registerSubagents: no local agent for dir; auto_session watchers start on reconcile',+ {+ dir,+ parentSwitchAgentId,+ }+ );+ return;+ }+ for (const name of names) {+ await applyLocalSubagentAutoSessionState(localParent.id, name, true).catch((error) => {+ log.warn('registerSubagents: failed to start auto_session watcher for new subagent', {+ parentAgentId: localParent.id,+ name,+ error: String(error),+ });+ });+ }+}+/*** Register the given subagents under the directory's parent agent on the gateway* and write their credentials. Used by the local onboarding flow, which knows the@@ -94,13 +140,16 @@ export async function registerSubagents();}- return registerSubagentsCore({+ const result = await registerSubagentsCore({behavior,server,parentSwitchAgentId: parent.agentId,fs: createPluginFs(params.dir),subagents: params.subagents,+ autoSession: true,});+ await startAutoSessionWatchers(params.dir, parent.agentId, result.registered);+ return result;}export type RegisterSubagentsRemoteParams = {@@ -142,12 +191,16 @@ export async function registerSubagentsRemote(`No Switch agent configured at ${params.sshHost}:${params.remoteRepoDir} — cannot register subagents under it.`);}+ // Subagents of remote parents register with auto_session off: neither the+ // local watcher (no project path) nor the on-VM sidecar watches subagents,+ // so an auto_session profile would advertise a capability nothing serves.return await registerSubagentsCore({behavior,server,parentSwitchAgentId: parent.agentId,fs: remote.fs,subagents: params.subagents,+ autoSession: false,});} finally {remote.close();diff --git a/dash/apps/switchdash-desktop/src/main/core/subagents/setSubagentAutoSession.ts b/dash/apps/switchdash-desktop/src/main/core/subagents/setSubagentAutoSession.tsindex 6c7789f8e..2c43c30bc 100644--- a/dash/apps/switchdash-desktop/src/main/core/subagents/setSubagentAutoSession.ts+++ b/dash/apps/switchdash-desktop/src/main/core/subagents/setSubagentAutoSession.ts@@ -19,6 +19,20 @@ export type SubagentAutoSessionParams = {enabled: boolean;};+/**+ * Apply a subagent's auto_session state to the LOCAL side only: mirror the flag+ * and start/stop its watcher. Does NOT touch the gateway profile — callers that+ * also mutate the gateway must do so separately.+ */+export async function applyLocalSubagentAutoSessionState(+ parentAgentId: string,+ name: string,+ enabled: boolean+): Promise<void> {+ await setAutoSessionSubagent(parentAgentId, name, enabled);+ await autoSessionWatcher.reconcileSubagent(parentAgentId, name, enabled);+}+/** Resolve a subagent's own Switch agent id (needed to flip its gateway profile). */async function resolveSubagentSwitchId(parentAgentId: string,@@ -50,8 +64,7 @@ export async function setSubagentAutoSession(params: SubagentAutoSessionParams):}await setAutoSession(server, switchAgentId, params.enabled);- await setAutoSessionSubagent(params.parentAgentId, params.name, params.enabled);- await autoSessionWatcher.reconcileSubagent(params.parentAgentId, params.name, params.enabled);+ await applyLocalSubagentAutoSessionState(params.parentAgentId, params.name, params.enabled);}/**@@ -74,8 +87,7 @@ export async function getSubagentAutoSession(params: {try {const { connectionModel } = await fetchAgentOptions(server, switchAgentId);const enabled = connectionModel === 'auto_session';- await setAutoSessionSubagent(params.parentAgentId, params.name, enabled);- await autoSessionWatcher.reconcileSubagent(params.parentAgentId, params.name, enabled);+ await applyLocalSubagentAutoSessionState(params.parentAgentId, params.name, enabled);return enabled;} catch (error) {if (error instanceof GatewayError) {diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.tsindex 69efecb73..395a38f77 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts@@ -332,6 +332,9 @@ export async function registerSubagentsBulk(params: {parentAgentId: string;subagents: { subagentName: string; description: string }[];+ /** Register every subagent with the `auto_session` connection model, so a+ * watcher auto-spawns a session when the subagent is addressed. */+ autoSession: boolean;overwrite?: boolean;}): Promise<BulkRegisteredSubagent[]> {@@ -341,7 +344,7 @@ export async function registerSubagentsBulk(body: {agent_type: 'claude-code',parent_agent_id: params.parentAgentId,- options: {},+ options: params.autoSession ? { auto_session: true } : {},subagents: params.subagents.map((s) => ({subagent_name: s.subagentName,description: s.description,