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
fix(console): read each agent's own watcher root, and stop abandoned launch directories breaking it (#568)
Louis Amaudruzd11c13ada945
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02c295fef..2627aa02b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1345,6 +1345,28 @@ version of their own to them without also giving them a release of their own.### [Unreleased]+#### Changed+- **Checking a remote agent's watcher reads only that agent's own state.** The+ watcher panel, session start and the sidecar connection used to read every+ agent's watcher configuration on the host to find one, so any other agent's+ broken or duplicated state could fail them. The agent's directory is named+ from its identity, so it is now read directly; the others are only looked at+ when it has none, to adopt a watcher saved under an earlier name.++#### Fixed+- **A remote agent's room watcher no longer fails with "Competing saved+ watchers require explicit cleanup" or an unreadable-config error after a+ launch was interrupted.** Each launch staged the agent's configuration in a+ scratch directory beside every agent's watcher state, and the watcher status+ check, session start and session listing all read that directory in full. A+ scratch directory left behind by a dropped SSH connection held either a+ half-written file, which broke the check for every agent on the host, or a+ complete copy of one agent's configuration, which made that agent look like+ it had two watchers. Launches now stage in a separate `sdk-launch` directory,+ the readers skip any scratch directory an earlier version left, and each+ launch removes staged configurations abandoned more than an hour ago, since+ they carry the agent's credentials.+### [0.37.1] - 2026-09-26#### Fixeddiff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.tsindex 7f2389d21..647949dda 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.ts@@ -6,6 +6,7 @@ import { getAgentById } from '@main/core/agents/getAgentById';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import type { IExecutionContext } from '@main/core/execution-context/types';import { READ_JSON } from './remote-json';+import { IS_STATE_ROOT } from './state-roots';/*** The sessions an agent has on its host, read from the hosts' own state.@@ -15,7 +16,7 @@ import { READ_JSON } from './remote-json';* finds them. One `node` run per call, locally or over the agent's SSH* connection: the same script either way.*/-export const LIST_SCRIPT = String.raw`${READ_JSON}+export const LIST_SCRIPT = String.raw`${READ_JSON}${IS_STATE_ROOT}const fs = require('node:fs');const os = require('node:os');const path = require('node:path');@@ -38,7 +39,7 @@ const alive = (root) => {} catch { return false; }};let names = [];-try { names = fs.readdirSync(base); } catch {}+try { names = fs.readdirSync(base).filter(isStateRoot); } catch {}const found = [];for (const name of names) {const root = path.join(base, name);diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.tsindex d8b1accd3..ada34c421 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.test.ts@@ -65,6 +65,16 @@ const config = {session: { sessionId: 'watcher', agentId: 'switch-agent-1' },} as never;+it('takes the agent’s own watcher root without reading any other', async () => {+ const keyed = localWatcherRoot('switch-agent-1');+ await mkdir(keyed, { recursive: true });+ await writeFile(join(keyed, 'config.json'), JSON.stringify(config));+ const earlier = join(home, '.local/state/switch/sdk-watchers/earlier');+ await mkdir(earlier, { recursive: true });+ await writeFile(join(earlier, 'config.json'), JSON.stringify(config));+ expect(localWatcherRoot('switch-agent-1')).toBe(keyed);+});+it('records why the watcher stopped so the agent panel can show it', async () => {mocks.runWatcher.mockRejectedValue(new Error('Shared SDK watcher delivery gap: sequence reset.'));await startLocalWatcher(config, { intent: 'explicit', spawning: true });diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.tsindex 1d178c249..1543868c8 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/local-host.ts@@ -21,6 +21,7 @@ import {import { resolveSharedHostBundlePath } from '@main/core/agent-runtime/impl/resolve-sidecar-bundle';import { log } from '@main/lib/logger';import { clearStaleOwners } from './local-host-owners';+import { isStateRootName } from './state-roots';/*** Local hosts belong to Console's process tree: a local agent must not answer@@ -59,14 +60,18 @@ export function savedAgentId(root: string): string | null {}/**- * Resolves the watcher state root for an agent, adopting a directory saved- * under an earlier key so a rename does not strand its journal.+ * Resolves the watcher state root for an agent: the directory keyed by its+ * identity, and no other is read while that one holds a configuration.+ * Otherwise a directory saved under an earlier key is adopted, so a rename+ * does not strand its journal. The same rule as `WATCHER_ROOT` on a host.*/export function localWatcherRoot(identity: string): string {const base = localStateBase('sdk-watchers');const keyed = join(base, createHash('sha256').update(identity).digest('hex'));- if (!existsSync(base)) return keyed;- const matches = readdirSync(base).filter((name) => savedAgentId(join(base, name)) === identity);+ if (existsSync(join(keyed, 'config.json')) || !existsSync(base)) return keyed;+ const matches = readdirSync(base)+ .filter(isStateRootName)+ .filter((name) => savedAgentId(join(base, name)) === identity);if (matches.length > 1) throw new Error('Competing saved watchers require explicit cleanup.');return matches[0] ? join(base, matches[0]) : keyed;}@@ -80,7 +85,7 @@ function localWatcherRoots(identity: string): string[] {const base = localStateBase('sdk-watchers');const roots = new Set([join(base, createHash('sha256').update(identity).digest('hex'))]);if (existsSync(base))- for (const name of readdirSync(base))+ for (const name of readdirSync(base).filter(isStateRootName))if (savedAgentId(join(base, name)) === identity) roots.add(join(base, name));return [...roots];}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/reap-local-hosts.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/reap-local-hosts.tsindex e5fc759d5..f38a47551 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/reap-local-hosts.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/reap-local-hosts.ts@@ -6,6 +6,7 @@ import { getAgents } from '@main/core/agents/getAgents';import { log } from '@main/lib/logger';import { localStateBase, savedAgentId, writeWatchFlags } from './local-host';import { ownedElsewhere } from './local-host-owners';+import { isStateRootName } from './state-roots';const STOP_ATTEMPTS = 100;const STOP_INTERVAL_MS = 200;@@ -44,7 +45,7 @@ export async function reapDetachedLocalWatchers(): Promise<void> {const base = localStateBase('sdk-watchers');let entries: string[];try {- entries = await readdir(base);+ entries = (await readdir(base)).filter(isStateRootName);} catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;throw error;diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.tsindex a5441c19d..eb9db6d3a 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts@@ -9,7 +9,7 @@ import type { IExecutionContext } from '@main/core/execution-context/types';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import type { LocationTransport } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { READ_JSON } from './remote-json';+import { MAKE_LAUNCH_DIR, RESOLVE_STATE_ROOT, STALE_LAUNCH_MS } from './state-roots';/*** Every deployment leaves a bundle named after its own hash, so without this@@ -77,8 +77,7 @@ export async function deploySharedHost(} else ctx = new LocalExecutionContext();const { stdout } = await ctx.exec('node', ['-e',- READ_JSON +- "const fs=require('node:fs'),path=require('node:path');const base=path.join(require('node:os').homedir(),'.local','state','switch',process.argv[2]);let root=path.join(base,process.argv[1]);if(process.argv[2]==='sdk-watchers'&&fs.existsSync(base)){const matches=fs.readdirSync(base).filter(name=>{try{return readJson(path.join(base,name,'config.json')).session.agentId===process.argv[3]}catch(e){if(e.code==='ENOENT')return false;throw e}});if(matches.length>1)throw new Error('Competing saved watchers require explicit cleanup.');if(matches.length)root=path.join(base,matches[0]);} console.log(root)",+ RESOLVE_STATE_ROOT,key,watcher ? 'sdk-watchers' : 'sdk-sessions',identity,@@ -104,8 +103,9 @@ export async function runSharedHostCommand(const proxy = await ensureSshConnected(transport.connectionId, transport.host);const result = await deployed.ctx.exec('node', ['-e',- "const fs=require('node:fs'),path=require('node:path');const parent=path.dirname(process.argv[1]);fs.mkdirSync(parent,{recursive:true,mode:0o700});console.log(fs.mkdtempSync(path.join(parent,'.launch-')))",+ MAKE_LAUNCH_DIR,deployed.root,+ String(STALE_LAUNCH_MS),]);remote = result.stdout.trim();const fs = new SshFileSystem(proxy, remote);diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-control.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-control.tsindex fc542b828..35e3be1f0 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-control.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/sidecar-control.ts@@ -3,7 +3,7 @@ import { z } from 'zod';import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';import { getAgentById } from '@main/core/agents/getAgentById';import { log } from '@main/lib/logger';-import { READ_JSON } from './remote-json';+import { WATCHER_ROOT } from './state-roots';/*** Console's connection to an agent's sidecar on its SSH host.@@ -15,19 +15,11 @@ import { READ_JSON } from './remote-json';* on first use and again after it drops.*/-const WATCHER_ROOT_SCRIPT = String.raw`${READ_JSON}-const fs = require('node:fs'), path = require('node:path'), crypto = require('node:crypto');+const WATCHER_ROOT_SCRIPT = String.raw`${WATCHER_ROOT}+const fs = require('node:fs'), path = require('node:path');const [identity, file] = process.argv.slice(1);const base = path.join(require('node:os').homedir(), '.local', 'state', 'switch', 'sdk-watchers');-let root = path.join(base, crypto.createHash('sha256').update(identity).digest('hex'));-if (fs.existsSync(base)) {- const matches = fs.readdirSync(base).filter((name) => {- try { return readJson(path.join(base, name, 'config.json')).session.agentId === identity; }- catch (e) { if (e.code === 'ENOENT') return false; throw e; }- });- if (matches.length > 1) throw new Error('Competing saved watchers require explicit cleanup.');- if (matches.length) root = path.join(base, matches[0]);-}+const root = watcherRoot(base, identity);try { process.stdout.write(fs.readFileSync(path.join(root, file), 'utf8')); }catch (e) { if (e.code === 'ENOENT') process.stdout.write('null'); else throw e; }`;diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/state-roots.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/state-roots.test.tsnew file mode 100644index 000000000..028df83a2--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/state-roots.test.ts@@ -0,0 +1,155 @@+import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import { existsSync } from 'node:fs';+import { mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { promisify } from 'node:util';+import { afterEach, expect, it } from 'vitest';+import {+ isStateRootName,+ MAKE_LAUNCH_DIR,+ RESOLVE_STATE_ROOT,+ STALE_LAUNCH_MS,+} from './state-roots';++const homes: string[] = [];+afterEach(async () => {+ for (const home of homes.splice(0)) await rm(home, { recursive: true, force: true });+});++async function home() {+ const path = await mkdtemp(join(tmpdir(), 'state-roots-'));+ homes.push(path);+ return path;+}++async function saved(root: string, config: string) {+ await mkdir(root, { recursive: true });+ await writeFile(join(root, 'config.json'), config);+}++const agentConfig = (agentId: string) => JSON.stringify({ session: { agentId } });++async function run(home: string, script: string, args: string[]) {+ const { stdout } = await promisify(execFile)(process.execPath, ['-e', script, ...args], {+ env: { ...process.env, HOME: home },+ });+ return stdout.trim();+}++async function age(path: string, ms: number) {+ const then = new Date(Date.now() - ms);+ await utimes(path, then, then);+}++it('takes neither staging prefix for a state root', () => {+ expect(isStateRootName('a'.repeat(64))).toBe(true);+ expect(isStateRootName('.launch-qQ92Pc')).toBe(false);+ expect(isStateRootName('launch-qQ92Pc')).toBe(false);+});++it('resolves an agent’s watcher root past launches that were abandoned beside it', async () => {+ const dir = await home();+ const watchers = join(dir, '.local/state/switch/sdk-watchers');+ const root = join(watchers, 'b'.repeat(64));+ await saved(root, agentConfig('agent'));+ // A complete copy of the agent's configuration used to read as a second,+ // competing watcher; an empty one used to abort the listing outright.+ await saved(join(watchers, '.launch-copy'), agentConfig('agent'));+ await saved(join(watchers, '.launch-empty'), '');+ await saved(join(watchers, 'launch-legacy'), '{"session":');++ expect(await run(dir, RESOLVE_STATE_ROOT, ['c'.repeat(64), 'sdk-watchers', 'agent'])).toBe(root);+});++const keyedName = (identity: string) => createHash('sha256').update(identity).digest('hex');++it('reads only the agent’s own root while it holds a configuration', async () => {+ const dir = await home();+ const watchers = join(dir, '.local/state/switch/sdk-watchers');+ const root = join(watchers, keyedName('agent'));+ await saved(root, agentConfig('agent'));+ // Either neighbour would fail a listing: one is unreadable, the other claims+ // the same agent. Neither is looked at.+ await saved(join(watchers, 'a'.repeat(64)), '{"session":');+ await saved(join(watchers, 'b'.repeat(64)), agentConfig('agent'));++ expect(await run(dir, RESOLVE_STATE_ROOT, [keyedName('agent'), 'sdk-watchers', 'agent'])).toBe(+ root+ );+});++it('adopts a watcher saved under an earlier key when the agent’s own root has none', async () => {+ const dir = await home();+ const watchers = join(dir, '.local/state/switch/sdk-watchers');+ const earlier = join(watchers, 'c'.repeat(64));+ await saved(earlier, agentConfig('agent'));+ await saved(join(watchers, 'd'.repeat(64)), agentConfig('another-agent'));++ expect(await run(dir, RESOLVE_STATE_ROOT, [keyedName('agent'), 'sdk-watchers', 'agent'])).toBe(+ earlier+ );+});++it('gives an agent that never had a watcher its own root', async () => {+ const dir = await home();+ await saved(join(dir, '.local/state/switch/sdk-watchers', 'e'.repeat(64)), agentConfig('other'));++ expect(await run(dir, RESOLVE_STATE_ROOT, [keyedName('agent'), 'sdk-watchers', 'agent'])).toBe(+ join(dir, '.local/state/switch/sdk-watchers', keyedName('agent'))+ );+});++it('keys a session’s root by its id without listing anything', async () => {+ const dir = await home();+ await saved(join(dir, '.local/state/switch/sdk-sessions', 'f'.repeat(64)), '{"session":');++ expect(await run(dir, RESOLVE_STATE_ROOT, ['0'.repeat(64), 'sdk-sessions', 'agent'])).toBe(+ join(dir, '.local/state/switch/sdk-sessions', '0'.repeat(64))+ );+});++it('still refuses two genuine roots claiming one agent', async () => {+ const dir = await home();+ const watchers = join(dir, '.local/state/switch/sdk-watchers');+ await saved(join(watchers, 'd'.repeat(64)), agentConfig('agent'));+ await saved(join(watchers, 'e'.repeat(64)), agentConfig('agent'));++ await expect(+ run(dir, RESOLVE_STATE_ROOT, ['f'.repeat(64), 'sdk-watchers', 'agent'])+ ).rejects.toThrow('Competing saved watchers require explicit cleanup.');+});++it('stages a launch outside the directory its root is listed in', async () => {+ const dir = await home();+ const root = join(dir, '.local/state/switch/sdk-watchers', 'a'.repeat(64));++ const staged = await run(dir, MAKE_LAUNCH_DIR, [root, String(STALE_LAUNCH_MS)]);++ expect(dirname(staged)).toBe(join(dir, '.local/state/switch/sdk-launch'));+ expect((await stat(staged)).mode & 0o777).toBe(0o700);+ expect((await stat(dirname(staged))).mode & 0o777).toBe(0o700);+});++it('removes what abandoned launches left, and nothing still in use', async () => {+ const dir = await home();+ const state = join(dir, '.local/state/switch');+ const watchers = join(state, 'sdk-watchers');+ const root = join(watchers, 'a'.repeat(64));+ await saved(root, agentConfig('agent'));+ await age(root, 2 * STALE_LAUNCH_MS);+ const staleStaged = join(state, 'sdk-launch/launch-stale');+ const freshStaged = join(state, 'sdk-launch/launch-fresh');+ const staleDotted = join(watchers, '.launch-stale');+ const staleLegacy = join(watchers, 'launch-stale');+ const freshDotted = join(watchers, '.launch-fresh');+ for (const path of [staleStaged, freshStaged, staleDotted, staleLegacy, freshDotted])+ await saved(path, agentConfig('agent'));+ for (const path of [staleStaged, staleDotted, staleLegacy]) await age(path, 2 * STALE_LAUNCH_MS);++ await run(dir, MAKE_LAUNCH_DIR, [root, String(STALE_LAUNCH_MS)]);++ for (const path of [staleStaged, staleDotted, staleLegacy]) expect(existsSync(path)).toBe(false);+ for (const path of [freshStaged, freshDotted, root]) expect(existsSync(path)).toBe(true);+});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/state-roots.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/state-roots.tsnew file mode 100644index 000000000..944b3b33a--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/state-roots.ts@@ -0,0 +1,102 @@+import { READ_JSON } from './remote-json';++/**+ * Which entries under `sdk-watchers` and `sdk-sessions` are state roots.+ *+ * Several readers find an agent's root by listing one of those directories and+ * reading every entry's `config.json`. Earlier builds staged each launch's+ * configuration in a scratch directory beside the roots (`.launch-*`, and+ * before that `launch-*`), and one left behind by an interrupted launch holds+ * either a half-written file or a complete copy of an agent's configuration.+ * Read as a root, the first breaks the listing and the second makes the agent+ * look like it has two competing watchers. A root is named by a hash, so+ * neither prefix can belong to one.+ */+export function isStateRootName(name: string): boolean {+ return !name.startsWith('.') && !name.startsWith('launch-');+}++/** `isStateRoot(name)` for scripts run with `node -e` on an execution host. */+export const IS_STATE_ROOT = String.raw`+const isStateRoot = (name) => !name.startsWith('.') && !name.startsWith('launch-');+`;++/**+ * How long a launch's staged configuration may sit before it is taken for one+ * a launch abandoned. A launch reads it within seconds; the hour is margin.+ */+export const STALE_LAUNCH_MS = 60 * 60 * 1000;++/**+ * Makes a private directory to stage one launch's configuration in, and prints+ * its path. It lives in `sdk-launch`, beside `sdk-watchers` and `sdk-sessions`+ * rather than inside either, so no reader of those directories ever meets it.+ *+ * A launch removes its own directory when it finishes, but not one whose SSH+ * connection dropped first. Each staged file carries the agent's credentials,+ * so every launch also removes what abandoned launches left: in `sdk-launch`,+ * and in the directory this root sits in, from the builds that staged there.+ *+ * Arguments: the state root being launched, and the staleness threshold in ms.+ */+export const MAKE_LAUNCH_DIR = String.raw`+const fs = require('node:fs'), path = require('node:path');+const [root, staleArg] = process.argv.slice(1);+const cutoff = Date.now() - Number(staleArg);+const sweep = (directory, abandoned) => {+ let names;+ try { names = fs.readdirSync(directory); }+ catch (e) { if (e.code === 'ENOENT') return; throw e; }+ for (const name of names) {+ if (!abandoned(name)) continue;+ const entry = path.join(directory, name);+ let stat;+ try { stat = fs.statSync(entry); }+ catch (e) { if (e.code === 'ENOENT') continue; throw e; }+ if (stat.mtimeMs < cutoff) fs.rmSync(entry, { recursive: true, force: true });+ }+};+const kind = path.dirname(root);+const staging = path.join(path.dirname(kind), 'sdk-launch');+fs.mkdirSync(staging, { recursive: true, mode: 0o700 });+sweep(staging, () => true);+sweep(kind, (name) => name.startsWith('.launch-') || name.startsWith('launch-'));+console.log(fs.mkdtempSync(path.join(staging, 'launch-')));+`;++/**+ * `watcherRoot(base, identity)` for scripts run with `node -e`: an agent's+ * watcher state root under `base`, the `sdk-watchers` directory.+ *+ * The root is named by a hash of the agent's identity, so that one directory+ * is read and no other. Only when it holds no configuration is the directory+ * listed, to adopt a watcher saved under an earlier key rather than strand its+ * journal; two such roots claiming one agent are an error rather than a guess.+ * An agent that has never had a watcher gets the keyed path.+ */+export const WATCHER_ROOT = String.raw`${READ_JSON}${IS_STATE_ROOT}+const watcherRoot = (base, identity) => {+ const fs = require('node:fs'), path = require('node:path');+ const keyed = path.join(base, require('node:crypto').createHash('sha256').update(identity).digest('hex'));+ if (fs.existsSync(path.join(keyed, 'config.json')) || !fs.existsSync(base)) return keyed;+ const saved = fs.readdirSync(base).filter(isStateRoot).filter((name) => {+ try { return readJson(path.join(base, name, 'config.json')).session.agentId === identity; }+ catch (e) { if (e.code === 'ENOENT') return false; throw e; }+ });+ if (saved.length > 1) throw new Error('Competing saved watchers require explicit cleanup.');+ return saved.length ? path.join(base, saved[0]) : keyed;+};+`;++/**+ * Prints the state root for a launch: a session's is keyed by its id, and a+ * watcher's is found by `watcherRoot`.+ *+ * Arguments: the root's key, the directory kind, and the agent identity.+ */+export const RESOLVE_STATE_ROOT = String.raw`${WATCHER_ROOT}+const path = require('node:path');+const [key, kind, identity] = process.argv.slice(1);+const base = path.join(require('node:os').homedir(), '.local', 'state', 'switch', kind);+console.log(kind === 'sdk-watchers' ? watcherRoot(base, identity) : path.join(base, key));+`;diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.test.tsindex bc9b55d3c..f15dd13d2 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.test.ts@@ -69,6 +69,29 @@ it('reports a watcher standing down rather than leaving it to read as a crash',},});});+it('reports the one watcher past launches that were abandoned beside it', async () => {+ const { home } = await fixture('agent');+ const watchers = join(home, '.local/state/switch/sdk-watchers');+ await mkdir(join(watchers, '.launch-copy'));+ await writeFile(+ join(watchers, '.launch-copy/config.json'),+ JSON.stringify({ session: { agentId: 'agent' } })+ );+ await mkdir(join(watchers, 'launch-empty'));+ await writeFile(join(watchers, 'launch-empty/config.json'), '');+ expect(await inspect(home, 'status')).toHaveLength(1);+});+it('reads the agent’s own root and no other while it has one', async () => {+ const home = await mkdtemp(join(tmpdir(), 'watcher-inspect-'));+ roots.push(home);+ const watchers = join(home, '.local/state/switch/sdk-watchers');+ const root = join(watchers, createHash('sha256').update('agent').digest('hex'));+ await mkdir(root, { recursive: true });+ await writeFile(join(root, 'config.json'), JSON.stringify({ session: { agentId: 'agent' } }));+ await mkdir(join(watchers, 'unreadable'));+ await writeFile(join(watchers, 'unreadable/config.json'), '{"session":');+ expect(await inspect(home, 'status')).toHaveLength(1);+});it('does not expose another agent’s status or logs', async () => {const { home, root } = await fixture('another-agent');await writeFile(join(root, 'supervisor/worker.log'), 'Other agent log');diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.tsindex ae7db4c5c..9eb64de46 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.ts@@ -1,7 +1,7 @@-import { READ_JSON } from './remote-json';+import { IS_STATE_ROOT, WATCHER_ROOT } from './state-roots';/** Runs on the execution host; paths are resolved there and never supplied by the renderer. */-export const inspectWatchers = String.raw`${READ_JSON}+export const inspectWatchers = String.raw`${WATCHER_ROOT}const fs=require('node:fs'), path=require('node:path'), cp=require('node:child_process');const directory=path.join(require('node:os').homedir(),'.local','state','switch','sdk-watchers');const read=p=>{try{return readJson(p)}catch(e){if(e.code==='ENOENT')return null;throw e}};@@ -17,8 +17,8 @@ const tail=p=>{}catch(e){if(e.code==='ENOENT')return '';throw e}finally{if(fd!==undefined)fs.closeSync(fd)}};const result=[], logs=[];-if(fs.existsSync(directory))for(const name of fs.readdirSync(directory)){- const root=path.join(directory,name),config=read(path.join(root,'config.json'));+for(const root of [watcherRoot(directory,process.argv[1])]){+ const config=read(path.join(root,'config.json'));if(config?.session.agentId!==process.argv[1])continue;if(process.argv[2]==='logs'){for(const file of ['supervisor.log','supervisor/worker.log']){@@ -40,7 +40,6 @@ if(fs.existsSync(directory))for(const name of fs.readdirSync(directory)){pid,supervisorPid,buildHash,takenOver:read(path.join(root,'taken-over.json')),failure:pid?null:read(path.join(root,'supervisor','failure.json'))?.message??null});}-if(result.length>1)throw new Error('Competing saved watchers require explicit cleanup.');console.log(JSON.stringify(process.argv[2]==='logs'?logs.join('\n\n'):result));`;@@ -49,6 +48,6 @@ console.log(JSON.stringify(process.argv[2]==='logs'?logs.join('\n\n'):result));* key and any saved under an earlier one. More than one root is an error to run* on but not to remove, so unlike the read above this takes them all.*/-export const removeWatcherRoots = String.raw`const fs=require('node:fs'),path=require('node:path');const identity=process.argv[1];const base=path.join(require('node:os').homedir(),'.local','state','switch','sdk-watchers');const roots=new Set([path.join(base,require('node:crypto').createHash('sha256').update(identity).digest('hex'))]);if(fs.existsSync(base))for(const name of fs.readdirSync(base)){try{if(JSON.parse(fs.readFileSync(path.join(base,name,'config.json'),'utf8')).session.agentId===identity)roots.add(path.join(base,name))}catch(e){if(e.code!=='ENOENT')throw e}}for(const root of roots)fs.rmSync(root,{recursive:true,force:true})`;+export const removeWatcherRoots = String.raw`${IS_STATE_ROOT}const fs=require('node:fs'),path=require('node:path');const identity=process.argv[1];const base=path.join(require('node:os').homedir(),'.local','state','switch','sdk-watchers');const roots=new Set([path.join(base,require('node:crypto').createHash('sha256').update(identity).digest('hex'))]);if(fs.existsSync(base))for(const name of fs.readdirSync(base).filter(isStateRoot)){try{if(JSON.parse(fs.readFileSync(path.join(base,name,'config.json'),'utf8')).session.agentId===identity)roots.add(path.join(base,name))}catch(e){if(e.code!=='ENOENT')throw e}}for(const root of roots)fs.rmSync(root,{recursive:true,force:true})`;export const waitForWatcherStop = String.raw`const fs=require('node:fs'),path=require('node:path');const files=['shared-owner.lock','supervisor/owner.json'];const alive=file=>{try{const pid=JSON.parse(fs.readFileSync(path.join(process.argv[1],file),'utf8')).pid;if(!Number.isSafeInteger(pid)||pid<=0)throw new Error('Invalid watcher PID');process.kill(pid,0);return true}catch(e){if(['ENOENT','ESRCH'].includes(e.code))return false;throw e}};(async()=>{for(let i=0;i<100;i++){if(!files.some(alive))return;await new Promise(r=>setTimeout(r,200))}throw new Error('The shared watcher has not stopped; retry after checking its log.')})().catch(e=>{console.error(e.message);process.exitCode=1})`;