The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(desktop): port the bot-mode suite off the .mjs vm harness
Brooklyn Nicholsond3df1a36a8cd
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 1ecf88c71ba..daef129468d 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -69,9 +69,8 @@"check:test:ui": "npm run test:ui","check:test:desktop:platforms": "npm run test:desktop:platforms","check:test:desktop:all": "npm run test:desktop:all",- "check:test:plugins": "node --test src/plugins/*/tests/*.test.mjs","check:lint": "npm run typecheck && npm run lint",- "check": "npm run check:lint && npm run test:ui && npm run test:desktop:platforms && npm run test:desktop:all && npm run check:test:plugins",+ "check": "npm run check:lint && npm run test:ui && npm run test:desktop:platforms && npm run test:desktop:all","test:e2e": "npm run build && playwright test e2e/","test:e2e:visual": "npm run build && WLR_BACKENDS=headless WLR_NO_HARDWARE_CURSORS=1 cage -- npx playwright test e2e/ --reporter=list","test:e2e:update-snapshots": "npm run build && WLR_BACKENDS=headless WLR_NO_HARDWARE_CURSORS=1 cage -- npx playwright test e2e/ --reporter=list --update-snapshots",diff --git a/apps/desktop/src/plugins/hermes-bots/avatar.face-clock.test.ts b/apps/desktop/src/plugins/hermes-bots/avatar.face-clock.test.tsnew file mode 100644index 00000000000..f17ae64d59a--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/avatar.face-clock.test.ts@@ -0,0 +1,315 @@+/**+ * The shared face clock: ONE animation loop for every mounted math face.+ *+ * A large roster mounts hundreds of faces, so the clock must not burn frames+ * (or 1Hz whole-document shadow walks) on faces nobody can see. It therefore+ * parks itself whenever there is nothing worth animating — no faces mounted,+ * or none intersecting — and is woken by exactly two events: a `BotFace`+ * render re-entering `startFaceClock`, and a face scrolling into view.+ *+ * Newer desktops delegate scheduling to the SDK's `createBudgetedLoop`+ * (15fps budget, hidden/minimized pause, dormancy, teardown); older shells+ * fall back to the hand-rolled rAF path. Both are exercised here, because the+ * fallback is what every un-upgraded install runs.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const { budgetedLoopMock } = vi.hoisted(() => ({ budgetedLoopMock: { impl: undefined as unknown } }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ blobatarSvg: undefined,+ // A live binding on the real SDK; the getter lets one test file cover both+ // the budgeted-loop path and the older hand-rolled one.+ get createBudgetedLoop() {+ return budgetedLoopMock.impl+ },+ host: { state: { connectionId: { get: () => 'local' } } },+ profileColor: () => '#8b5cf6',+ PROFILE_SWATCHES: [],+ queryClient: undefined,+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++interface ObserverEntry {+ isIntersecting: boolean+ target: Element+}++/** The live fake observer, so a test can drive visibility changes. */+let observer: FakeIntersectionObserver | null = null++class FakeIntersectionObserver {+ callback: (entries: ObserverEntry[]) => void+ disconnected = false+ observed = new Set<Element>()++ constructor(callback: (entries: ObserverEntry[]) => void) {+ this.callback = callback+ observer = this+ }++ disconnect() {+ this.disconnected = true+ this.observed.clear()+ }++ emit(entries: ObserverEntry[]) {+ this.callback(entries)+ }++ observe(element: Element) {+ this.observed.add(element)+ }++ unobserve(element: Element) {+ this.observed.delete(element)+ }+}++let frames = new Map<number, (now: number) => void>()+let frameSeq = 0+let now = 0++/** Run every frame scheduled so far and advance the clock. */+function pump(advance = 100) {+ now += advance++ const pending = [...frames.values()]++ frames.clear()++ for (const frame of pending) {+ frame(now)+ }+}++function mountFace() {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')++ svg.setAttribute('data-hb-math', '1')+ document.body.append(svg)++ return svg+}++async function loadClock() {+ vi.resetModules()++ return import('./avatar')+}++beforeEach(() => {+ frames = new Map()+ frameSeq = 0+ now = 0+ observer = null+ budgetedLoopMock.impl = undefined+ document.body.innerHTML = ''+ delete window.__hbFaceClock+ vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver)++ window.requestAnimationFrame = (callback: FrameRequestCallback) => {+ frameSeq += 1+ frames.set(frameSeq, callback)++ return frameSeq+ }++ window.cancelAnimationFrame = (id: number) => {+ frames.delete(id)+ }+})++afterEach(() => {+ window.__hbFaceClock?.stop()+ vi.unstubAllGlobals()+})++describe('the hand-rolled rAF path (older shells)', () => {+ it('parks itself when no faces are mounted', async () => {+ const { startFaceClock } = await loadClock()++ startFaceClock()+ expect(frames.size).toBe(1)++ pump()+ expect(frames.size).toBe(0)+ })++ it('wakes a parked clock when a face mounts', async () => {+ const { startFaceClock } = await loadClock()++ startFaceClock()+ pump()+ expect(frames.size).toBe(0)++ mountFace()+ // The BotFace render path — re-entry is the wake signal.+ startFaceClock()+ expect(frames.size).toBe(1)+ })++ it('parks when every face scrolls out and the observer wakes it back', async () => {+ const { startFaceClock } = await loadClock()+ const face = mountFace()++ startFaceClock()+ pump()+ // Observed but not yet intersecting: nothing visible, so park.+ expect(frames.size).toBe(0)++ observer!.emit([{ isIntersecting: true, target: face }])+ expect(frames.size).toBe(1)++ pump()+ expect(frames.size).toBe(1)++ observer!.emit([{ isIntersecting: false, target: face }])+ pump()+ pump()+ expect(frames.size).toBe(0)+ })++ it('stops cleanly and can be restarted', async () => {+ const { startFaceClock, stopFaceClock } = await loadClock()+ const face = mountFace()++ startFaceClock()+ observer!.emit([{ isIntersecting: true, target: face }])+ pump()+ expect(frames.size).toBe(1)++ const first = observer!++ stopFaceClock()+ expect(frames.size).toBe(0)+ expect(first.disconnected).toBe(true)+ expect(window.__hbFaceClock).toBeUndefined()++ // A fresh start after teardown re-initializes rather than hitting a dead+ // handle left on `window`.+ startFaceClock()+ expect(frames.size).toBe(1)+ })++ it('stops the whole-document walk when a face unmounts', async () => {+ const { startFaceClock } = await loadClock()+ const face = mountFace()++ startFaceClock()+ observer!.emit([{ isIntersecting: true, target: face }])+ pump()++ face.remove()+ // The 1Hz rescan drops the node from both caches and parks the clock.+ pump(1500)+ pump()++ expect(observer!.observed.has(face)).toBe(false)+ expect(frames.size).toBe(0)+ })+})++describe('the SDK budgeted-loop path', () => {+ interface CapturedLoop {+ draw: (now: number) => void+ idleWhen: () => boolean+ }++ function captureLoop() {+ const captured: Partial<CapturedLoop> = {}+ const calls = { created: 0, dispose: 0, fps: 0, wake: 0 }++ budgetedLoopMock.impl = (draw: (now: number) => void, options: { fps: number; idleWhen: () => boolean }) => {+ calls.created += 1+ calls.fps = options.fps+ captured.draw = draw+ captured.idleWhen = options.idleWhen++ return {+ dispose: () => {+ calls.dispose += 1+ },+ isDormant: () => false,+ wake: () => {+ calls.wake += 1+ }+ }+ }++ return { calls, captured }+ }++ it('hands the paint to the SDK loop and schedules no rAF of its own', async () => {+ const { calls } = captureLoop()+ const { startFaceClock } = await loadClock()++ mountFace()+ startFaceClock()++ expect(calls.fps).toBe(15)+ expect(frames.size).toBe(0)+ })++ it('reports idleness from visible-face state and wakes on visibility', async () => {+ const { calls, captured } = captureLoop()+ const { startFaceClock } = await loadClock()+ const face = mountFace()++ startFaceClock()++ // The first draw performs the initial scan + observation.+ captured.draw!(1000)+ expect(captured.idleWhen!()).toBe(true)++ observer!.emit([{ isIntersecting: true, target: face }])+ expect(captured.idleWhen!()).toBe(false)+ expect(calls.wake).toBeGreaterThanOrEqual(1)++ // Re-entry (a BotFace mount) wakes rather than re-initializing.+ startFaceClock()+ expect(calls.wake).toBeGreaterThanOrEqual(2)+ })++ it('disposes the loop and drops the window handle on stop', async () => {+ const { calls } = captureLoop()+ const { startFaceClock, stopFaceClock } = await loadClock()++ mountFace()+ startFaceClock()++ const live = observer!++ stopFaceClock()++ expect(calls.dispose).toBe(1)+ expect(live.disconnected).toBe(true)+ expect(window.__hbFaceClock).toBeUndefined()+ })++ it('keeps a single clock across plugin loads', async () => {+ // Parked on `window` so a second load adopts the running clock instead of+ // starting a rival loop.+ const { calls } = captureLoop()+ const first = await loadClock()++ mountFace()+ first.startFaceClock()++ const second = await loadClock()++ second.startFaceClock()++ expect(calls.created).toBe(1)+ expect(calls.wake).toBeGreaterThanOrEqual(1)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/avatar.test.tsx b/apps/desktop/src/plugins/hermes-bots/avatar.test.tsxnew file mode 100644index 00000000000..d911f3ad99e--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/avatar.test.tsx@@ -0,0 +1,206 @@+/**+ * The avatar face: blobatar shape strings, the markup they render to, and the+ * catchlight polarity fix.+ *+ * Shape strings are stored per bot and must round-trip forever —+ * `blobatar[:seed[:kind]]`, where an unlocked seed follows the bot's name and+ * an unknown silhouette is ignored rather than trusted. The silhouette is+ * pinned by handing the library a TRAIT position inside its frozen band, so+ * the band a kind lands in is a stored-appearance contract, not an+ * implementation detail.+ *+ * Catchlight (image14 report, Aug 2026): the sparkle's contrast follows the+ * PUPIL, not the body. Dark bodies flip the pupils to light cream, and a white+ * catchlight on a cream pupil is invisible — maroon/ink/oxblood avatars looked+ * like they had "no dots in their eyes".+ */++import { render } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { blobatarSvgMock } = vi.hoisted(() => ({ blobatarSvgMock: vi.fn() }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ blobatarSvg: (seed: string, opts: unknown) => blobatarSvgMock(seed, opts) as string,+ createBudgetedLoop: undefined,+ host: { state: { connectionId: { get: () => 'local' } } },+ profileColor: (name: string) => (name === 'inbox-triage' ? '#38bdf8' : '#8b5cf6'),+ PROFILE_SWATCHES: ['#38bdf8', '#8b5cf6'],+ queryClient: undefined,+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++/** The library's frozen band per silhouette (gen2 thresholds). */+const BANDS: Record<string, [number, number]> = {+ boxy: [0.48, 0.6],+ capsule: [0.6, 0.7],+ cloud: [0.79, 0.86],+ droplet: [0.86, 0.915],+ hexagon: [0.915, 0.95],+ nub: [0.7, 0.79],+ organic: [0.22, 0.48],+ round: [0, 0.22],+ sun: [0.95, 0.98],+ triangle: [0.98, 1]+}++interface BlobOptions {+ size: number+ traits?: { shape: number }+}++const lastBlobCall = () => blobatarSvgMock.mock.calls.at(-1) as [string, BlobOptions]++beforeEach(() => {+ vi.clearAllMocks()+ blobatarSvgMock.mockReturnValue('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>')+})++describe('blob shape strings round-trip through parse/build', () => {+ it('recognizes only the blobatar family', async () => {+ const { isBlobShape } = await import('./avatar')++ expect(isBlobShape('blobatar')).toBe(true)+ expect(isBlobShape('blobatar:seed123')).toBe(true)+ expect(isBlobShape('blobatar::sun')).toBe(true)+ expect(isBlobShape('circle')).toBe(false)+ expect(isBlobShape(undefined)).toBe(false)+ })++ it('parses the seed/silhouette segments, ignoring an unknown silhouette', async () => {+ const { parseBlobShape } = await import('./avatar')++ // Unlocked: the seed follows the name.+ expect(parseBlobShape('blobatar', 'inbox-triage')).toEqual({ kind: '', seed: 'inbox-triage', seedPart: '' })+ expect(parseBlobShape('blobatar:abc123', 'inbox-triage')).toEqual({+ kind: '',+ seed: 'abc123',+ seedPart: 'abc123'+ })+ expect(parseBlobShape('blobatar::cloud', 'inbox-triage')).toEqual({+ kind: 'cloud',+ seed: 'inbox-triage',+ seedPart: ''+ })+ expect(parseBlobShape('blobatar:abc:mystery', 'x').kind).toBe('')+ })++ it('rebuilds every segment combination', async () => {+ const { blobShapeString } = await import('./avatar')++ expect(blobShapeString('', '')).toBe('blobatar')+ expect(blobShapeString('abc', '')).toBe('blobatar:abc')+ expect(blobShapeString('abc', 'sun')).toBe('blobatar:abc:sun')+ expect(blobShapeString('', 'sun')).toBe('blobatar::sun')+ })+})++describe('rendering a blob face', () => {+ it('tags the markup data-bot-face so the roster PNG backfill can find it', async () => {+ // pushLocalAvatars → rasterizeSvgToPng queries `svg[data-bot-face=…]`;+ // without the tag a vector face never reaches the inter-agent notices.+ const { BotFace } = await import('./avatar')+ const { container } = render(<BotFace color="#38bdf8" name="inbox-triage" shape="blobatar" size={56} />)++ expect(container.querySelector('svg[data-bot-face="inbox-triage"]')).toBeTruthy()++ const [seed, opts] = lastBlobCall()++ expect(seed).toBe('inbox-triage')+ expect(opts.size).toBe(56)+ // No pinned silhouette means no traits at all — the library picks.+ expect('traits' in opts).toBe(false)+ })++ it('passes the locked seed and the pinned silhouette’s trait', async () => {+ const { BotFace } = await import('./avatar')++ render(<BotFace color="#38bdf8" name="inbox-triage" shape="blobatar:abc:sun" size={32} />)++ const [seed, opts] = lastBlobCall()++ expect(seed).toBe('abc')+ expect(opts.traits?.shape).toBeGreaterThanOrEqual(BANDS.sun[0])+ expect(opts.traits?.shape).toBeLessThan(BANDS.sun[1])+ })++ it('puts every silhouette inside its own frozen band', async () => {+ const { BLOB_KINDS, BotFace } = await import('./avatar')++ for (const kind of BLOB_KINDS) {+ render(<BotFace color="#38bdf8" name="agent" shape={`blobatar::${kind}`} size={32} />)++ const trait = lastBlobCall()[1].traits?.shape++ expect(typeof trait, kind).toBe('number')+ expect(trait, kind).toBeGreaterThanOrEqual(BANDS[kind][0])+ expect(trait, kind).toBeLessThan(BANDS[kind][1])+ }+ })++ it('falls back to the legacy math face when the renderer throws', async () => {+ blobatarSvgMock.mockImplementation(() => {+ throw new Error('boom')+ })++ const { BotFace } = await import('./avatar')+ const { container } = render(<BotFace color="#38bdf8" name="agent" shape="blobatar" size={32} />)++ expect(container.querySelector('svg[data-hb-math]')).toBeTruthy()+ })+})++describe('catchlight contrast follows the pupil, not the body', () => {+ const catchlights = (container: HTMLElement) =>+ ['l', 'r'].map(side => container.querySelector(`[data-hb-hl-${side}]`)?.getAttribute('fill'))++ it('puts a DARK sparkle on the cream pupils of a dark body', async () => {+ const { BotFace } = await import('./avatar')+ const { container } = render(<BotFace color="#3b0910" name="oxblood" shape="circle" />)++ expect(catchlights(container)).toEqual(['rgba(0,0,0,0.6)', 'rgba(0,0,0,0.6)'])+ })++ it('keeps the white sparkle on the dark pupils of a light body', async () => {+ const { BotFace } = await import('./avatar')+ const { container } = render(<BotFace color="#f5e6c8" name="cream" shape="circle" />)++ expect(catchlights(container)).toEqual(['rgba(255,255,255,0.85)', 'rgba(255,255,255,0.85)'])+ })+})++// Last: re-mocking the SDK re-links the whole avatar graph, so anything after+// this would be running against the swapped module.+describe('an SDK that predates blobatarSvg', () => {+ it('renders the legacy deterministic shape instead of nothing', async () => {+ vi.resetModules()+ vi.doMock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ blobatarSvg: undefined,+ createBudgetedLoop: undefined,+ host: { state: { connectionId: { get: () => 'local' } } },+ profileColor: () => '#8b5cf6',+ PROFILE_SWATCHES: [],+ queryClient: undefined,+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+ })++ const { BotFace, defaultShapeFor } = await import('./avatar')+ const { container } = render(<BotFace color="#38bdf8" name="agent" shape="blobatar" size={32} />)++ expect(container.querySelector('svg[data-hb-math]')?.getAttribute('data-hb-shape')).toBe(defaultShapeFor('agent'))+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/bot-delete.test.ts b/apps/desktop/src/plugins/hermes-bots/bot-delete.test.tsnew file mode 100644index 00000000000..fcacba31d4b--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/bot-delete.test.ts@@ -0,0 +1,254 @@+/**+ * Deleting a bot deletes its Hermes profile, then everything plugin-local+ * that would otherwise leave stale appearance/unread data behind.+ *+ * `host.deleteProfile` is preferred whenever the Desktop build ships it: it+ * routes through the Electron-intercepted REST delete, which tears the bot's+ * pool backend down FIRST. The older `cli.exec` path bypasses that+ * interception, so a backend the roster's hover pre-warm just woke (a+ * right-click hovers the row!) holds the profile dir open and the CLI's rmtree+ * races it — that is the "can't delete a bot" error (hermes-agent#52279).+ *+ * Ported from tests/bot-delete.test.mjs, which ran the whole plugin.js bundle+ * under `vm`.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import type { ProfileRoute, RosterRow } from './types'++const { forgetSessionUnread, invalidateQueries, newChat, overrides, request, stateAtoms } = vi.hoisted(() => {+ const makeAtom = <T>(initial: T) => {+ let value = initial++ return {+ get: () => value,+ listen: () => () => undefined,+ set: (next: T) => {+ value = next+ }+ }+ }++ return {+ forgetSessionUnread: vi.fn(),+ invalidateQueries: vi.fn(),+ newChat: vi.fn(),+ // Read through a Proxy below so a test can make a host verb *absent* —+ // `typeof host.deleteProfile === 'function'` is the whole feature gate.+ overrides: {} as Record<string, unknown>,+ request: vi.fn(),+ stateAtoms: {+ connectionId: makeAtom('local'),+ focusedSessionOwner: makeAtom<{ connectionId: string; profile: string }>({+ connectionId: 'local',+ profile: 'default'+ }),+ profile: makeAtom('default')+ }+ }+})++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ overrides.newChat = newChat+ overrides.request = request+ overrides.state = { ...sdk.host.state, ...stateAtoms }++ return {+ ...sdk,+ forgetSessionUnread,+ host: new Proxy(sdk.host, {+ get: (target, prop) => (prop in overrides ? overrides[prop as string] : Reflect.get(target, prop))+ }),+ queryClient: { invalidateQueries }+ }+})++interface StorageOp {+ key: string+ op: 'remove' | 'set'+ value?: unknown+}++const remoteRoute: ProfileRoute = {+ connectionId: 'source-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+}++async function loadModules() {+ vi.resetModules()++ const ops: StorageOp[] = []+ const [data, profileOps, shared] = await Promise.all([import('./data'), import('./profile-ops'), import('./shared')])++ shared.setPluginCtx({+ storage: {+ get: () => null,+ remove: (key: string) => {+ ops.push({ key, op: 'remove' })+ },+ set: (key: string, value: unknown) => {+ ops.push({ key, op: 'set', value })+ }+ }+ } as unknown as Parameters<typeof shared.setPluginCtx>[0])++ return { data, ops, profileOps }+}++// Pay the graph's cold transform once, up front. `loadModules` re-imports on+// every test, and charging that one-time cost to whichever test happens to run+// first makes it time out under a loaded runner.+beforeAll(async () => {+ await loadModules()+}, 60_000)++beforeEach(() => {+ vi.clearAllMocks()+ // Absent by default: the older-desktop shape. Tests opt in to the SDK verb.+ overrides.deleteProfile = undefined+ request.mockResolvedValue({ blocked: false, code: 0, output: 'deleted' })+ stateAtoms.connectionId.set('local')+ stateAtoms.focusedSessionOwner.set({ connectionId: 'local', profile: 'default' })+ stateAtoms.profile.set('default')+})++describe('the SDK delete verb is preferred over the CLI', () => {+ it('deletes through host.deleteProfile and never shells out', async () => {+ const deleteProfile = vi.fn()++ overrides.deleteProfile = deleteProfile++ const { profileOps } = await loadModules()++ await profileOps.deleteBot({ name: 'researcher' } as RosterRow)++ expect(deleteProfile.mock.calls).toEqual([['researcher']])+ expect(request.mock.calls.filter(([method]) => method === 'cli.exec')).toHaveLength(0)+ })++ it('hands a source-scoped row its whole route, targetProfile included', async () => {+ const deleteProfile = vi.fn()++ overrides.deleteProfile = deleteProfile++ const { profileOps } = await loadModules()++ await profileOps.deleteBot({ name: 'worker', route: remoteRoute, sourceScoped: true } as RosterRow)++ expect(deleteProfile.mock.calls[0][0]).toMatchObject(remoteRoute)+ })++ it('falls back to the non-interactive profile CLI on an older desktop', async () => {+ const { profileOps } = await loadModules()++ await profileOps.deleteBot({ name: 'researcher' } as RosterRow)++ const exec = request.mock.calls.filter(([method]) => method === 'cli.exec')++ expect(exec[0][1]).toEqual({ argv: ['profile', 'delete', 'researcher', '--yes'] })+ })+})++describe('deletes that must not happen', () => {+ it('rejects an alias whose backend target is the default profile', async () => {+ const deleteProfile = vi.fn()++ overrides.deleteProfile = deleteProfile++ const { profileOps } = await loadModules()++ await expect(+ profileOps.deleteBot({+ name: 'worker',+ route: { ...remoteRoute, targetProfile: 'default' },+ sourceScoped: true+ } as RosterRow)+ ).rejects.toThrow(/default profile cannot be deleted/i)++ expect(deleteProfile).not.toHaveBeenCalled()+ expect(request.mock.calls.some(([method]) => method === 'cli.exec')).toBe(false)+ })++ it('fails a source-scoped delete closed rather than shelling out', async () => {+ const { profileOps } = await loadModules()++ await expect(+ profileOps.deleteBot({+ name: 'worker',+ route: { ...remoteRoute, targetProfile: 'worker' },+ sourceScoped: true+ } as RosterRow)+ ).rejects.toThrow(/source-scoped profile deletion requires host\.deleteProfile/i)++ expect(request.mock.calls.some(([method]) => method === 'cli.exec')).toBe(false)+ })+})++describe('plugin-local state is cleaned up behind the delete', () => {+ it('commits the source-scoped bot-meta-v2 snapshot atomically', async () => {+ overrides.deleteProfile = vi.fn()++ const { data, ops, profileOps } = await loadModules()++ data.$botMeta.set({+ 'source-a::worker': { title: 'Worker' },+ 'source-a::writer': { title: 'Writer' }+ })++ await profileOps.deleteBot({ name: 'worker', route: remoteRoute, sourceScoped: true } as RosterRow)++ expect(ops.slice(-3)).toEqual([+ { key: 'bot-meta-v2-migrated', op: 'remove' },+ { key: 'bot-meta-v2', op: 'set', value: { 'source-a::writer': { title: 'Writer' } } },+ { key: 'bot-meta-v2-migrated', op: 'set', value: true }+ ])+ })++ it('drops meta, unread and selection, then refreshes the roster', async () => {+ const { data, ops, profileOps } = await loadModules()++ data.$botMeta.set({ researcher: { title: 'Research' }, writer: { title: 'Writer' } })+ data.$lastRoster.set([{ name: 'researcher' }, { name: 'writer' }] as RosterRow[])++ const { $selectedBot } = await import('./bot-state')++ $selectedBot.set('researcher')++ await profileOps.deleteBot({+ canonical_session: { id: 'reg-1', resolved_id: 'tip-9' },+ name: 'researcher'+ } as RosterRow)++ expect(data.$botMeta.get().researcher).toBeUndefined()+ // Unread lives in core's store now; both ids because the marker may have+ // been filed under either tip of the chat's compression lineage.+ expect(forgetSessionUnread).toHaveBeenCalledWith(['reg-1', 'tip-9'], 'researcher')+ expect($selectedBot.get()).toBe('default')+ expect(ops.at(-1)?.key).toBe('bot-meta')+ expect((ops.at(-1)?.value as Record<string, unknown>).researcher).toBeUndefined()+ expect(invalidateQueries).toHaveBeenCalledTimes(1)+ })++ it('keeps the active chat when the deleted bot is a same-name twin elsewhere', async () => {+ overrides.deleteProfile = vi.fn()+ stateAtoms.connectionId.set('source-b')+ stateAtoms.focusedSessionOwner.set({ connectionId: 'source-b', profile: 'worker' })+ stateAtoms.profile.set('worker')++ const { profileOps } = await loadModules()++ await profileOps.deleteBot({+ name: 'worker',+ route: { ...remoteRoute, targetProfile: 'worker' },+ sourceScoped: true+ } as RosterRow)++ expect(newChat).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/bot-open-focus-identity.test.ts b/apps/desktop/src/plugins/hermes-bots/bot-open-focus-identity.test.tsnew file mode 100644index 00000000000..09ec244831e--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/bot-open-focus-identity.test.ts@@ -0,0 +1,97 @@+/**+ * First-click home bounce (community report, Aug 2026): clicking a bot whose+ * canonical Bot Chat had been COMPRESSED landed on the Bots home instead of+ * the chat, and only a second click got through.+ *+ * Root cause: openRosterBot claimed the center with the durable registry id,+ * but the session-focus edge that the open itself fired reports the+ * compression-lineage TIP. releaseStaleOpenBotChat compared tip !== registry+ * id, called the claim stale, released it, and the home reasserted over the+ * freshly opened chat. The second click "worked" only because the tip was+ * already focused, so no new focus edge fired to sabotage it.+ *+ * The fix is to carry BOTH identities: openBotCanonicalChat returns+ * registryId + openedId, the claim stores both, and focus on either one keeps+ * it.+ *+ * Ported from tests/bot-open-focus-identity.test.mjs.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RosterRow } from './types'++const { ackStoredSessionId, openBotCanonicalChat } = vi.hoisted(() => ({+ ackStoredSessionId: vi.fn(),+ openBotCanonicalChat: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return { ...sdk, ackStoredSessionId }+})++vi.mock('./canonical-chat', () => ({+ ensureBotMetadata: vi.fn(async () => ({})),+ notifyBotOpenFailure: vi.fn(),+ openBotCanonicalChat,+ prepareBotSource: vi.fn(async () => undefined),+ PROFILE_SESSION_LIST_LIMIT: 200+}))++const { $openBotChat } = await import('./bot-state')+const { openRosterBot } = await import('./roster-actions')+const { releaseStaleOpenBotChat } = await import('./roster-pane')++beforeEach(() => {+ vi.clearAllMocks()+ $openBotChat.set(null)+})++describe('an open claims both identities of the chat it opened', () => {+ it('records the registry row and the lineage tip it actually navigated to', async () => {+ openBotCanonicalChat.mockResolvedValue({ openedId: 'tip-9', registryId: 'reg-1' })++ await openRosterBot({ connectionId: 'local', name: 'ops' } as RosterRow)++ expect($openBotChat.get()).toMatchObject({ openedRegistryId: 'reg-1', openedSessionId: 'tip-9' })+ })+})++describe('focus on either owned identity keeps the claim', () => {+ it('survives the tip focus edge the open itself fires', () => {+ $openBotChat.set({ key: 'k', openedRegistryId: 'reg-1', openedSessionId: 'tip-9' })++ releaseStaleOpenBotChat('tip-9')++ expect($openBotChat.get()).not.toBeNull()+ })++ it('survives focus reported as the durable registry id', () => {+ $openBotChat.set({ key: 'k', openedRegistryId: 'reg-1', openedSessionId: 'tip-9' })++ releaseStaleOpenBotChat('reg-1')++ expect($openBotChat.get()).not.toBeNull()+ })++ it('releases on a genuinely foreign session', () => {+ $openBotChat.set({ key: 'k', openedRegistryId: 'reg-1', openedSessionId: 'tip-9' })++ releaseStaleOpenBotChat('other-session')++ expect($openBotChat.get()).toBeNull()+ })++ it('releases a legacy draft claim as soon as any session takes focus', () => {+ // The newChat fallback has no registry id to compare against, so it only+ // yields once something is actually focused.+ $openBotChat.set({ key: 'k', openedRegistryId: '' })++ releaseStaleOpenBotChat('any')++ expect($openBotChat.get()).toBeNull()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx b/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsxnew file mode 100644index 00000000000..731160a9ab9--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx@@ -0,0 +1,162 @@+/**+ * The bot row's two side effects: pre-warming and opening.+ *+ * Pre-warm is per-row and hover-scoped. Warming the whole roster on paint+ * spun up every profile backend the moment the Bots rail rendered, so the row+ * warms exactly one bot and only once a pointer is actually over it — and a+ * source-scoped row pre-dials its OWN source rather than the active gateway.+ *+ * Opening is delegated whole: the row hands its exact roster row to+ * openRosterBot and does nothing else. It never activates a connection+ * itself, which is what keeps a remote row from resolving into the same-named+ * local bot.+ *+ * Ported from tests/profile-prewarm.test.mjs, which sliced BotRow out of the+ * old plugin.js bundle and rendered it against a hand-built jsx stub.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { fireEvent, render, screen } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { BotRow } from './bot-row'+import type { RosterRow } from './types'++const { ensureAgent, ensureBotMetadata, notifyError, openRosterBot, requestProfile, warmAgent, warmProfile } =+ vi.hoisted(() => ({+ ensureAgent: vi.fn(),+ ensureBotMetadata: vi.fn(),+ notifyError: vi.fn(),+ openRosterBot: vi.fn(),+ requestProfile: vi.fn(),+ warmAgent: vi.fn(),+ warmProfile: vi.fn()+ }))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return {+ ...sdk,+ host: { ...sdk.host, ensureAgent, notifyError, requestProfile, warmAgent, warmProfile }+ }+})++vi.mock('./canonical-chat', () => ({+ ensureBotMetadata,+ notifyBotOpenFailure: vi.fn(),+ openBotCanonicalChat: vi.fn(),+ prepareBotSource: vi.fn(),+ PROFILE_SESSION_LIST_LIMIT: 200+}))++vi.mock('./roster-actions', () => ({ openRosterBot }))++const noop = () => undefined++function renderRow(bot: RosterRow) {+ render(<BotRow bot={bot} onDelete={noop} onEdit={noop} onGroup={noop} />)++ return screen.getByRole('button')+}++beforeEach(() => {+ vi.clearAllMocks()+ ensureBotMetadata.mockResolvedValue({ pinned: true })+ openRosterBot.mockResolvedValue(true)+ requestProfile.mockResolvedValue({})+})++describe('pre-warm is hover-scoped, never roster-wide', () => {+ it('warms nothing on paint and exactly the hovered bot on pointer entry', async () => {+ const row = renderRow({ name: 'alpha' } as RosterRow)++ expect(warmProfile).not.toHaveBeenCalled()++ fireEvent.pointerEnter(row)++ expect(warmProfile.mock.calls).toEqual([['alpha']])+ expect(warmAgent).not.toHaveBeenCalled()+ })++ it('pre-dials a source-scoped row on its own source', async () => {+ const row = renderRow({+ connectionId: 'work',+ connectionLabel: 'Work',+ name: 'research',+ remoteSource: true,+ sourceScoped: true+ } as RosterRow)++ fireEvent.pointerEnter(row)++ expect(warmAgent.mock.calls).toEqual([['work', 'research']])+ expect(warmProfile).not.toHaveBeenCalled()+ })+})++describe('the row delegates the open and claims no activation authority', () => {+ it('hands a remote Connections row to openRosterBot without activating it', async () => {+ const bot = {+ connectionId: 'work',+ connectionLabel: 'Work',+ name: 'research',+ remoteSource: true,+ sourceScoped: true+ } as RosterRow++ fireEvent.click(renderRow(bot))++ expect(ensureAgent).not.toHaveBeenCalled()+ expect(openRosterBot.mock.calls).toEqual([[bot]])+ })++ it('never resolves a remote default into the same-named local bot', async () => {+ const bot = {+ connectionId: 'mac-mini',+ connectionLabel: 'Mac Mini',+ name: 'default',+ remoteSource: true,+ sourceScoped: true+ } as RosterRow++ fireEvent.click(renderRow(bot))++ expect(ensureAgent).not.toHaveBeenCalled()+ expect(openRosterBot.mock.calls[0][0].connectionId).toBe('mac-mini')+ expect(notifyError).not.toHaveBeenCalled()+ })+})++describe('context-menu mutations hydrate the alias first', () => {+ it('reads the backend row before toggling pin, and writes to the alias target', async () => {+ // A non-identity alias (Desktop calls it `worker`, the backend calls it+ // `backend-worker`) must have its CURRENT state hydrated from its own+ // source before the toggle — flipping a locally-assumed value would+ // fight whatever the backend actually holds.+ const bot = {+ connectionId: 'remote-a',+ name: 'worker',+ remoteSource: true,+ route: { connectionId: 'remote-a', mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' },+ sourceScoped: true+ } as RosterRow++ fireEvent.contextMenu(renderRow(bot))+ // The label reads from LOCAL meta (unpinned here); the toggle reads from+ // the hydrated backend row, which says pinned. That divergence is the+ // point — an alias whose state lives elsewhere must not be flipped+ // against a locally-assumed value.+ fireEvent.click(await screen.findByText('Pin to top'))+ await vi.waitFor(() =>+ expect(requestProfile.mock.calls.some(([, method]) => method === 'profiles.configure')).toBe(true)+ )++ expect(ensureBotMetadata).toHaveBeenCalledWith(bot)++ const [route, , params] = requestProfile.mock.calls.find(([, method]) => method === 'profiles.configure')!++ expect(route.profile).toBe('worker')+ expect(params).toMatchObject({ name: 'backend-worker', ui_meta: { 'hermes-bots': { pinned: false } } })+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/bot-state.focused-owner.test.ts b/apps/desktop/src/plugins/hermes-bots/bot-state.focused-owner.test.tsnew file mode 100644index 00000000000..e4400b41464--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/bot-state.focused-owner.test.ts@@ -0,0 +1,149 @@+/**+ * The roster highlight and the Routines tile follow the chat the user is+ * LOOKING AT — the focused session's OWNER (profile + connection) — not the+ * gateway socket's home. Tab focus moves without swapping the socket, so+ * keying off `host.state.profile` highlighted the wrong bot whenever a focused+ * tab showed another profile's chat (community report: Newsanalyst chat open,+ * Hermes highlighted).+ *+ * Newer desktops publish the complete pair as `host.state.focusedSessionOwner`.+ * Older ones expose only `focusedSessionProfile`, a legacy HALF-SHAPE with no+ * source identity: pairing that profile with the ambient connection id+ * manufactures a cross-source owner out of two unrelated atoms, which is how a+ * remote bot got highlighted as "active" on the wrong machine. The fallback+ * therefore fails closed unless the focused profile IS the active profile.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++interface Store<T> {+ get: () => T+ listen: (listener: (value: T) => void) => () => void+}++const { state } = vi.hoisted(() => ({+ state: {+ activeConnectionId: '' as string,+ connectionId: 'source-a',+ focusedProfile: null as null | string,+ focusedOwner: null as null | { authoritative?: boolean; connectionId: string; profile: string },+ profile: 'default'+ }+}))++const store = <T>(read: () => T): Store<T> => ({ get: read, listen: () => () => undefined })++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ host: {+ activeConnectionId: () => state.activeConnectionId,+ state: {+ connectionId: store(() => state.connectionId),+ // Both focus atoms are FEATURE-DETECTED: their absence is the whole+ // signal on an older desktop, so they must be genuinely absent.+ get focusedSessionOwner() {+ return state.focusedOwner ? store(() => state.focusedOwner) : undefined+ },+ get focusedSessionProfile() {+ return state.focusedProfile === null ? undefined : store(() => state.focusedProfile)+ },+ profile: store(() => state.profile)+ }+ },+ queryClient: { invalidateQueries: vi.fn() },+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++/** $focusedBotOwner binds to host.state at module load, so each topology needs+ * a fresh graph. */+async function load() {+ vi.resetModules()++ const [botState, data] = await Promise.all([import('./bot-state'), import('./data')])++ return { ...botState, isActiveRosterBot: data.isActiveRosterBot }+}++beforeEach(() => {+ state.activeConnectionId = ''+ state.connectionId = 'source-a'+ state.focusedOwner = null+ state.focusedProfile = null+ state.profile = 'default'+})++describe('a desktop that publishes the complete focused owner', () => {+ it('uses it verbatim and treats it as authoritative', async () => {+ state.focusedOwner = { connectionId: 'source-b', profile: 'worker' }++ const { $focusedBotOwner, focusedRosterOwner, isActiveRosterBot } = await load()+ const owner = focusedRosterOwner($focusedBotOwner.get())++ expect(owner).toEqual({ authoritative: true, connectionId: 'source-b', name: 'worker' })+ expect(isActiveRosterBot({ connectionId: 'source-b', name: 'worker', remoteSource: true }, owner)).toBe(true)+ // Same name on ANOTHER machine is a different agent.+ expect(isActiveRosterBot({ connectionId: 'source-a', name: 'worker', remoteSource: true }, owner)).toBe(false)+ })+})++describe('a legacy desktop with focusedSessionProfile only', () => {+ it('fails closed rather than pairing foreign focus with the ambient connection', async () => {+ state.focusedProfile = 'worker'+ state.profile = 'default'++ const { $focusedBotOwner, focusedRosterOwner, isActiveRosterBot } = await load()+ const owner = focusedRosterOwner($focusedBotOwner.get())++ expect(owner).toBeNull()+ expect(isActiveRosterBot({ connectionId: 'source-a', name: 'worker', remoteSource: true }, owner)).toBe(false)+ // And nothing else gets highlighted in its place.+ expect(isActiveRosterBot({ name: 'default' }, owner)).toBe(false)+ })++ it('reuses the ambient connection only when focus IS the active profile', async () => {+ state.focusedProfile = 'default'+ state.profile = 'default'++ const { $focusedBotOwner, focusedRosterOwner } = await load()++ // Non-authoritative: it is inferred, not published by the desktop.+ expect(focusedRosterOwner($focusedBotOwner.get())).toEqual({+ authoritative: false,+ connectionId: 'source-a',+ name: 'default'+ })+ })+})++describe('a desktop with neither focus atom', () => {+ it('falls back to the socket home profile', async () => {+ state.profile = 'researcher'+ state.activeConnectionId = 'source-a'+ state.connectionId = ''++ const { $focusedBotOwner, focusedMentionProfile, focusedRosterOwner } = await load()++ expect(focusedMentionProfile()).toBe('researcher')+ expect(focusedRosterOwner($focusedBotOwner.get())).toEqual({+ authoritative: false,+ connectionId: 'source-a',+ name: 'researcher'+ })+ })+})++describe('focusedRosterOwner', () => {+ it('reports nothing for an owner with no profile', async () => {+ const { focusedRosterOwner } = await load()++ expect(focusedRosterOwner(null)).toBeNull()+ expect(focusedRosterOwner({ connectionId: 'source-a', profile: ' ' })).toBeNull()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-chat-adopt-on-conflict.test.ts b/apps/desktop/src/plugins/hermes-bots/canonical-chat-adopt-on-conflict.test.tsnew file mode 100644index 00000000000..0d2829bf655--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-chat-adopt-on-conflict.test.ts@@ -0,0 +1,136 @@+/**+ * ADOPT-BEFORE-MINT (#92473 part 2).+ *+ * Between the registry miss and our eager `session.title` write, another+ * writer can take the canonical title (peer dm minting server-side, a second+ * machine, cross-connection sync). UNIQUE(title) rejects our write with+ * "already in use". Before this fix that rejection was read as "old gateway"+ * and the compat path prompted into OUR stray lazy session — forking the+ * forever chat. Now the mint re-consults the registry and adopts the winner;+ * the stray zero-message session is abandoned to the gateway's pruner.+ *+ * Ported from tests/canonical-chat-adopt-on-conflict.test.mjs.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RosterRow } from './types'++const { hostMock, persistMock, requestForBotMock, saveBotMetaMock } = vi.hoisted(() => ({+ hostMock: { openSession: vi.fn(), request: vi.fn() },+ persistMock: vi.fn(),+ requestForBotMock: vi.fn(),+ saveBotMetaMock: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', () => ({+ BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS: 15_000,+ host: hostMock+}))++vi.mock('./routing', () => ({+ backendTargetProfile: (route: { targetProfile?: string } | null, name: string) => route?.targetProfile ?? name,+ botConnectionRoute: () => null,+ botRosterMeta: () => ({}),+ botWorkspaceOwnerKey: (bot: { name?: string } | null) => String(bot?.name || ''),+ requestForBot: requestForBotMock+}))++vi.mock('./data', () => ({+ $botMeta: { get: () => ({}), set: vi.fn() },+ botMetaKey: (bot: { name?: string }) => bot?.name ?? '',+ botOwner: (owner: RosterRow | string) =>+ typeof owner === 'string'+ ? { bot: { name: owner }, key: owner, name: owner, route: null }+ : { bot: owner, key: owner?.name, name: owner?.name, route: null },+ persistBotMetaSnapshot: persistMock,+ saveBotMeta: saveBotMetaMock+}))++vi.mock('./shared', () => ({ getPluginCtx: () => null }))++let events: string[]++function respondWith(handler: (method: string) => unknown) {+ requestForBotMock.mockImplementation(async (_bot: unknown, method: string) => {+ events.push(method)++ return handler(method)+ })+}++async function loadModule() {+ vi.resetModules()++ return import('./canonical-chat')+}++beforeEach(() => {+ vi.clearAllMocks()+ events = []+ hostMock.openSession.mockImplementation(async (id: string) => {+ events.push(`open:${id}`)+ })+})++describe('a title-uniqueness rejection means someone else won the registry', () => {+ it('adopts the racing winner instead of forking into the stray row', async () => {+ let lists = 0++ respondWith(method => {+ if (method === 'session.list') {+ lists += 1++ // First consult: registry miss (this is why we mint at all). Second+ // consult (after the conflict): the racing winner exists.+ return lists === 1+ ? { sessions: [] }+ : { sessions: [{ id: 'winner-1', message_count: 3, resolved_id: 'winner-1', title: 'Bot Chat' }] }+ }++ if (method === 'session.create') {+ return { session_id: 'rt-stray', stored_session_id: 'stray-1' }+ }++ if (method === 'session.title') {+ throw new Error("Title 'Bot Chat' is already in use by session winner-1")+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()++ expect(await createCanonicalChat('ops')).toBe('winner-1')+ // The winner is opened; the stray is never prompted into or opened.+ expect(events).toContain('open:winner-1')+ expect(events).not.toContain('prompt.submit')+ expect(events).not.toContain('open:stray-1')+ })++ it('keeps the compat path for a NON-conflict title failure (old gateways)', async () => {+ respondWith(method => {+ if (method === 'session.list') {+ return { sessions: [] }+ }++ if (method === 'session.create') {+ return { session_id: 'rt-1', stored_session_id: 'stored-1' }+ }++ if (method === 'session.title') {+ throw new Error('unknown method')+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()++ expect(await createCanonicalChat('ops')).toBe('stored-1')+ // Old gateway: eager title unsupported → the kickoff persists the lazy row.+ expect(events).toContain('prompt.submit')+ // Only the initial registry consult — a plain failure must not re-list.+ expect(events.filter(event => event === 'session.list')).toHaveLength(1)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-chat-creation.test.ts b/apps/desktop/src/plugins/hermes-bots/canonical-chat-creation.test.tsnew file mode 100644index 00000000000..a7b66d125d1--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-chat-creation.test.ts@@ -0,0 +1,262 @@+/**+ * Minting a bot's forever-chat.+ *+ * `session.create` is lazy: the stored row does not exist until something+ * writes to it. Creation therefore materializes and TITLES the row eagerly,+ * before it opens or prompts — until the row carries "Bot Chat" the registry+ * has no entry for this bot, and a second click during that window mints a+ * duplicate forever-chat. Older gateways that reject the eager title keep a+ * narrow compat kickoff, else the pruner reaps the empty lazy session and the+ * chat never survives its own creation.+ *+ * The other half of the contract is navigation: a create still completes+ * registry-side when the user has already moved on, but it must not steal the+ * workspace (#89834 family).+ *+ * Ported from tests/canonical-chat-creation.test.mjs, which sliced the+ * creation section out of the old plugin.js bundle and ran it under `vm`.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RosterRow } from './types'++const { hostMock, persistMock, requestForBotMock, saveBotMetaMock } = vi.hoisted(() => ({+ hostMock: { openSession: vi.fn(), request: vi.fn() },+ persistMock: vi.fn(),+ requestForBotMock: vi.fn(),+ saveBotMetaMock: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', () => ({+ BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS: 15_000,+ host: hostMock+}))++vi.mock('./routing', () => ({+ backendTargetProfile: (route: { targetProfile?: string } | null, name: string) => route?.targetProfile ?? name,+ botConnectionRoute: () => null,+ botRosterMeta: () => ({}),+ botWorkspaceOwnerKey: (bot: { connectionId?: string; name?: string } | null) =>+ `bot:${bot?.connectionId ? `${bot.connectionId}::` : ''}${bot?.name || 'default'}`,+ requestForBot: requestForBotMock+}))++vi.mock('./data', () => ({+ $botMeta: { get: () => ({}), set: vi.fn() },+ botMetaKey: (bot: { name?: string }) => bot?.name ?? '',+ botOwner: (owner: RosterRow | string) =>+ typeof owner === 'string'+ ? { bot: { name: owner }, key: owner, name: owner, route: null }+ : { bot: owner, key: owner?.name, name: owner?.name, route: null },+ persistBotMetaSnapshot: persistMock,+ saveBotMeta: saveBotMetaMock+}))++vi.mock('./shared', () => ({ getPluginCtx: () => null }))++/** Ordered log of everything creation did — RPCs and navigations interleaved,+ * because the ORDER between them is most of what this suite pins. */+let events: string[]++function respondWith(handler: (method: string, params: Record<string, unknown>) => unknown) {+ requestForBotMock.mockImplementation(async (_bot: unknown, method: string, params: Record<string, unknown>) =>+ handler(method, params ?? {})+ )+}++async function loadModule() {+ // Creation is single-flighted through a module-level map keyed by bot.+ vi.resetModules()++ return import('./canonical-chat')+}++beforeEach(() => {+ vi.clearAllMocks()+ events = []+ hostMock.openSession.mockImplementation(async (id: string) => {+ events.push(`open:${id}`)+ })+})++describe('the lazy row is materialized before anything else touches it', () => {+ it('titles the created row, then opens it, and sends no intro', async () => {+ respondWith((method, params) => {+ events.push(method)++ if (method === 'session.create') {+ return { session_id: 'runtime-1', stored_session_id: 'stored-1' }+ }++ if (method === 'session.title') {+ // A throw here is NOT inert: createCanonicalChat reads it as "eager+ // title unsupported" and falls back to the compat kickoff.+ expect(params).toEqual({ session_id: 'runtime-1', title: 'Bot Chat' })+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()++ // No kickoff option: the click-path mint. The eager title write persists+ // the row, so NO intro turn fires — the user speaks first (ScottFive).+ expect(await createCanonicalChat('ops')).toBe('stored-1')+ expect(events).toEqual(['session.list', 'session.create', 'session.title', 'open:stored-1'])+ })++ it('always creates hidden — Bot Mode sessions have no visibility pref', async () => {+ // Canonical Bot Chats are plugin-owned forever-chats, never scratch+ // conversations, so `hidden` is unconditional. The `$hideBotChats` user+ // pref that used to gate it is gone.+ let created: Record<string, unknown> | null = null++ respondWith((method, params) => {+ if (method === 'session.create') {+ created = params++ return { session_id: 'rt-1', stored_session_id: 'sid-1' }+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()+ await createCanonicalChat('alpha')++ expect(created).toMatchObject({ hidden: true, title: 'Bot Chat' })+ })++ it('sends the one intro turn on New Bot creation (kickoff: true)', async () => {+ respondWith((method, params) => {+ events.push(method)++ if (method === 'session.create') {+ return { session_id: 'runtime-1', stored_session_id: 'stored-1' }+ }++ if (method === 'prompt.submit') {+ expect(params.session_id).toBe('runtime-1')+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()++ expect(await createCanonicalChat('ops', { kickoff: true })).toBe('stored-1')+ expect(events).toEqual(['session.list', 'session.create', 'session.title', 'open:stored-1', 'prompt.submit'])+ })++ it('retries navigation after the compat kickoff when the eager title is unsupported', async () => {+ let attempts = 0++ hostMock.openSession.mockImplementation(async (id: string) => {+ events.push(`open:${id}`)+ attempts += 1++ if (attempts === 1) {+ throw new Error('stored row not persisted yet')+ }+ })+ respondWith(method => {+ if (method === 'session.create') {+ return { session_id: 'runtime-1', stored_session_id: 'stored-1' }+ }++ if (method === 'session.title') {+ throw new Error('unknown method')+ }++ if (method === 'prompt.submit') {+ events.push('kickoff:persisted')+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()++ expect(await createCanonicalChat('ops')).toBe('stored-1')+ expect(events).toEqual(['open:stored-1', 'kickoff:persisted', 'open:stored-1'])+ })++ it('still returns the created registry row when the intro fails', async () => {+ respondWith(method => {+ if (method === 'session.create') {+ return { session_id: 'rt-1', stored_session_id: 'new-bot-chat' }+ }++ if (method === 'prompt.submit') {+ throw new Error('gateway timeout')+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()++ // The chat exists under the canonical title — the next click finds it by+ // NAME (the registry), so a failed kickoff can never orphan or fork it.+ expect(await createCanonicalChat('newbie', { kickoff: true })).toBe('new-bot-chat')+ })+})++describe('a superseded click completes registry-side but never navigates', () => {+ it('creates the canonical row without stealing the workspace', async () => {+ let current = true++ respondWith(method => {+ if (method === 'session.create') {+ current = false++ return { session_id: 'new-runtime', stored_session_id: 'new-stored' }+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()++ expect(await createCanonicalChat('ops', { openingStillCurrent: () => current })).toBe('new-stored')+ expect(hostMock.openSession).not.toHaveBeenCalled()+ })++ it('lets a newer same-bot open take over the in-flight creation navigation', async () => {+ let firstCurrent = true+ let releaseCreate = () => undefined as void+ let markCreateStarted = () => undefined as void++ const createStarted = new Promise<void>(resolve => {+ markCreateStarted = resolve+ })++ respondWith(method => {+ if (method === 'session.create') {+ markCreateStarted()++ return new Promise(resolve => {+ releaseCreate = () => resolve({ session_id: 'shared-runtime', stored_session_id: 'shared-stored' })+ })+ }++ return {}+ })++ const { createCanonicalChat } = await loadModule()+ const first = createCanonicalChat('ops', { openingStillCurrent: () => firstCurrent })++ await createStarted+ firstCurrent = false++ const second = createCanonicalChat('ops', { openingStillCurrent: () => true })++ releaseCreate()++ expect(await first).toBe('shared-stored')+ expect(await second).toBe('shared-stored')+ // The newer current click owns the shared creation's one navigation.+ expect(hostMock.openSession).toHaveBeenCalledTimes(1)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-chat-registry.test.ts b/apps/desktop/src/plugins/hermes-bots/canonical-chat-registry.test.tsnew file mode 100644index 00000000000..03e34f8e6cd--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-chat-registry.test.ts@@ -0,0 +1,283 @@+/**+ * The canonical-chat REGISTRY contract.+ *+ * A bot's forever-chat has exactly ONE identity: the session titled "Bot Chat"+ * on that bot's profile. The core UNIQUE(title) index makes (profile, "Bot+ * Chat") an exact registry — at most one row, resolved fresh on every open via+ * `session.list { title: 'Bot Chat', include_hidden: true }`.+ *+ * There is NO session-id pin. The previous design stored a pointer in+ * ui_meta['hermes-bots'].chat and spent five hardening waves (#88690, #90732,+ * #90751, the #91791 revert, #92042) guarding its failure modes: rows[0]+ * steals, last_session adoptions, transient clears, drifted-title welds. Every+ * "lost canonical chat" incident traced to that pointer dangling and a later+ * guard welding the wrong session in. Name-as-identity removes the failure+ * class instead of guarding it: a name cannot dangle.+ *+ * This suite pins the whole contract:+ * 1. open = registry lookup → open the row (lineage tip)+ * 2. no row → create (adopt-before-mint lives inside creation)+ * 3. no pointer is ever read or written on the open path+ *+ * It drives the real module. Its predecessor sliced `plugin.js` out of the+ * bundle with string offsets and ran it under `vm`, which meant the tripwire+ * below could only be a regex over source text; here it is an assertion about+ * what the code DOES — no write reaches the metadata store, and no RPC carries+ * an id to verify.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RosterRow } from './types'++const { hostMock, persistMock, requestForBotMock, saveBotMetaMock } = vi.hoisted(() => ({+ hostMock: { openSession: vi.fn(), request: vi.fn() },+ persistMock: vi.fn(),+ requestForBotMock: vi.fn(),+ saveBotMetaMock: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', () => ({+ BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS: 15_000,+ host: hostMock+}))++vi.mock('./routing', () => ({+ backendTargetProfile: (route: { targetProfile?: string } | null, name: string) => route?.targetProfile ?? name,+ botConnectionRoute: () => null,+ botRosterMeta: () => ({}),+ botWorkspaceOwnerKey: (bot: { connectionId?: string; name?: string } | null) =>+ `bot:${bot?.connectionId ? `${bot.connectionId}::` : ''}${bot?.name || 'default'}`,+ requestForBot: requestForBotMock+}))++vi.mock('./data', () => ({+ $botMeta: { get: () => ({}), set: vi.fn() },+ botMetaKey: (bot: { name?: string }) => bot?.name ?? '',+ // Local bots carry no route, so everything resolves onto the ambient+ // request — the single-connection shape these tests pin.+ botOwner: (owner: RosterRow | string) =>+ typeof owner === 'string'+ ? { bot: { name: owner }, key: owner, name: owner, route: null }+ : { bot: owner, key: owner?.name, name: owner?.name, route: null },+ persistBotMetaSnapshot: persistMock,+ saveBotMeta: saveBotMetaMock+}))++vi.mock('./shared', () => ({ getPluginCtx: () => null }))++/** Route every RPC through one table, recording what was asked. */+function respondWith(handler: (method: string, params: Record<string, unknown>) => unknown) {+ const calls: Array<{ method: string; params: Record<string, unknown> }> = []++ requestForBotMock.mockImplementation(async (_bot: unknown, method: string, params: Record<string, unknown>) => {+ calls.push({ method, params: structuredClone(params ?? {}) })++ return handler(method, params)+ })++ return calls+}++async function loadModule() {+ vi.resetModules()++ return import('./canonical-chat')+}++beforeEach(() => {+ vi.clearAllMocks()+ hostMock.openSession.mockResolvedValue(undefined)+})++describe('the registry row wins, always', () => {+ it('resolves the profile\u2019s "Bot Chat" row by exact title and opens it', async () => {+ const calls = respondWith(method => {+ if (method === 'session.list') {+ return { sessions: [{ id: 'forever-chat', message_count: 930, title: 'Bot Chat' }] }+ }++ if (method === 'session.create') {+ throw new Error('must not create: the registry row exists')+ }++ return {}+ })++ const { openBotCanonicalChat } = await loadModule()+ const opened = await openBotCanonicalChat('ops')++ expect(opened).toEqual({ openedId: 'forever-chat', registryId: 'forever-chat' })+ expect(hostMock.openSession).toHaveBeenCalledTimes(1)++ const [id, options] = hostMock.openSession.mock.calls[0]++ expect(id).toBe('forever-chat')+ expect(options).toMatchObject({+ profile: 'ops',+ // Opening a bot leaves the Sessions workspace on its current gateway.+ keepAllProfilesScope: true,+ tabTitle: 'Bot Chat',+ workspaceMode: 'bots',+ workspaceOwnerKey: 'bot:ops'+ })+ // Same intent a session row click uses. `tab` stacked a fresh tile on every+ // miss, so bot chats piled up beside each other and beside the untouched+ // "New session" draft.+ expect(options.intent).toBe('in-place')++ const list = calls.find(call => call.method === 'session.list')++ expect(list?.params).toMatchObject({+ profile: 'ops',+ // Canonical chats are always hidden — the lookup must see hidden rows.+ include_hidden: true,+ title: 'Bot Chat'+ })+ })++ it('opens the lineage tip of a compression-rotated registry row', async () => {+ respondWith(method =>+ method === 'session.list'+ ? {+ sessions: [+ { id: 'root-1', message_count: 400, resolved_id: 'tip-9', root_title: 'Bot Chat', title: 'Bot Chat' }+ ]+ }+ : {}+ )++ const { openBotCanonicalChat } = await loadModule()+ const opened = await openBotCanonicalChat('ops')++ // The durable registry id names the chat; the tip is what takes focus.+ expect(opened).toEqual({ openedId: 'tip-9', registryId: 'root-1' })+ expect(hostMock.openSession.mock.calls[0][0]).toBe('tip-9')+ })++ it('never reads or writes a stored pointer while opening', async () => {+ const calls = respondWith(method =>+ method === 'session.list' ? { sessions: [{ id: 'forever-chat', title: 'Bot Chat' }] } : {}+ )++ const { openBotCanonicalChat } = await loadModule()+ await openBotCanonicalChat('ops')++ expect(saveBotMetaMock).not.toHaveBeenCalled()+ expect(persistMock).not.toHaveBeenCalled()+ // No id-verification RPC: the name IS the identity, so there is nothing to+ // verify a stored id against.+ expect(calls.every(call => !('preferred_session_ids' in call.params))).toBe(true)+ expect(calls.map(call => call.method)).toEqual(['session.list'])+ })+})++describe('no registry row → create', () => {+ it('mints a hidden "Bot Chat" WITHOUT an intro kickoff', async () => {+ // Click-path resolution mints silently. The intro turn fires only from New+ // Bot creation (kickoff: true) — re-firing it on a resolution miss burned a+ // model turn and stamped a user-attributed prompt into the chat.+ const calls = respondWith(method => {+ if (method === 'session.list') {+ return { sessions: [] }+ }++ if (method === 'session.create') {+ return { session_id: 'rt-1', stored_session_id: 'fresh-1' }+ }++ return {}+ })++ const { openBotCanonicalChat } = await loadModule()+ const opened = await openBotCanonicalChat('newbie')++ expect(opened).toEqual({ openedId: 'fresh-1', registryId: 'fresh-1' })+ expect(calls.find(call => call.method === 'session.create')?.params).toMatchObject({+ hidden: true,+ title: 'Bot Chat'+ })+ // The eager title write persists the row; no user-attributed intro.+ expect(calls.find(call => call.method === 'session.title')?.params).toMatchObject({ session_id: 'rt-1' })+ expect(calls.find(call => call.method === 'prompt.submit')).toBeUndefined()+ })++ it('never claims an ordinary titled session', async () => {+ respondWith(method => {+ if (method === 'session.list') {+ // An older gateway ignores the title param and returns a windowed+ // listing — the local exact-title scan still applies.+ return {+ sessions: [+ { id: 'scratch', message_count: 40, title: 'help me with x' },+ { id: 'draft', message_count: 0, title: '' }+ ]+ }+ }++ return method === 'session.create' ? { session_id: 'rt-2', stored_session_id: 'fresh-2' } : {}+ })++ const { openBotCanonicalChat } = await loadModule()+ const opened = await openBotCanonicalChat('ops')++ expect(opened).toEqual({ openedId: 'fresh-2', registryId: 'fresh-2' })+ expect(hostMock.openSession.mock.calls.every(([id]) => id !== 'scratch')).toBe(true)+ })++ it('surfaces a failed open of the registry row instead of forking a replacement', async () => {+ respondWith(method => {+ if (method === 'session.list') {+ return { sessions: [{ id: 'forever-chat', message_count: 12, title: 'Bot Chat' }] }+ }++ if (method === 'session.create') {+ throw new Error('must not create: a transient open failure is not ownership loss')+ }++ return {}+ })+ hostMock.openSession.mockRejectedValue(new Error('backend restarting'))++ const { openBotCanonicalChat } = await loadModule()++ await expect(openBotCanonicalChat('ops')).rejects.toThrow('backend restarting')+ })+})++describe('a failed lookup fails CLOSED — never "no chat exists"', () => {+ // The post-update window: the desktop restarts every profile backend, the+ // first bot click races the warm-up, and the lookup RPC fails transiently.+ // Swallowing that made the failure indistinguishable from "this bot has no+ // Bot Chat yet", so create minted a fresh forever-chat while the real one+ // (data intact, hidden) still held the canonical title — read by users as+ // "my bot lost everything after the update".+ const refuseToMint = (method: string) => {+ if (method === 'session.list') {+ throw new Error('gateway not ready')+ }++ if (method === 'session.create') {+ throw new Error('must not create: a failed lookup is not "no chat exists"')+ }++ return {}+ }++ it('rejects instead of minting a replacement chat', async () => {+ const calls = respondWith(refuseToMint)+ const { openBotCanonicalChat } = await loadModule()++ await expect(openBotCanonicalChat('ops')).rejects.toThrow(/Bot Chat registry/)+ expect(calls.some(call => call.method === 'session.create')).toBe(false)+ expect(hostMock.openSession).not.toHaveBeenCalled()+ })++ it('refuses to mint when the adoption lookup inside creation fails', async () => {+ const calls = respondWith(refuseToMint)+ const { createCanonicalChat } = await loadModule()++ await expect(createCanonicalChat('ops')).rejects.toThrow(/Bot Chat registry/)+ expect(calls.some(call => call.method === 'session.create')).toBe(false)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/create-agent-lazy-profile.test.tsx b/apps/desktop/src/plugins/hermes-bots/create-agent-lazy-profile.test.tsxnew file mode 100644index 00000000000..ee1dbfe5412--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/create-agent-lazy-profile.test.tsx@@ -0,0 +1,255 @@+/**+ * New Bot creates its profile LAZILY. Two contracts hang off that:+ *+ * - MCP OAuth / API-key credentials must be configurable DURING creation+ * rather than forcing create-then-edit, so the setup button materializes+ * the profile through `ensureAgentCreated()` on its first action. The+ * creation is single-flighted and idempotent: whichever door fires first+ * (a setup click, the Capabilities tab, or Create Bot itself) is the only+ * `profiles.create` the dialog ever sends.+ * - `reset()` has to restore the SAME clone source the dialog mounted with.+ * It restored '__none__' instead: the first open cloned the main profile,+ * every later open after a create or cancel silently started fresh.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import type { ReactNode } from 'react'+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import type * as DataModule from './data'+import { translateBots } from './i18n-test-helper'+import type { RosterRow } from './types'++interface SkillsViewProps {+ fixedConnection?: string+ fixedProfile?: string+}++const mocks = vi.hoisted(() => ({+ connections: vi.fn(async () => [] as { id: string; label: string }[]),+ createCanonicalChat: vi.fn(async () => 'session-1'),+ deleteBot: vi.fn(async () => undefined),+ /** Flipped off to model a desktop build that predates the live surface. */+ hasSkillsView: { value: true },+ notify: vi.fn(),+ notifyError: vi.fn(),+ request: vi.fn(),+ requestProfile: vi.fn(async () => ({})),+ saveBotMeta: vi.fn(),+ skillsView: [] as SkillsViewProps[]+}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const original = await importOriginal<typeof HermesSdk>()++ const SkillsViewStub = (props: SkillsViewProps) => {+ mocks.skillsView.push(props)++ return null+ }++ // Builds that route `fixedConnection` get the live Capabilities tab for+ // remote targets too, pinned to the target machine's backend.+ SkillsViewStub.supportsFixedConnection = true++ const mocked: Record<string, unknown> = {+ ...original,+ host: {+ ...original.host,+ connections: mocks.connections,+ notify: mocks.notify,+ notifyError: mocks.notifyError,+ request: mocks.request,+ requestProfile: mocks.requestProfile+ },+ // The plugin bundle normally lands via `ctx.i18n.register` at load.+ usePluginI18n: () => translateBots+ }++ Object.defineProperty(mocked, 'SkillsView', {+ configurable: true,+ enumerable: true,+ get: () => (mocks.hasSkillsView.value ? SkillsViewStub : undefined)+ })++ return mocked+})++vi.mock('./canonical-chat', () => ({ createCanonicalChat: mocks.createCanonicalChat }))+vi.mock('./profile-ops', () => ({ deleteBot: mocks.deleteBot }))+vi.mock('./data', async importOriginal => {+ const original = await importOriginal<typeof DataModule>()++ return { ...original, saveBotMeta: mocks.saveBotMeta }+})++// Each build re-imports the dialog's whole module graph.+vi.setConfig({ testTimeout: 30_000 })++const roster: RosterRow[] = [{ connectionId: 'local', name: 'default' }]++/** A catalog entry that needs an API key — the only row that renders setup. */+const catalog = { auth: null, installed: false, name: 'linear', requires: ['LINEAR_API_KEY'] }++function withQueryClient(children: ReactNode) {+ return (+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ {children}+ </QueryClientProvider>+ )+}++async function renderDialog(hasSkillsView: boolean) {+ mocks.hasSkillsView.value = hasSkillsView+ vi.resetModules()++ const { CreateAgentDialog } = await import('./create-dialog')++ const view = render(withQueryClient(<CreateAgentDialog onClose={() => undefined} open roster={roster} />))++ fireEvent.change(screen.getByPlaceholderText('inbox-triage'), { target: { value: 'inbox-triage' } })+ fireEvent.click(screen.getByRole('button', { name: /Advanced/ }))++ return view+}++function createCalls() {+ return mocks.request.mock.calls.filter(([method]) => method === 'profiles.create')+}++/** The control under a `labeled(...)` caption — the label is presentational,+ * so it carries no `for`/`id` pair to query by. */+function controlUnder(caption: string) {+ return screen.getByText(caption).parentElement!.querySelector('[role="combobox"]') as HTMLElement+}++beforeAll(async () => {+ // Radix Select/Dialog reach for APIs jsdom does not implement.+ Element.prototype.scrollIntoView = () => undefined+ Element.prototype.hasPointerCapture = () => false+ Element.prototype.releasePointerCapture = () => undefined+ Element.prototype.setPointerCapture = () => undefined+ // Warm the transform cache so the first test isn't charged for it.+ await import('./create-dialog')+}, 120_000)++beforeEach(() => {+ vi.clearAllMocks()+ mocks.skillsView.length = 0+ mocks.connections.mockResolvedValue([])+ mocks.requestProfile.mockResolvedValue({})+ mocks.request.mockImplementation(async (method: string) => {+ switch (method) {+ case 'mcp.catalog':+ return { servers: [catalog] }++ case 'mcp.servers.test':+ return { ok: true }++ case 'profiles.describe':+ return { mcp_servers: [], skills: [], toolsets: [] }++ default:+ return {}+ }+ })+})++afterEach(() => {+ cleanup()+})++describe('materializing the draft profile', () => {+ it('creates it once when the Capabilities tab opens, pinned to the new slug', async () => {+ await renderDialog(true)++ fireEvent.click(screen.getByRole('button', { name: 'Capabilities' }))++ await waitFor(() => expect(createCalls()).toHaveLength(1))+ expect(createCalls()[0][1]).toMatchObject({ clone_from: 'default', name: 'inbox-triage' })+ // The live surface needs a REAL backend row to write to.+ await waitFor(() => expect(mocks.skillsView.at(-1)).toMatchObject({ fixedProfile: 'inbox-triage' }))++ // Create Bot goes through the same helper — no duplicate profiles.create.+ fireEvent.click(screen.getByRole('button', { name: 'Create Bot' }))++ await waitFor(() => expect(mocks.createCanonicalChat).toHaveBeenCalledWith('inbox-triage', { kickoff: true }))+ expect(createCalls()).toHaveLength(1)+ })++ it('pins a remote-target draft to the TARGET machine, not the active gateway', async () => {+ mocks.connections.mockResolvedValue([+ { id: 'local', label: 'This Mac' },+ { id: 'studio', label: 'Studio' }+ ])++ await renderDialog(true)++ // "Create on" only exists on a multi-connection desktop.+ await screen.findByText('Create on')+ fireEvent.click(controlUnder('Create on'))+ fireEvent.click(await screen.findByRole('option', { name: 'Studio' }))+ fireEvent.click(screen.getByRole('button', { name: 'Capabilities' }))++ // The create lands on THAT machine's backend — no gateway switch, and the+ // clone source is the remote's own default (a local profile name the+ // remote box does not have would fail there).+ await waitFor(() =>+ expect(mocks.requestProfile).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'studio' }),+ 'profiles.create',+ expect.objectContaining({ clone_from: 'default', name: 'inbox-triage' })+ )+ )+ expect(createCalls()).toHaveLength(0)+ await waitFor(() =>+ expect(mocks.skillsView.at(-1)).toMatchObject({ fixedConnection: 'studio', fixedProfile: 'inbox-triage' })+ )+ })++ it('creates it on the first MCP setup click, then adds the server to it', async () => {+ // Older builds keep the staged MCP tab, which is where the setup button+ // lives. There is no "save the agent first" gate: the button is live.+ await renderDialog(false)++ fireEvent.click(screen.getByRole('button', { name: 'MCP' }))+ fireEvent.click(await screen.findByRole('button', { name: /Set up/ }))++ await waitFor(() => expect(createCalls()).toHaveLength(1))+ expect(createCalls()[0][1]).toMatchObject({ name: 'inbox-triage' })+ // The add lands on the profile the click just minted, not on `null`.+ await waitFor(() =>+ expect(mocks.request).toHaveBeenCalledWith('mcp.servers.add', {+ name: 'linear',+ preset: 'linear',+ profile: 'inbox-triage'+ })+ )+ })+})++describe('the clone-from default', () => {+ it('regression: reset restores the mounted default, not "fresh profile"', async () => {+ await renderDialog(true)++ // `labeled()` renders a bare <label>, so the trigger is found by position.+ const cloneFrom = () =>+ screen.getByText('Clone from profile').parentElement!.querySelector('[role="combobox"]') as HTMLElement++ expect(cloneFrom().textContent).toBe('default')++ fireEvent.click(cloneFrom())+ fireEvent.click(await screen.findByRole('option', { name: /Fresh profile/ }))+ expect(cloneFrom().textContent).toMatch(/Fresh profile/)++ fireEvent.click(screen.getByRole('button', { name: 'Create Bot' }))+ await waitFor(() => expect(mocks.createCanonicalChat).toHaveBeenCalled())++ // Second open: the picker must read `default` again, or every agent after+ // the first silently starts from a bare profile.+ fireEvent.click(screen.getByRole('button', { name: /Advanced/ }))+ expect(cloneFrom().textContent).toBe('default')+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/create-dialog.single-flight.test.ts b/apps/desktop/src/plugins/hermes-bots/create-dialog.single-flight.test.tsnew file mode 100644index 00000000000..0be79fa6bd6--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/create-dialog.single-flight.test.ts@@ -0,0 +1,97 @@+/**+ * The create dialog pre-creates the draft profile so the Capabilities tab has+ * a real backend to point at. Every tab that needs one races for it, so the+ * creation is shared through one in-flight slot — otherwise a user tabbing+ * quickly mints two profiles and the second one leaks.+ *+ * The other half is failure: a rejected creation must CLEAR the slot, or one+ * gateway blip permanently wedges the dialog on a promise that will never+ * resolve and the user can never finish creating the bot.+ */++import { describe, expect, it, vi } from 'vitest'++import { singleFlight } from './create-dialog'++// The dialog is a 1200-line surface pulling in most of the SDK; the helper+// under test touches none of it, so a self-returning stub keeps the module+// graph linkable without pinning any of that surface.+vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ const stub: unknown = new Proxy(function stubbed() {}, {+ apply: () => stub,+ get: (_target, key) => (key === 'then' ? undefined : stub)+ })++ return new Proxy({ atom } as Record<string, unknown>, {+ // A callable `then` would make the namespace look thenable and hang the+ // module loader.+ get: (target, key) =>+ typeof key === 'symbol' || key in target ? target[key as string] : key === 'then' ? undefined : stub,+ has: () => true+ })+})++describe('singleFlight', () => {+ it('shares one in-flight creation across concurrent callers', async () => {+ const ref: { current: null | Promise<string> } = { current: null }+ let calls = 0+ let release!: () => void++ const pending = new Promise<void>(resolve => {+ release = resolve+ })++ const create = async () => {+ calls += 1+ await pending++ return 'researcher'+ }++ const first = singleFlight(ref, create)+ const second = singleFlight(ref, create)++ expect(calls).toBe(1)+ expect(first).toBe(second)++ release()+ await expect(first).resolves.toBe('researcher')+ expect(ref.current).toBe(first)+ })++ it('clears the slot on failure so a retry can succeed', async () => {+ const ref: { current: null | Promise<string> } = { current: null }+ let calls = 0++ await expect(+ singleFlight(ref, async () => {+ calls += 1+ throw new Error('gateway unavailable')+ })+ ).rejects.toThrow(/gateway unavailable/)++ expect(ref.current).toBeNull()++ await expect(+ singleFlight(ref, async () => {+ calls += 1++ return 'researcher'+ })+ ).resolves.toBe('researcher')+ expect(calls).toBe(2)+ })++ it('treats a synchronous throw as a rejected flight, not a crash', async () => {+ const ref: { current: null | Promise<string> } = { current: null }++ await expect(+ singleFlight<string>(ref, () => {+ throw new Error('bad args')+ })+ ).rejects.toThrow(/bad args/)+ expect(ref.current).toBeNull()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-create-dialog.test.tsx b/apps/desktop/src/plugins/hermes-bots/cron-create-dialog.test.tsxnew file mode 100644index 00000000000..2f975e4385c--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-create-dialog.test.tsx@@ -0,0 +1,142 @@+/**+ * The Create-job dialog: who it says the job belongs to, and where the run's+ * output is delivered.+ *+ * #93572: the dialog's `bot` prop is the pane's create target — an owner+ * OBJECT for roster-scoped bots, a bare profile name otherwise. Building the+ * label with `displayName({ name: bot }, $botMeta.get()[bot])` rendered+ * "[object Object]" and keyed the meta map with an object. The prop is now+ * normalized to a roster row at the component boundary and the meta lookup+ * goes through the object-aware `botRosterMeta`.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++// Radix calls these on open; jsdom doesn't implement them.+beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn()+ Element.prototype.hasPointerCapture = vi.fn(() => false)+ Element.prototype.releasePointerCapture = vi.fn()+})++const { notify, request } = vi.hoisted(() => ({+ notify: vi.fn(),+ request: vi.fn(async (_method: string, _params: Record<string, unknown>) => ({}))+}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return { ...sdk, host: { ...sdk.host, notify, request } }+})++const { $botMeta } = await import('./data')+const { CreateRoutineDialog } = await import('./cron')++/** The control under a `labeled(...)` caption — the label is presentational,+ * so it carries no `for`/`id` pair to query by. */+function controlUnder(caption: string) {+ const field = screen.getByText(caption).parentElement!++ return within(field).getByRole('combobox')+}++/** Name + instruction; the schedule picker already defaults to a valid daily. */+function fillRequiredFields() {+ fireEvent.change(screen.getByPlaceholderText('Morning briefing'), { target: { value: 'Morning digest' } })+ fireEvent.change(screen.getByPlaceholderText(/Summarize my unread Slack threads/), {+ target: { value: 'Summarize yesterday.' }+ })+}++beforeEach(() => {+ vi.clearAllMocks()+ $botMeta.set({})+})++afterEach(() => {+ cleanup()+})++describe('the dialog names the bot, never its object', () => {+ it('resolves an owner OBJECT through the roster-aware meta lookup', () => {+ $botMeta.set({ ops: { title: 'Ops Bot' } })++ render(<CreateRoutineDialog bot={{ name: 'ops' }} onClose={() => undefined} open />)++ const dialog = screen.getByRole('dialog')++ expect(dialog.textContent).toContain('Ops Bot')+ expect(dialog.textContent).not.toContain('[object Object]')+ })++ it('normalizes the bare-name arm to the same label', () => {+ $botMeta.set({ ops: { title: 'Ops Bot' } })++ render(<CreateRoutineDialog bot="ops" onClose={() => undefined} open />)++ expect(screen.getByRole('dialog').textContent).toContain('Ops Bot')+ })+})++describe('where the run\u2019s output lands', () => {+ it('offers run history and the bot\u2019s own chat', () => {+ render(<CreateRoutineDialog bot={{ name: 'ops' }} onClose={() => undefined} open />)++ fireEvent.click(controlUnder('Send results to'))++ const options = screen.getAllByRole('option').map(option => option.textContent)++ expect(options).toContain('Run history only')+ expect(options.some(option => option?.includes('chat (bot responds)'))).toBe(true)+ })++ it('sends no deliver param by default \u2014 history only', async () => {+ render(<CreateRoutineDialog bot={{ name: 'ops' }} onClose={() => undefined} open />)+ fillRequiredFields()++ fireEvent.click(screen.getByRole('button', { name: 'Create cron' }))++ await waitFor(() => expect(request).toHaveBeenCalled())++ const [, params] = request.mock.calls[0]++ expect(params).not.toHaveProperty('deliver')+ expect(params).toMatchObject({ action: 'add', name: '[bot:ops] Morning digest', profile: 'ops' })+ })++ it('sends the BARE bot-chat token on the profile-scoped create', async () => {+ render(<CreateRoutineDialog bot={{ name: 'ops' }} onClose={() => undefined} open />)+ fillRequiredFields()++ fireEvent.click(controlUnder('Send results to'))+ fireEvent.click(screen.getByRole('option', { name: /chat \(bot responds\)/ }))+ fireEvent.click(screen.getByRole('button', { name: 'Create cron' }))++ await waitFor(() => expect(request).toHaveBeenCalled())++ const [, params] = request.mock.calls[0]++ // The job is created in the bot's OWN cron store (profile scoping above),+ // so the bare token resolves to that profile machine-locally. A named+ // token built from a Desktop-side alias could name a profile the backend+ // does not have — the #82530 alias trap.+ expect(params.deliver).toBe('bot-chat')+ expect(params.profile).toBe('ops')+ })++ it('returns the picker to history when the dialog is reopened', async () => {+ const { rerender } = render(<CreateRoutineDialog bot={{ name: 'ops' }} onClose={() => undefined} open />)++ fireEvent.click(controlUnder('Send results to'))+ fireEvent.click(screen.getByRole('option', { name: /chat \(bot responds\)/ }))+ // Cancel resets; a reopened dialog must never inherit the last target.+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))++ rerender(<CreateRoutineDialog bot={{ name: 'ops' }} onClose={() => undefined} open />)++ await waitFor(() => expect(controlUnder('Send results to').textContent).toBe('Run history only'))+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-detail.test.tsx b/apps/desktop/src/plugins/hermes-bots/cron-detail.test.tsxnew file mode 100644index 00000000000..f42b9808d1c--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-detail.test.tsx@@ -0,0 +1,174 @@+/**+ * Bot Mode's cronjob rows were inert: the only interactive controls were the+ * enable switch and the hover-only delete button, so clicking a job to see+ * what it runs, when it runs next, or why it stopped did nothing at all. The+ * gateway already ships every one of those facts with `cron.manage list`, so+ * the inspector reads the record the pane is already holding — no extra RPC,+ * and no second mutation path beside the row's own switch and delete.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { cleanup, render, screen, within } from '@testing-library/react'+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'++import type { RoutineJob } from './types'++// Radix calls these on open; jsdom doesn't implement them.+beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn()+ Element.prototype.hasPointerCapture = vi.fn(() => false)+ Element.prototype.releasePointerCapture = vi.fn()+})++const request = vi.fn(async () => ({}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return { ...sdk, host: { ...sdk.host, request } }+})++const { RoutineDetailDialog, RoutineRow, routineDetailIssue, routineDetailRows } = await import('./cron')++const activeJob: RoutineJob = {+ deliver: 'bot-chat',+ enabled: true,+ job_id: 'job-1',+ last_run_at: '2026-08-23T09:00:00Z',+ last_status: 'success',+ name: '[bot:notetaker] Morning digest',+ next_run_at: '2026-08-23T10:00:00Z',+ prompt_preview: 'Summarize yesterday and post it.',+ repeat: 'forever',+ schedule: 'every 1440m'+}++const valueOf = (rows: Array<{ label: string; value: string }>, label: string) =>+ rows.find(row => row.label === label)?.value++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('the facts the row never showed', () => {+ it('carries only the fields the gateway actually sent', () => {+ const rows = routineDetailRows({ enabled: true, job_id: 'bare', name: 'Bare', schedule: 'every 1h' })+ const labels = rows.map(row => row.label)++ // A job that has never run carries no last_run_at/last_status/model; those+ // rows must be absent rather than rendering an empty or "undefined" value.+ expect(labels).not.toContain('Last run')+ expect(labels).not.toContain('Last result')+ expect(labels).not.toContain('Model')+ expect(rows.every(row => row.value.trim().length > 0)).toBe(true)+ })++ it('promises a next run only while the job is active', () => {+ const active = routineDetailRows(activeJob)++ expect(valueOf(active, 'Status')).toBe('Active')+ expect(valueOf(active, 'Next run')).toBeTruthy()++ const paused = routineDetailRows({ ...activeJob, enabled: false, state: 'paused' })++ expect(valueOf(paused, 'Status')).toBe('Paused')+ expect(valueOf(paused, 'Next run')).toBeUndefined()+ expect(valueOf(paused, 'Last run')).toBeTruthy()+ })++ it('shows the raw schedule only when the humanized label dropped something', () => {+ // "every 1440m" humanizes to "Daily" — the raw form still carries the cadence.+ expect(valueOf(routineDetailRows(activeJob), 'Schedule (raw)')).toBe('every 1440m')++ // A schedule the label passes through unchanged would only be duplicated.+ const passthrough = routineDetailRows({ ...activeJob, schedule: '0 9 * * 1-5' })++ expect(valueOf(passthrough, 'Schedule (raw)')).toBeUndefined()+ expect(valueOf(passthrough, 'Schedule')).toBe('0 9 * * 1-5')+ })++ it('explains a failing or scheduler-paused job in failure order', () => {+ expect(routineDetailIssue(activeJob)).toBeNull()+ expect(routineDetailIssue({ ...activeJob, paused_reason: 'too many failures' })).toBe('too many failures')+ expect(+ routineDetailIssue({ ...activeJob, last_delivery_error: 'telegram 401', paused_reason: 'too many failures' })+ ).toBe('telegram 401')+ expect(+ routineDetailIssue({+ ...activeJob,+ last_delivery_error: 'telegram 401',+ last_fire_error: 'model timeout',+ paused_reason: 'too many failures'+ })+ // The run that never happened outranks the delivery of a run that did.+ ).toBe('model timeout')+ })+})++describe('the row is reachable', () => {+ it('opens THIS job from its own title control', async () => {+ const opened: RoutineJob[] = []++ render(<RoutineRow job={activeJob} onOpen={job => opened.push(job)} owner={{ name: 'notetaker' }} />)++ screen.getByRole('button', { name: /Morning digest/ }).click()++ expect(opened).toEqual([activeJob])+ })++ it('cannot swallow the switch or the delete control', () => {+ render(<RoutineRow job={activeJob} onOpen={() => undefined} owner={{ name: 'notetaker' }} />)++ const opener = screen.getByRole('button', { name: /Morning digest/ })++ // The switch and delete button must be SIBLINGS of the opener: nested+ // inside it, a click on either would also open the inspector (and nested+ // interactive elements are invalid markup).+ expect(within(opener).queryByRole('switch')).toBeNull()+ expect(within(opener).queryByRole('button')).toBeNull()+ expect(screen.getAllByRole('switch')).toHaveLength(1)+ expect(screen.getByRole('button', { name: /delete/i })).toBeTruthy()+ })++ it('refuses to run a legacy delegated routine, and says why', () => {+ const legacy: RoutineJob = {+ ...activeJob,+ prompt_preview: 'You are running the scheduled routine "Morning digest" for agent \'notetaker\'.'+ }++ render(<RoutineRow job={legacy} onOpen={() => undefined} owner={{ name: 'notetaker' }} />)++ // Its prompt was built by interpolation, so the switch stays locked until+ // the user recreates the job through the hardened create path.+ expect(screen.getByRole('switch')).toHaveProperty('disabled', true)+ expect(screen.getByText(/Paused for security/)).toBeTruthy()+ })+})++describe('the inspector', () => {+ it('renders the job\u2019s instruction and its failure', () => {+ render(+ <RoutineDetailDialog job={{ ...activeJob, last_fire_error: 'model timeout' }} onClose={() => undefined} open />+ )++ const dialog = screen.getByRole('dialog')++ expect(within(dialog).getByText('Morning digest')).toBeTruthy()+ expect(within(dialog).getByText('Summarize yesterday and post it.')).toBeTruthy()+ expect(within(dialog).getByText('model timeout')).toBeTruthy()+ // The routing tag is plumbing, not a title.+ expect(dialog.textContent).not.toMatch(/\[bot:notetaker\]/)+ })++ it('stays shut without a job to inspect', () => {+ render(<RoutineDetailDialog job={null} onClose={() => undefined} open />)++ expect(screen.queryByRole('dialog')).toBeNull()++ cleanup()+ render(<RoutineDetailDialog job={activeJob} onClose={() => undefined} open={false} />)++ expect(screen.queryByRole('dialog')).toBeNull()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-jobs-view.test.ts b/apps/desktop/src/plugins/hermes-bots/cron-jobs-view.test.tsnew file mode 100644index 00000000000..1b1b1293b1e--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-jobs-view.test.ts@@ -0,0 +1,118 @@+/**+ * Which cron jobs the pane shows, and why it can look empty.+ *+ * Jobs are namespaced `[bot:<name>]`. Newer gateways honour the `profile`+ * param and answer with the bot's OWN cron store (echoed back as `scoped`),+ * in which case every job in the reply belongs to the bot. Older gateways+ * ignore the param and return the launch-profile store, so the tag filter+ * stays the fallback — and a stale `scoped` marker must never be trusted to+ * leak another profile's jobs.+ */++import { describe, expect, it } from 'vitest'++import { routineFilterHint, selectRoutineJobs } from './cron'+import type { RoutineJob } from './types'++const jobs: RoutineJob[] = [+ { job_id: '1', name: '[bot:ops] Morning' },+ { job_id: '2', name: '[bot:research] Digest' }+]++describe('selecting the jobs for the active bot', () => {+ it('filters a live list down to the current bot', () => {+ const view = selectRoutineJobs({ jobs }, null, [], 'ops')++ expect(view.live).toHaveLength(2)+ expect(view.jobs.map(job => job.job_id)).toEqual(['1'])+ })++ it('shows every job in a profile-scoped list, tagged or not', () => {+ const profileJobs: RoutineJob[] = [+ { job_id: 'legacy', name: 'ordinary profile cronjob' },+ { job_id: 'routine', name: '[bot:ops] Bot Mode routine' }+ ]++ const view = selectRoutineJobs({ jobs: profileJobs, scoped: 'ops' }, null, [], 'ops')++ expect(view.jobs.map(job => job.job_id)).toEqual(['legacy', 'routine'])+ })++ it('keeps tag filtering for an unmarked list (older gateways)', () => {+ const profileJobs: RoutineJob[] = [+ { job_id: 'legacy', name: 'ordinary launch-profile cronjob' },+ { job_id: 'routine', name: '[bot:ops] Bot Mode routine' }+ ]++ const view = selectRoutineJobs({ jobs: profileJobs }, null, [], 'ops')++ expect(view.jobs.map(job => job.job_id)).toEqual(['routine'])+ })++ it('cannot leak another profile\u2019s jobs through a stale scope marker', () => {+ const profileJobs: RoutineJob[] = [+ { job_id: 'research', name: 'ordinary research cronjob' },+ { job_id: 'routine', name: '[bot:ops] Bot Mode routine' }+ ]++ const view = selectRoutineJobs({ jobs: profileJobs, scoped: 'research' }, null, [], 'ops')++ expect(view.jobs.map(job => job.job_id)).toEqual(['routine'])+ })++ it('shows untagged legacy cronjobs only on the default bot', () => {+ const legacy: RoutineJob = { job_id: 'legacy', name: 'Existing reminder' }++ expect(selectRoutineJobs({ jobs: [legacy] }, null, [], 'default').jobs).toEqual([legacy])+ expect(selectRoutineJobs({ jobs: [legacy] }, null, [], 'ops').jobs).toEqual([])+ })+})++describe('a failed refresh keeps the last good list', () => {+ it('falls back to the previous jobs, still filtered', () => {+ const view = selectRoutineJobs(undefined, new Error('down'), jobs, 'ops')++ expect(view.live).toBeNull()+ expect(view.all).toHaveLength(2)+ expect(view.jobs).toHaveLength(1)+ })++ it('does not resurrect a list a successful refresh emptied', () => {+ const view = selectRoutineJobs({ jobs: [] }, null, jobs, 'ops')++ expect(view.live).toBeTruthy()+ expect(view.jobs).toHaveLength(0)+ })++ it('has nothing to show when the FIRST load fails', () => {+ const view = selectRoutineJobs(undefined, new Error('down'), [], 'ops')++ expect(view.all).toHaveLength(0)+ expect(view.jobs).toHaveLength(0)+ })+})++// A bot's cron store can hold jobs while none are namespaced for the active+// bot. Without a hint the user stares at the generic empty state with no clue+// that cronjobs are present but hidden by the tag filter.+describe('explaining an empty pane over a non-empty store', () => {+ it('stays quiet when the active bot already has tagged jobs', () => {+ const all: RoutineJob[] = [{ job_id: '1', name: '[bot:ops] Morning' }]++ expect(routineFilterHint(all, all)).toBeNull()+ })++ it('stays quiet when the store is genuinely empty', () => {+ expect(routineFilterHint([], [])).toBeNull()+ expect(routineFilterHint(undefined as unknown as RoutineJob[], [])).toBeNull()+ })++ it('explains the hidden jobs when the store has jobs but none match', () => {+ const all: RoutineJob[] = [+ { job_id: '2', name: '[bot:research] Digest' },+ { job_id: '3', name: 'untagged job' }+ ]++ expect(routineFilterHint(all, [])).toMatch(/tagged for this bot/)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-load.test.ts b/apps/desktop/src/plugins/hermes-bots/cron-load.test.tsnew file mode 100644index 00000000000..3839827ccd4--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-load.test.ts@@ -0,0 +1,177 @@+/**+ * `loadRoutines` — the pane's one read, and the two things it must survive.+ *+ * 1. Profile scope (#37). cron.manage is scoped to the bot's OWN cron store+ * through the core RPC's optional `profile` param: a bot's profile can run+ * a separate gateway, or keep cron in ~/.hermes/profiles/<name>/cron/.+ * Older gateways ignore the unknown param, so the `[bot:]` tag filter in+ * selectRoutineJobs stays the fallback.+ * 2. Legacy delegated routines are paused inline before the list returns —+ * they carry a pre-hardening prompt whose shell command was built by+ * interpolation. A single pause RPC failing used to reject the WHOLE query:+ * the pane showed "Could not load cronjobs" over a list that had 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 the jobs the gateway actually paused.+ *+ * The RPC boundary is `host.request` rather than `requestForBot`, so the real+ * routing layer (route resolution, error coercion) runs.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RoutineJob } from './types'++const request = vi.fn()++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return { ...sdk, host: { ...sdk.host, request } }+})++const { loadRoutines } = await import('./cron')++const LEGACY_PREFIX = 'You are running the scheduled routine "'++/** The shape a pre-hardening routine was persisted with. */+function legacyJob(id: string, title: string, bot: string): RoutineJob {+ return {+ enabled: true,+ job_id: id,+ name: `[bot:${bot}] ${title}`,+ prompt_preview: `${LEGACY_PREFIX}${title}" for agent '${bot}'`,+ state: 'scheduled'+ }+}++/** Every cron.manage call, as `[action, name]`. */+function callLog() {+ return request.mock.calls.map(([, params]) => [params.action, params.name])+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('the bot\u2019s own cron store', () => {+ it('scopes the list and every inline pause to the bot profile', async () => {+ request.mockImplementation(async (_method: string, params: Record<string, unknown>) =>+ params.action === 'list' ? { jobs: [legacyJob('legacy', 'Audit', 'research')] } : { success: true }+ )++ await loadRoutines('research')++ expect(request.mock.calls.map(([method, params]) => [method, params])).toEqual([+ ['cron.manage', { action: 'list', include_disabled: true, profile: 'research' }],+ ['cron.manage', { action: 'pause', name: 'legacy', profile: 'research' }]+ ])+ })++ it('omits the scope entirely when no owner is resolved', async () => {+ request.mockResolvedValue({ jobs: [] })++ await loadRoutines(undefined)++ expect(request).toHaveBeenCalledWith('cron.manage', { action: 'list', include_disabled: true })+ })+})++describe('pausing a legacy delegated routine cannot fail the list', () => {+ it('returns the whole list and overlays only the pauses that landed', async () => {+ const jobs: RoutineJob[] = [+ legacyJob('legacy-fails', 'Audit', 'research'),+ legacyJob('legacy-pauses', 'Build', 'research'),+ {+ enabled: true,+ job_id: 'normal',+ name: '[bot:research] Report',+ prompt: 'Summarize the day',+ state: 'scheduled'+ }+ ]++ request.mockImplementation(async (_method: string, params: Record<string, unknown>) => {+ if (params.action === 'list') {+ return { jobs }+ }++ if (params.name === 'legacy-fails') {+ throw new Error('gateway rejected the pause')+ }++ return { success: true }+ })++ // Pre-fix this rejected with the pause error.+ const result = await loadRoutines('research')++ expect(result.jobs).toHaveLength(3)++ const byId = Object.fromEntries(result.jobs!.map(job => [job.job_id, job]))++ // The failed pause keeps its server state and is retried on the next poll;+ // claiming it as paused would tell the user a job is safe when it is not.+ expect(byId['legacy-fails']).toMatchObject({ enabled: true, state: 'scheduled' })+ expect(byId['legacy-pauses']).toMatchObject({ enabled: false, state: 'paused' })+ expect(byId.normal.enabled).toBe(true)++ expect(callLog()).toEqual([+ ['list', undefined],+ ['pause', 'legacy-fails'],+ ['pause', 'legacy-pauses']+ ])+ })++ it('still resolves with the list when every pause fails', async () => {+ request.mockImplementation(async (_method: string, params: Record<string, unknown>) => {+ if (params.action === 'list') {+ return { jobs: [legacyJob('only', 'Watch', 'ops')] }+ }++ throw new Error('gateway down')+ })++ const result = await loadRoutines('ops')++ expect(result.jobs![0]).toMatchObject({ enabled: true, job_id: 'only' })+ })+})++describe('the security pause is one-shot, not a poll loop', () => {+ it('pauses the persisted routine once and leaves the rest of the record intact', async () => {+ const persisted: RoutineJob = {+ ...legacyJob('legacy-job', 'Audit', 'research'),+ repeat: { completed: 1, times: 3 } as unknown as string,+ schedule: 'every 2h'+ }++ request.mockImplementation(async (_method: string, params: Record<string, unknown>) => {+ if (params.action === 'list') {+ return { jobs: [persisted] }+ }++ persisted.enabled = false+ persisted.state = 'paused'++ return { success: true }+ })++ const first = await loadRoutines('research')++ expect(first.jobs![0]).toMatchObject({+ enabled: false,+ job_id: 'legacy-job',+ repeat: { completed: 1, times: 3 },+ schedule: 'every 2h',+ state: 'paused'+ })++ request.mockClear()+ await loadRoutines('research')++ // Already paused: the next poll must not re-attempt the pause forever.+ expect(callLog()).toEqual([['list', undefined]])+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-owner.test.tsx b/apps/desktop/src/plugins/hermes-bots/cron-owner.test.tsxnew file mode 100644index 00000000000..2860d4bce35--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-owner.test.tsx@@ -0,0 +1,70 @@+/**+ * A cron mutation names the owner that rendered it, never the ambient profile.+ *+ * The Routines pane follows the focused chat, so the live gateway profile can+ * already be on another bot by the time a row's switch is flipped or a create+ * dialog is submitted. Both the RPC scope and the cache eviction therefore+ * ride the captured owner — and the eviction is `exact`, so flipping one bot's+ * job cannot invalidate every other bot's list.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { queryClient } from '@hermes/plugin-sdk'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const { request } = vi.hoisted(() => ({ request: vi.fn(async () => ({})) }))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return { ...sdk, host: { ...sdk.host, request } }+})++const { invalidateRoutineOwner, RoutineRow, routineCreateTarget } = await import('./cron')++const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined)++beforeEach(() => {+ vi.clearAllMocks()+})++afterEach(() => {+ cleanup()+})++describe('the create target is captured, not re-read', () => {+ it('keeps the owner the dialog was opened for while another bot becomes active', () => {+ expect(routineCreateTarget('ops', 'ops')).toBe('ops')+ expect(routineCreateTarget('ops', 'default')).toBe('ops')+ // Nothing captured yet: the pane's resolved bot is the target.+ expect(routineCreateTarget(null, 'default')).toBe('default')+ })+})++describe('cache eviction is scoped to one owner', () => {+ it('invalidates that owner\u2019s list and nothing else', async () => {+ await invalidateRoutineOwner('ops')++ expect(invalidateQueries).toHaveBeenCalledWith({ exact: true, queryKey: ['hermes-bots', 'routines', 'ops'] })+ })+})++describe('a row mutation addresses the owner that rendered it', () => {+ it('scopes the pause RPC and the eviction to that owner', async () => {+ render(+ <RoutineRow+ job={{ enabled: true, job_id: 'digest', name: '[bot:ops] Digest', schedule: 'every 1h' }}+ onOpen={() => undefined}+ owner={{ name: 'ops' }}+ />+ )++ fireEvent.click(screen.getByRole('switch'))++ await waitFor(() => expect(invalidateQueries).toHaveBeenCalled())++ expect(request).toHaveBeenCalledWith('cron.manage', { action: 'pause', name: 'digest', profile: 'ops' })+ expect(invalidateQueries).toHaveBeenCalledWith({ exact: true, queryKey: ['hermes-bots', 'routines', 'ops'] })+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-pane.test.tsx b/apps/desktop/src/plugins/hermes-bots/cron-pane.test.tsxnew file mode 100644index 00000000000..a1582a286f4--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-pane.test.tsx@@ -0,0 +1,131 @@+/**+ * #94483: the Scheduled jobs pane read the shared roster with a bare+ * `$lastRoster.get()` while rendering. BotsPane owns the roster fetch, so+ * whenever this pane mounted before the roster hydrated (fresh boot ordering,+ * a renderer reload resetting the atoms) it captured an empty snapshot+ * forever: the pane stayed pinned on its "has to appear in the roster"+ * placeholder even for a focused bot chat whose exact roster row existed, and+ * creating a job silently no-oped.+ *+ * The contract:+ * 1. the pane SUBSCRIBES to the roster, so hydration re-renders it;+ * 2. once the owner resolves it paints real content and a working create+ * affordance instead of the placeholder;+ * 3. a complete (authoritative) focused owner with no exact roster row STILL+ * fails closed — the subscription fix must not loosen identity matching.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'+import type { atom } from 'nanostores'+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import type { RoutineJob } from './types'++// Radix calls these on open; jsdom doesn't implement them.+beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn()+ Element.prototype.hasPointerCapture = vi.fn(() => false)+ Element.prototype.releasePointerCapture = vi.fn()+})++const { request } = vi.hoisted(() => ({ request: vi.fn() }))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()+ const { atom: nanoAtom } = await import('nanostores')++ return {+ ...sdk,+ host: {+ ...sdk.host,+ request,+ // The pane's owner ladder starts here, so it has to be a real store:+ // `$focusedBotOwner` is resolved once at bot-state module load.+ state: { ...sdk.host.state, focusedSessionOwner: nanoAtom(null) }+ }+ }+})++const { host } = await import('@hermes/plugin-sdk')+const { $lastRoster } = await import('./data')+const { $selectedBot } = await import('./bot-state')+const { RoutinesPane } = await import('./cron')++/** The SDK store the pane's owner ladder reads. */+const $focused = host.state.focusedSessionOwner as unknown as ReturnType<typeof atom>++const job: RoutineJob = { enabled: true, job_id: 'j-1', name: 'Report', schedule: 'every 1h', state: 'scheduled' }++function renderPane() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })++ return render(+ <QueryClientProvider client={client}>+ <RoutinesPane />+ </QueryClientProvider>+ )+}++beforeEach(() => {+ vi.clearAllMocks()+ request.mockResolvedValue({ jobs: [job], scoped: 'research' })+ // Mount order under test: the pane paints BEFORE the roster fetch lands.+ $lastRoster.set([])+ $selectedBot.set('default')+ $focused.set({ connectionId: 'local', profile: 'research' })+})++afterEach(() => {+ cleanup()+})++describe('the pane follows the roster hydrating after mount', () => {+ it('starts fail-closed, then paints once the row arrives', async () => {+ renderPane()++ expect(screen.getByText('This agent has to appear in the roster first.')).toBeTruthy()++ // The same focused bot chat now resolves to its exact roster row. Nothing+ // else changes — only a store write the pane must be subscribed to see.+ act(() => $lastRoster.set([{ connectionId: 'local', name: 'research' }]))++ await waitFor(() => expect(screen.queryByText('This agent has to appear in the roster first.')).toBeNull())+ expect(await screen.findByText('Report')).toBeTruthy()+ expect(screen.getByText('Scheduled jobs')).toBeTruthy()+ })++ it('offers a create affordance once the owner resolves', async () => {+ request.mockResolvedValue({ jobs: [], scoped: 'research' })+ renderPane()++ act(() => $lastRoster.set([{ connectionId: 'local', name: 'research' }]))++ // The reported "create silently no-ops" symptom starts here: while the+ // owner is stuck unresolved the pane never offers any create control.+ expect(await screen.findByText('No scheduled jobs yet')).toBeTruthy()++ // Both doors: the header action and the empty state's own call to action.+ const create = screen.getAllByRole('button', { name: 'New cron' })++ expect(create).toHaveLength(2)++ act(() => create[0].click())++ // The dialog opens naming the resolved owner, not a placeholder.+ expect((await screen.findByRole('dialog')).textContent).toMatch(/research/i)+ })+})++describe('identity matching stays exact', () => {+ it('fails closed for a complete focused owner with no roster row', async () => {+ $focused.set({ connectionId: 'local', profile: 'ghost-profile' })+ renderPane()++ act(() => $lastRoster.set([{ connectionId: 'local', name: 'research' }]))++ await waitFor(() => expect(screen.getByText('This agent has to appear in the roster first.')).toBeTruthy())+ expect(request).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-prompt.test.ts b/apps/desktop/src/plugins/hermes-bots/cron-prompt.test.tsnew file mode 100644index 00000000000..fbaf1e28c02--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-prompt.test.ts@@ -0,0 +1,92 @@+/**+ * What a routine actually runs.+ *+ * A job scheduled for the ACTIVE bot profile runs its instruction directly. A+ * job for a different profile keeps the `hermes -p <bot> chat` delegation+ * wrapper so the run lands in that bot's own history — and that wrapper is a+ * shell command line, which is why every operand is single-quoted rather than+ * interpolated. The pre-hardening prompts were built by interpolation, so a+ * routine title or instruction containing `$(…)` executed on the scheduler's+ * machine; `isLegacyDelegatedRoutine` is how those persisted jobs are still+ * recognized and paused.+ */++import { spawnSync } from 'node:child_process'++import { describe, expect, it } from 'vitest'++import { isLegacyDelegatedRoutine, normalizedProfileName, routineInputError, routinePrompt } from './cron'++/** Run the delegation command under a `hermes` stub that prints its argv, so+ * the assertion is what the SHELL passed — not what the string looks like. */+function argvOf(prompt: string): string[] {+ const command = prompt.slice(prompt.indexOf('hermes '), prompt.lastIndexOf('\n\nIf the command'))+ const result = spawnSync('sh', ['-c', `hermes() { printf '%s\\037' "$@"; }\n${command}`], { encoding: 'utf8' })++ expect(result.status, result.stderr).toBe(0)++ return result.stdout.split('\u001f').slice(0, -1)+}++describe('direct vs delegated execution', () => {+ it('runs the bare instruction when the routine owns the active profile', () => {+ expect(normalizedProfileName(' Default ')).toBe('default')+ expect(routinePrompt('default', 'Health', 'Collect status', ' DEFAULT ')).toBe('Collect status')+ })++ it('keeps the delegation wrapper for a different active profile', () => {+ const prompt = routinePrompt('research', 'Digest', 'Summarize findings', 'default')++ expect(prompt).toMatch(/hermes -p 'research' chat/)+ expect(prompt).toMatch(/\[Scheduled routine\] Summarize findings/)+ })++ it('never re-wraps a direct prompt', () => {+ const instruction = 'Keep "quoted" output intact'++ expect(routinePrompt('ops', 'Check', instruction, 'ops')).toBe(instruction)+ })+})++describe('delegated arguments stay literal shell values', () => {+ it('passes substitutions, backticks and quotes through as text', () => {+ const title = "Audit $(printf TITLE_EXPANDED) `printf TITLE_TICK` 'quoted'"+ const instruction = "Line one $(printf TASK_EXPANDED) `printf TASK_TICK`\nLine two 'quoted'"++ expect(argvOf(routinePrompt('research', title, instruction, 'default'))).toEqual([+ '-p',+ 'research',+ 'chat',+ '-c',+ `Routine: ${title}`,+ '-q',+ `[Scheduled routine] ${instruction}`+ ])+ })++ it('a recreated routine is no longer recognized as the unsafe legacy shape', () => {+ // The v2 marker is what tells the loader this prompt was composed with+ // quoting, so it must NOT be swept into the security pause.+ const recreated = routinePrompt('research', 'Audit', 'Inspect', 'default')++ expect(+ isLegacyDelegatedRoutine({ job_id: 'x', name: '[bot:research] Audit', prompt_preview: recreated.slice(0, 100) })+ ).toBe(false)+ })++ it('recognizes a persisted pre-hardening prompt', () => {+ const legacy = 'You are running the scheduled routine "Audit" for agent \'research\'.'++ expect(isLegacyDelegatedRoutine({ job_id: 'x', name: '[bot:research] Audit', prompt_preview: legacy })).toBe(true)+ // Untagged jobs are not Bot Mode's to pause, whatever their prompt says.+ expect(isLegacyDelegatedRoutine({ job_id: 'x', name: 'Audit', prompt_preview: legacy })).toBe(false)+ })+})++describe('input the gateway cannot store', () => {+ it('rejects NUL before cron creation, naming the offending field', () => {+ expect(routineInputError('Normal title', 'Normal instruction')).toBeNull()+ expect(routineInputError('Bad\0title', 'Normal instruction')).toMatch(/NUL.*U\+0000/)+ expect(routineInputError('Normal title', 'Bad\0instruction')).toMatch(/NUL.*U\+0000/)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-rpc-error.test.ts b/apps/desktop/src/plugins/hermes-bots/cron-rpc-error.test.tsnew file mode 100644index 00000000000..4619bfe2740--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-rpc-error.test.ts@@ -0,0 +1,111 @@+/**+ * #94471: React Query stores whatever the queryFn throws, and React 19 then+ * formats it with `(error.name || '').trim()`. IPC / JSON-RPC rejections are+ * frequently plain objects whose `name` is the numeric error code, so that+ * `.trim()` threw "is not a function" and the Routines pane died instead of+ * rendering "Could not load cronjobs".+ *+ * `requestForBot` is the choke point every cron read and mutation goes+ * through, so the coercion is pinned there — through the real function, not+ * the private helper behind it.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const request = vi.fn()++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return { ...sdk, host: { ...sdk.host, request } }+})++const { loadRoutines } = await import('./cron')+const { requestForBot } = await import('./routing')++/** Exactly what React 19 does to a query error before painting it. */+function react19Format(error: { message?: unknown; name?: unknown }) {+ return `${((error.name as string) || '').trim()}: ${String(error.message)}`+}++/** The rejection `requestForBot` hands back, after coercion. */+async function rejectionFrom(thrown: unknown) {+ request.mockRejectedValue(thrown)++ return requestForBot({ name: 'research' }, 'cron.manage', {}).then(+ () => {+ throw new Error('requestForBot resolved; it must propagate the rejection')+ },+ (error: Error) => error+ )+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('a rejection always reaches React with a string name', () => {+ it('coerces a plain JSON-RPC object whose name is an error code', async () => {+ request.mockRejectedValue({ code: -32603, message: 'cron.manage failed', name: 32000 })++ const error = await loadRoutines('research').then(+ () => {+ throw new Error('loadRoutines resolved; the list read must propagate the failure')+ },+ (thrown: Error) => thrown+ )++ expect(typeof error.name).toBe('string')+ expect(() => react19Format(error)).not.toThrow()+ expect(error.message).toMatch(/cron\.manage failed/)+ // The original rejection is preserved for logs — only the surface is fixed.+ expect((error.cause as { name: number }).name).toBe(32000)+ })++ it('coerces a real Error whose name was overwritten with a number', async () => {+ const weird = new Error('down')++ Object.defineProperty(weird, 'name', { configurable: true, value: 13 })++ const error = await rejectionFrom(weird)++ expect(typeof error.name).toBe('string')+ expect(() => react19Format(error)).not.toThrow()+ expect(error.message).toMatch(/down/)+ })++ it('copies rather than mutates a frozen non-string name', async () => {+ const weird = new Error('down')++ Object.defineProperty(weird, 'name', { configurable: false, value: 13, writable: false })++ const error = await rejectionFrom(weird)++ expect(error).not.toBe(weird)+ expect(typeof error.name).toBe('string')+ expect(() => react19Format(error)).not.toThrow()+ })++ it('copies a sealed Error even where assignment would have worked', async () => {+ const weird = new Error('sealed')++ Object.defineProperty(weird, 'name', { configurable: true, value: 32000, writable: true })+ Object.seal(weird)++ const error = await rejectionFrom(weird)++ expect(error).not.toBe(weird)+ expect(typeof error.name).toBe('string')+ expect(error.message).toMatch(/sealed/)+ // Assignment would have succeeded on a sealed writable property; we still+ // copy so React 19 never sees a numeric name even if mutation is possible.+ expect(weird.name).toBe(32000)+ })++ it('passes an ordinary Error through untouched', async () => {+ const original = new Error('gateway rejected the pause')++ expect(await rejectionFrom(original)).toBe(original)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cron-selected-bot.test.ts b/apps/desktop/src/plugins/hermes-bots/cron-selected-bot.test.tsnew file mode 100644index 00000000000..51090213892--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cron-selected-bot.test.ts@@ -0,0 +1,131 @@+/**+ * Which bot the Routines pane is scoped to.+ *+ * #89625 (PR #89637 residual): nanostores' `.listen()` never replays the+ * current value the way `.subscribe()` does, so the focused-owner listener in+ * register() only kept `$selectedBot` current from the moment it was attached.+ * A disable → profile switch → re-enable cycle (Settings ▸ Plugins) left+ * `$selectedBot` pointed at whichever bot was active before the plugin was+ * disabled. `bindProfileSync` reseeds from the store's CURRENT value before+ * attaching the listener, so every register() starts in sync.+ *+ * #94516: the same ladder must not dead-end the pane. The SDK's+ * focusedSessionOwner store fails closed to null whenever the focused session+ * has no unique bot owner (a normal chat, ambiguous owner hints) — the common+ * case while the user browses the Bots pane. The pane falls back to the bot+ * the user clicked in the roster instead of pinning every bot on the+ * "has to appear in the roster first" placeholder.+ */++import { beforeEach, describe, expect, it } from 'vitest'++import { $selectedBot } from './bot-state'+import { bindProfileSync, resolveRoutineOwner } from './cron'+import type { RosterRow } from './types'++/** Real nanostores semantics — `get()` plus a NON-replaying `listen()` — so a+ * regression back to a plain listen() fails honestly instead of being masked+ * by a mock that assumes the fix. */+function fakeOwnerStore<T>(initial: T) {+ const listeners = new Set<(value: T) => void>()+ let value = initial++ return {+ get: () => value,+ listen: (listener: (value: T) => void) => {+ listeners.add(listener)++ return () => listeners.delete(listener)+ },+ set: (next: T) => {+ value = next+ listeners.forEach(listener => listener(value))+ }+ }+}++beforeEach(() => {+ $selectedBot.set('default')+})++describe('bindProfileSync reseeds, then follows', () => {+ it('resyncs on re-bind after a profile switch made while unbound', () => {+ const profile = fakeOwnerStore('blog-writer')+ const unbind = bindProfileSync(profile)++ expect($selectedBot.get()).toBe('blog-writer')++ unbind() // plugin disabled: listener torn down+ profile.set('researcher') // profile changes while nothing is listening++ bindProfileSync(profile) // plugin re-enabled: register() runs again++ expect($selectedBot.get()).toBe('researcher')+ })++ it('keeps forwarding live profile changes after (re)binding', () => {+ const profile = fakeOwnerStore('default')++ bindProfileSync(profile)+ profile.set('researcher')++ expect($selectedBot.get()).toBe('researcher')+ })++ it('follows a connection change for the same profile name', () => {+ const owner = fakeOwnerStore({ connectionId: 'source-a', profile: 'default' })++ bindProfileSync(owner)++ expect($selectedBot.get()).toBe('source-a::default')++ owner.set({ connectionId: 'source-b', profile: 'default' })++ expect($selectedBot.get()).toBe('source-b::default')+ })++ it('leaves the selection alone when the current value is empty', () => {+ bindProfileSync(fakeOwnerStore(''))++ expect($selectedBot.get()).toBe('default')+ })+})++describe('resolving the pane\u2019s owner', () => {+ const scoped = (name: string): RosterRow => ({+ connectionId: 'source-a',+ name,+ remoteSource: true,+ sourceScoped: true+ })++ it('fails closed when an authoritative focused owner has no roster row', () => {+ // Routing cron reads/mutations through a stale selection or an unscoped+ // profile name would address the wrong machine's cron store.+ expect(+ resolveRoutineOwner(+ [scoped('default')],+ { authoritative: true, connectionId: 'source-b', name: 'worker' },+ 'source-a::default'+ )+ ).toBeNull()+ })++ it('#94516: falls back to the roster-clicked bot when nothing is focused', () => {+ const roster = [scoped('default'), scoped('blog-writer')]++ expect(resolveRoutineOwner(roster, null, 'source-a::blog-writer')).toBe(roster[1])+ })++ it('#94516: still fails closed when the selection has no roster row either', () => {+ // Nothing to scope cron reads/mutations to, so the pane keeps its+ // fail-closed state rather than guessing.+ expect(resolveRoutineOwner([scoped('default')], null, 'source-a::missing')).toBeNull()+ })++ it('lets a legacy SDK without focused-owner support use the selection', () => {+ const roster = [scoped('default')]++ expect(resolveRoutineOwner(roster, null, 'source-a::default')).toBe(roster[0])+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/cross-connection-bots.test.ts b/apps/desktop/src/plugins/hermes-bots/cross-connection-bots.test.tsnew file mode 100644index 00000000000..2c075e83487--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/cross-connection-bots.test.ts@@ -0,0 +1,178 @@+/**+ * Cross-connection Bot Mode: a roster row can belong to another registered+ * connection's backend, and a group chat can seat members from several+ * machines at once.+ *+ * Everything hangs off one rule — a source-scoped row carries an IMMUTABLE+ * route descriptor and every RPC for it goes through `host.requestProfile`+ * with that descriptor, never through the active gateway. The alias case is+ * the sharp edge: Desktop's identity for the row (`route.profile`) and the+ * backend's own name for it (`route.targetProfile`) differ, so the params of+ * every profile-shaped RPC have to be translated on the way out while the+ * route keeps the Desktop identity.+ *+ * Ported from tests/cross-connection-bots.test.mjs, which ran the whole+ * plugin.js bundle under `vm`.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { GroupMember, ProfileRoute, RosterRow } from './types'++const { overrides, request, requestProfile } = vi.hoisted(() => ({+ overrides: {} as Record<string, unknown>,+ request: vi.fn(),+ requestProfile: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ overrides.request = request+ overrides.requestProfile = requestProfile++ return {+ ...sdk,+ host: new Proxy(sdk.host, {+ get: (target, prop) => (prop in overrides ? overrides[prop as string] : Reflect.get(target, prop))+ })+ }+})++const { botBackendProfileScope, botConnectionRoute, requestForBot } = await import('./routing')+const { groupMemberKey } = await import('./group-membership')++const { buildGroupChatTurnPrompt, formatGroupChatLine, parseGroupChatMentions, resolveGroupResponders } =+ await import('./group-rounds')++const aliasBot = {+ name: 'worker',+ route: {+ connectionId: 'remote-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ } satisfies ProfileRoute,+ sourceScoped: true+} as RosterRow++beforeEach(() => {+ vi.clearAllMocks()+ request.mockResolvedValue({})+ requestProfile.mockResolvedValue({})+})++describe('every source-scoped row resolves to an immutable owner', () => {+ it('routes only source-annotated rows, and freezes the descriptor', () => {+ expect(botConnectionRoute({ connectionId: 'local', name: 'writer' })).toBeNull()+ expect(botConnectionRoute({ name: 'writer' })).toBeNull()+ expect(Object.isFrozen(botConnectionRoute({ connectionId: 'spark', name: 'writer', sourceScoped: true }))).toBe(+ true+ )+ expect(botConnectionRoute({ connectionId: 'mac-mini', name: 'dixie', remoteSource: true })).toEqual({+ connectionId: 'mac-mini',+ mode: 'remote',+ profile: 'dixie',+ targetProfile: 'dixie'+ })+ })++ it('keeps Desktop identity separate from the backend target in the capability scope', () => {+ expect(+ botBackendProfileScope({+ connectionId: 'remote-a',+ mode: 'remote',+ profile: 'worker',+ targetProfile: 'backend-worker'+ })+ ).toEqual({ connectionId: 'remote-a', profile: 'backend-worker' })+ })+})++describe('requestForBot dispatches on the owner, not the active gateway', () => {+ it('sends source-scoped rows through requestProfile and local rows through request', async () => {+ await requestForBot({ name: 'local-bot' }, 'session.create', { title: 'x' })+ await requestForBot({ connectionId: 'local', name: 'local-bot', sourceScoped: true }, 'session.create', {+ title: 'x'+ })+ await requestForBot({ connectionId: 'mac-mini', name: 'dixie', remoteSource: true }, 'prompt.submit', {+ text: 'hi'+ })++ expect(request.mock.calls.map(([method]) => method)).toEqual(['session.create'])+ // A registered LOCAL source still uses the explicit descriptor.+ expect(requestProfile.mock.calls.map(([route, method]) => [route.connectionId, method])).toEqual([+ ['local', 'session.create'],+ ['mac-mini', 'prompt.submit']+ ])+ })++ it('translates every backend-profile RPC shape for a non-identity alias', async () => {+ await requestForBot(aliasBot, 'profiles.describe', { name: 'worker' })+ await requestForBot(aliasBot, 'profiles.configure', { name: 'worker', soul: 'x' })+ await requestForBot(aliasBot, 'profiles.create', { clone_from: 'worker', name: 'worker-2' })+ await requestForBot(aliasBot, 'session.create', { profile: 'worker', title: 'Bot Chat' })+ await requestForBot(aliasBot, 'cli.exec', { argv: ['--profile', 'worker', 'config', 'unset', 'model'] })+ await requestForBot(aliasBot, 'cli.exec', { argv: ['profile', 'describe', 'worker', '--text', 'worker'] })++ expect(requestProfile.mock.calls.map(([, , params]) => params)).toEqual([+ { name: 'backend-worker' },+ { name: 'backend-worker', soul: 'x' },+ { clone_from: 'backend-worker', name: 'worker-2' },+ { profile: 'backend-worker', title: 'Bot Chat' },+ { argv: ['--profile', 'backend-worker', 'config', 'unset', 'model'] },+ // Only the profile operand is rewritten — the trailing --text value is+ // the user's own argument and stays untouched.+ { argv: ['profile', 'describe', 'backend-worker', '--text', 'worker'] }+ ])+ // The route keeps Desktop's identity for the row throughout.+ expect(requestProfile.mock.calls.every(([route]) => route.profile === 'worker')).toBe(true)+ })+})++describe('a group room seats members from several machines', () => {+ it('source-qualifies remote member keys and leaves local ones bare', () => {+ // Bare names keep persisted-room compatibility for single-source rooms.+ expect(groupMemberKey({ name: 'ops' } as GroupMember)).toBe('ops')+ expect(groupMemberKey({ connectionId: 'mac-mini', name: 'dixie', remoteSource: true } as GroupMember)).toBe(+ 'mac-mini::dixie'+ )+ })++ it('resolves @name-device to the remote member, keeping same-named agents distinct', () => {+ const members = [+ { name: 'dixie', title: '' },+ { connectionId: 'mac-mini', handle: 'dixie-mac-mini', name: 'dixie', remoteSource: true }+ ] as GroupMember[]++ const parsed = parseGroupChatMentions('hey @dixie-mac-mini can you check disk space', members)++ expect([...parsed.mentioned]).toEqual(['mac-mini::dixie'])++ const responders = resolveGroupResponders(+ [{ at: 1, from: { kind: 'user', name: 'You' }, text: '@dixie-mac-mini ping' }],+ members+ )++ expect(responders).toHaveLength(1)+ expect(responders[0].remoteSource).toBe(true)+ })++ it('badges cross-connection speakers with their device in lines and turn prompts', () => {+ expect(+ formatGroupChatLine({ at: 1, from: { kind: 'member', name: 'dixie', source: 'Mac Mini' }, text: 'done' }, 'ops')+ ).toBe('dixie [Mac Mini]: done')+ expect(+ buildGroupChatTurnPrompt({+ deltaLines: ['You (user): hi'],+ groupName: 'infra',+ members: [+ { name: 'ops', title: '' },+ { connectionId: 'mac-mini', connectionLabel: 'Mac Mini', name: 'dixie', remoteSource: true }+ ] as GroupMember[],+ viewer: { name: 'ops' } as GroupMember+ })+ ).toMatch(/@dixie \[on Mac Mini\]/)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/data.bot-meta.test.ts b/apps/desktop/src/plugins/hermes-bots/data.bot-meta.test.tsnew file mode 100644index 00000000000..59940e5df98--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/data.bot-meta.test.ts@@ -0,0 +1,301 @@+/**+ * Bot metadata: the write path (`saveBotMeta`), the disk-load path+ * (`migrateBotMeta`), and the server-reconciliation overlay+ * (`mergeServerMeta`).+ *+ * Every case below is a shipped regression:+ * - a save must report a REAL remote failure differently from the documented+ * older-gateway fallback, or the editor toasts "remote persistence failed"+ * on every save forever;+ * - `profiles.set_asset` must fire only when the avatar actually changed — a+ * no-op `clear` from one machine raced another machine's just-pushed avatar+ * and wiped it server-side;+ * - a slow disk load must not wipe metadata written earlier in the session;+ * - the server overlay is authoritative for the fields it carries (a dropped+ * `chat` pointer, a disbanded group) but must NOT resurrect state a local+ * write already removed — the disband-resurrection fence.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import { $botMeta, botMetaWriteAt, saveBotMeta } from './data'+import { mergeServerMeta } from './profile-ops'+import type { RosterRow } from './types'++const { hostMock, storageMock } = vi.hoisted(() => ({+ hostMock: {+ agents: undefined as unknown,+ profileRoutes: undefined as unknown,+ request: vi.fn(),+ requestProfile: vi.fn(),+ state: { connectionId: { get: () => 'local' }, profile: { get: () => 'default' } }+ },+ storageMock: { get: vi.fn(), remove: vi.fn(), set: vi.fn() }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ forgetSessionUnread: vi.fn(),+ host: hostMock,+ queryClient: { invalidateQueries: vi.fn() },+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => ({ storage: storageMock }), ID: 'hermes-bots' }))++// profile-ops pulls in the roster surfaces for delete/duplicate; the overlay+// under test needs none of them.+vi.mock('./avatar-image', () => ({ isBackfilledFacePng: () => false }))+vi.mock('./canonical-chat', () => ({ ensureBotMetadata: vi.fn() }))++/** Every `host.request` recorded, with the params frozen at call time. */+function recordRequests(reply: (method: string) => unknown = () => ({})) {+ const calls: Array<{ method: string; params: Record<string, unknown> }> = []++ hostMock.request.mockImplementation(async (method: string, params: Record<string, unknown>) => {+ calls.push({ method, params: structuredClone(params ?? {}) })++ return reply(method)+ })++ return calls+}++beforeEach(() => {+ vi.clearAllMocks()+ $botMeta.set({})+ botMetaWriteAt.clear()+ storageMock.get.mockResolvedValue(null)+ storageMock.set.mockResolvedValue(undefined)+ storageMock.remove.mockResolvedValue(undefined)+ recordRequests()+})++describe('a save reports what the SERVER did, not just what the screen shows', () => {+ it('keeps the look locally and reports the remote failure', async () => {+ recordRequests(method => (method === 'profiles.configure' ? { applied: { ui_meta: false } } : {}))++ const result = await saveBotMeta('researcher', { color: '#38bdf8', custom: true, shape: 'cloud' })++ expect($botMeta.get().researcher).toMatchObject({ color: '#38bdf8', shape: 'cloud' })+ expect(result).toEqual({ serverOutcome: 'failed', serverPersisted: false })+ })++ it('reports success once ui_meta is applied', async () => {+ recordRequests(method => (method === 'profiles.configure' ? { applied: { ui_meta: true } } : {}))++ await expect(saveBotMeta('researcher', { color: '#8b5cf6', custom: true, shape: 'hexagon' })).resolves.toEqual({+ serverOutcome: 'persisted',+ serverPersisted: true+ })+ })++ it('treats an older gateway with no `applied` contract as unsupported, not failed', async () => {+ // An error toast on this path would fire on EVERY save forever.+ recordRequests(() => ({}))++ await expect(saveBotMeta('researcher', { custom: true, shape: 'circle' })).resolves.toEqual({+ serverOutcome: 'unsupported',+ serverPersisted: false+ })+ })++ it('treats a rejected configure the same way', async () => {+ hostMock.request.mockRejectedValue(new Error('param shape rejected'))++ await expect(saveBotMeta('researcher', { custom: true, shape: 'circle' })).resolves.toMatchObject({+ serverOutcome: 'unsupported'+ })+ })+})++describe('avatar asset sync fires only on a real change', () => {+ // Edit Profile always sends the image key, changed or not. Firing+ // set_asset for every patch re-uploaded the full data URL — and a no-op+ // `clear` from one machine could race another machine's just-pushed+ // avatar and wipe it server-side.+ it('pushes once, skips the re-save, clears on removal, ignores an absent key', async () => {+ const calls = recordRequests()+ const png = 'data:image/png;base64,AAAA'++ await saveBotMeta('ops', { image: png, title: 'One' })+ await saveBotMeta('ops', { image: png, title: 'Two' })+ await saveBotMeta('ops', { image: null, title: 'Three' })+ await saveBotMeta('ops', { title: 'Four' })++ expect(calls.filter(call => call.method === 'profiles.set_asset').map(call => call.params)).toEqual([+ { asset: 'avatar', data: png, name: 'ops' },+ { asset: 'avatar', clear: true, name: 'ops' }+ ])+ // Meta still merges per patch, and ui_meta sync is unaffected.+ expect($botMeta.get().ops.title).toBe('Four')+ expect(calls.filter(call => call.method === 'profiles.configure')).toHaveLength(4)+ })++ it('still pushes the copied avatar when a bot is duplicated', async () => {+ const calls = recordRequests()+ const png = 'data:image/png;base64,BBBB'++ await saveBotMeta('source', { image: png, title: 'Original' })+ await saveBotMeta('source-2', { image: png, title: 'Original (copy)' })++ // The fresh profile's image differs from its (empty) meta, so it pushes.+ expect(calls.filter(call => call.method === 'profiles.set_asset').map(call => call.params)).toEqual([+ { asset: 'avatar', data: png, name: 'source' },+ { asset: 'avatar', data: png, name: 'source-2' }+ ])+ })++ it('never ships the image or the pet icon inside ui_meta', async () => {+ // ui_meta rides every profiles.list and is capped at 64KB; the image goes+ // to the uncapped profile asset store instead.+ const calls = recordRequests()++ await saveBotMeta('ops', { image: 'data:image/png;base64,CCCC', pet: 'pet-cat', title: 'Ops' })++ const configure = calls.find(call => call.method === 'profiles.configure')+ const uiMeta = (configure?.params.ui_meta as Record<string, Record<string, unknown>>)['hermes-bots']++ expect(uiMeta).toEqual({ title: 'Ops' })+ })+})++describe('the disk load never clobbers a write from this session', () => {+ async function loadWithStorage(value: unknown) {+ vi.resetModules()++ const data = await import('./data')++ storageMock.get.mockImplementation(async (key: string) => (key === 'bot-meta' ? await value : null))++ return data+ }++ it('keeps a value written while the load was still in flight', async () => {+ let resolveStorage!: (value: unknown) => void++ const pending = new Promise(resolve => {+ resolveStorage = resolve+ })++ const data = await loadWithStorage(pending)++ void data.saveBotMeta('researcher', { pinned: true, title: 'Research' })+ expect(data.$botMeta.get().researcher.pinned).toBe(true)++ const migration = data.migrateBotMeta(storageMock)++ resolveStorage({ researcher: { title: 'Research' } })+ await migration++ expect(data.$botMeta.get().researcher).toMatchObject({ pinned: true, title: 'Research' })+ })++ it('still merges looks from disk under the fresher in-session write', async () => {+ const data = await loadWithStorage({ researcher: { color: '#38bdf8', shape: 'cloud', title: 'Research' } })++ void data.saveBotMeta('researcher', { pinned: true })+ await data.migrateBotMeta(storageMock)++ expect(data.$botMeta.get().researcher).toMatchObject({+ color: '#38bdf8',+ pinned: true,+ shape: 'cloud',+ title: 'Research'+ })+ })++ it('fills in bots this session has not touched', async () => {+ const data = await loadWithStorage({+ researcher: { pinned: true, title: 'Research' },+ writer: { title: 'Writer' }+ })++ await data.migrateBotMeta(storageMock)++ expect(data.$botMeta.get().researcher.pinned).toBe(true)+ expect(data.$botMeta.get().writer.title).toBe('Writer')+ })+})++describe('server metadata reconciliation', () => {+ const serverRow = (name: string, meta: Record<string, unknown>) =>+ ({ name, ui_meta: { 'hermes-bots': meta } }) as unknown as RosterRow++ it('removes a stale local canonical-chat pointer on sight', () => {+ // Identity is the profile's "Bot Chat" registry row, resolved by name.+ // Old `meta.chat` pointers must never look meaningful again.+ $botMeta.set({+ default: { chat: '4f6f6798ad6f', image: 'data:image/png;base64,avatar', pet: 'pet-cat', shape: 'cloud' }+ })++ mergeServerMeta([serverRow('default', { color: '#8b5cf6', shape: 'cloud', title: 'Hermana' })])++ const current = $botMeta.get().default++ expect(Object.hasOwn(current, 'chat')).toBe(false)+ // Local-only fields the server copy never carries survive the overlay.+ expect(current.image).toBe('data:image/png;base64,avatar')+ expect(current.pet).toBe('pet-cat')++ const [key, value] = storageMock.set.mock.calls.at(-1) as [string, Record<string, Record<string, unknown>>]++ expect(key).toBe('bot-meta')+ expect(Object.hasOwn(value.default, 'chat')).toBe(false)+ })++ it('drops the legacy scalar when authoritative groups say the membership is gone', () => {+ // A server-side `group: null` is represented by OMISSION, so retaining+ // the local scalar resurrects a membership another desktop just removed.+ $botMeta.set({ researcher: { group: 'Old', groups: ['Old'], title: 'Researcher' } })++ mergeServerMeta([serverRow('researcher', { groups: [], title: 'Researcher' })])++ const current = $botMeta.get().researcher++ expect(current.groups).toEqual([])+ expect(Object.hasOwn(current, 'group')).toBe(false)+ })++ it('leaves local metadata alone when the gateway has none', () => {+ $botMeta.set({ default: { chat: 'local-chat', shape: 'cloud' } })++ mergeServerMeta([{ name: 'default' } as RosterRow])++ expect($botMeta.get().default.chat).toBe('local-chat')+ expect(storageMock.set).not.toHaveBeenCalled()+ })++ it('cannot resurrect a membership a later local write removed (disband-resurrection)', async () => {+ $botMeta.set({ builder: { group: 'Team', groups: ['Team'], title: 'Builder' } })++ // Snapshot fetched now — its ui_meta still names the group.+ const staleFetchedAt = Date.now()+ const staleRow = serverRow('builder', { group: 'Team', groups: ['Team'], title: 'Builder' })++ // Disband path: the local write lands AFTER that fetch.+ await new Promise(resolve => setTimeout(resolve, 5))+ await saveBotMeta('builder', { group: null, groups: [] })+ expect($botMeta.get().builder.groups).toEqual([])++ mergeServerMeta([staleRow], staleFetchedAt)+ expect($botMeta.get().builder.groups).toEqual([])++ // A FRESH snapshot still gets the last word — server truth wins once it+ // actually post-dates the local change.+ mergeServerMeta([staleRow], Date.now() + 5)+ expect($botMeta.get().builder.groups).toEqual(['Team'])+ })++ it('overlays without a fence when the caller has no fetch time (older callers)', async () => {+ await saveBotMeta('builder', { group: null, groups: [] })+ mergeServerMeta([serverRow('builder', { groups: ['Team'] })])++ expect($botMeta.get().builder.groups).toEqual(['Team'])+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/data.cached-roster.test.ts b/apps/desktop/src/plugins/hermes-bots/data.cached-roster.test.tsnew file mode 100644index 00000000000..fe9a18b2272--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/data.cached-roster.test.ts@@ -0,0 +1,87 @@+/**+ * `cachedUnionRoster` is the imperative roster read — the @mention popover+ * must answer per keystroke and the composer middleware runs on submit, so+ * neither can wait on the hook.+ *+ * `useRoster` keys its query on `[...ROSTER_KEY, connectionId]`, one entry per+ * connection the window has been on. Reading it back with the BARE key is an+ * exact-key match in TanStack Query and therefore matches NOTHING — the+ * regression where completions offered no handles and remote `@name-device`+ * mentions passed through unresolved. The read has to fall back to a prefix+ * match over the key family, newest snapshot wins.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++const { cache, connection } = vi.hoisted(() => ({+ cache: new Map<string, { key: unknown[]; value: unknown }>(),+ connection: { id: 'local' }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')+ const keyOf = (key: unknown[]) => JSON.stringify(key)++ return {+ atom,+ host: { state: { connectionId: { get: () => connection.id }, profile: { get: () => 'default' } } },+ queryClient: {+ getQueriesData: ({ queryKey }: { queryKey: unknown[] }) =>+ [...cache.values()]+ .filter(entry => queryKey.every((part, index) => entry.key[index] === part))+ .map(entry => [entry.key, entry.value]),+ getQueryData: (key: unknown[]) => cache.get(keyOf(key))?.value,+ invalidateQueries: vi.fn(),+ setQueryData: (key: unknown[], value: unknown) => cache.set(keyOf(key), { key, value })+ },+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++const seed = (key: unknown[], value: unknown) => cache.set(JSON.stringify(key), { key, value })++beforeEach(() => {+ cache.clear()+ connection.id = 'local'+})++describe('cachedUnionRoster', () => {+ it('reads the entry useRoster wrote under the connection-suffixed key', async () => {+ const { cachedUnionRoster } = await import('./data')++ seed(['hermes-bots', 'roster', 'local'], { profiles: [{ name: 'default' }] })++ expect(cachedUnionRoster()?.profiles).toHaveLength(1)+ // The bare key is what the broken read used — it must still miss, or this+ // test would pass for the wrong reason.+ expect(cache.has(JSON.stringify(['hermes-bots', 'roster']))).toBe(false)+ })++ it('falls back to another connection’s entry when the window has moved', async () => {+ const { cachedUnionRoster } = await import('./data')++ seed(['hermes-bots', 'roster', 'vera'], { profiles: [{ connectionId: 'vera', name: 'default' }] })+ connection.id = 'local'++ expect(cachedUnionRoster()?.profiles?.[0]).toMatchObject({ connectionId: 'vera' })+ })++ it('prefers the freshest snapshot among several cached connections', async () => {+ const { cachedUnionRoster } = await import('./data')++ seed(['hermes-bots', 'roster', 'old'], { fetchedAt: 1_000, profiles: [{ name: 'stale' }] })+ seed(['hermes-bots', 'roster', 'new'], { fetchedAt: 9_000, profiles: [{ name: 'fresh' }] })+ connection.id = 'neither'++ expect(cachedUnionRoster()?.profiles?.[0]).toMatchObject({ name: 'fresh' })+ })++ it('reports nothing rather than throwing on a cold cache', async () => {+ const { cachedUnionRoster } = await import('./data')++ expect(cachedUnionRoster()).toBeNull()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/data.identity.test.ts b/apps/desktop/src/plugins/hermes-bots/data.identity.test.tsnew file mode 100644index 00000000000..e398be9fcb4--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/data.identity.test.ts@@ -0,0 +1,416 @@+/**+ * The identity layer every Bot Mode surface files a bot under: the @handle it+ * is tagged with, the friendly forms a rename makes taggable, the+ * source-qualified keys that keep two same-named bots apart, which session+ * counts as "what this bot is doing", roster search, and the needs-attention+ * badge.+ *+ * Drives the real `data` module (with real `labels` / `routing` underneath);+ * only the SDK is mocked.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import {+ $botAttention,+ $botMeta,+ botActivitySession,+ botFriendlyNames,+ botHandle,+ botMentionTag,+ botMetaKey,+ botRosterKey,+ botSelectionKey,+ clearBotAttention,+ filterBots,+ mentionNameForms,+ noteBotAttention,+ preferReachableSameNameRows,+ resolveRosterMentions+} from './data'+import { indexAliasRoutes } from './routing'+import type { RosterRow } from './types'++const { hostMock } = vi.hoisted(() => ({+ hostMock: {+ request: vi.fn(),+ requestProfile: vi.fn(),+ state: { connectionId: { get: vi.fn(() => 'local') }, profile: { get: vi.fn(() => 'default') } }+ }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom: nanoAtom } = await import('nanostores')++ return {+ atom: nanoAtom,+ host: hostMock,+ queryClient: undefined,+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++/** Gateway rows carry a session id on `last_session` that the plugin's+ * `SessionPreview` type deliberately does not model; the fixtures keep it so+ * "which session speaks for a bot" can be asserted by id. */+interface RowFixture extends Omit<Partial<RosterRow>, 'last_session'> {+ last_session?: { id?: string; last_active?: number; preview?: string }+}++const row = (bot: RowFixture) => bot as RosterRow++beforeEach(() => {+ vi.clearAllMocks()+ hostMock.state.connectionId.get.mockReturnValue('local')+ indexAliasRoutes([])+ $botMeta.set({})+ $botAttention.set({})+})++describe('the @handle a bot answers to', () => {+ it('presents the primary profile as @hermes — "default" never surfaces in the UI', () => {+ expect(botHandle('default')).toBe('hermes')+ expect(botHandle('ops')).toBe('ops')+ })++ it('prefers a precomputed multi-source handle over the bare name', () => {+ expect(botHandle('default', row({ handle: 'default-vera', name: 'default' }))).toBe('default-vera')+ })+})++describe('renamed bots stay taggable', () => {+ // Discord report, Aug 2026: renaming a bot — Bot Mode title or `hermes+ // profile rename` display_name — must change what you can @-tag it with,+ // while the old profile handle keeps resolving.+ it('reduces a friendly name to its slugged and collapsed forms', () => {+ expect(mentionNameForms('Research Buddy')).toEqual(['research-buddy', 'researchbuddy'])+ expect(mentionNameForms('Ops')).toEqual(['ops'])+ })++ it('drops reserved tokens so a rename cannot hijack a built-in tag', () => {+ expect(mentionNameForms('Hermes')).toEqual([])+ expect(mentionNameForms('@everyone')).toEqual([])+ expect(mentionNameForms('')).toEqual([])+ })++ it('inserts the renamed slug, falling back to the profile handle', () => {+ $botMeta.set({ writer: { title: 'Research Buddy' } })++ expect(botMentionTag(row({ name: 'writer' }))).toBe('research-buddy')+ expect(botMentionTag(row({ name: 'ops' }))).toBe('ops')+ expect(botMentionTag(row({ name: 'default' }))).toBe('hermes')+ // display_name (`hermes profile rename`) drives the tag too.+ expect(botMentionTag(row({ display_name: 'Deal Finder', name: 'scout' }))).toBe('deal-finder')+ })++ it('resolves a renamed bot by its friendly tag AND its old handle', () => {+ $botMeta.set({ writer: { title: 'Research Buddy' } })++ const roster = [+ row({ name: 'default' }),+ row({ name: 'writer' }),+ row({ display_name: 'Deal Finder', name: 'scout' })+ ]++ const live = { connectionId: 'local', name: 'default' }+ const names = (text: string) => resolveRosterMentions(text, roster, live).map(bot => bot.name)++ expect(names('hey @research-buddy check this')).toEqual(['writer'])+ expect(names('ping @dealfinder please')).toEqual(['scout'])+ expect(names('hey @writer')).toEqual(['writer'])+ })+})++describe('resolving @mentions against the roster', () => {+ const roster = [+ row({ connectionId: 'local', name: 'default' }),+ row({ connectionId: 'mac-mini', connectionLabel: 'Mac Mini', name: 'dixie', remoteSource: true }),+ row({ connectionId: 'mac-mini', handle: 'bob-mac-mini', name: 'bob', remoteSource: true })+ ]++ it('reaches Connections bots by bare name and by @name-device handle', () => {+ const live = { connectionId: 'local', name: 'default' }++ expect(resolveRosterMentions('@dixie how is disk space?', roster, live).map(bot => bot.name)).toEqual(['dixie'])+ expect(resolveRosterMentions('ping @bob-mac-mini', roster, live).map(bot => bot.name)).toEqual(['bob'])+ })++ it('never treats @hermes in your own chat as a handoff to yourself', () => {+ expect(resolveRosterMentions('@hermes do it', roster, { connectionId: 'local', name: 'default' })).toEqual([])+ // From ANOTHER bot's chat the same tag is a real handoff.+ expect(+ resolveRosterMentions('@hermes do it', roster, { connectionId: 'mac-mini', name: 'dixie' }).map(bot => bot.name)+ ).toEqual(['default'])+ })++ it('ignores tags inside code spans and fences', () => {+ const live = { connectionId: 'local', name: 'default' }++ expect(resolveRosterMentions('run `@dixie` literally', roster, live)).toEqual([])+ expect(resolveRosterMentions('```\n@dixie\n```', roster, live)).toEqual([])+ })++ it('refuses an ambiguous bare name — the device-qualified handle is required', () => {+ const twins = [+ row({ connectionId: 'a', handle: 'ops-a', name: 'ops', remoteSource: true }),+ row({ connectionId: 'b', handle: 'ops-b', name: 'ops', remoteSource: true })+ ]++ expect(resolveRosterMentions('@ops ping', twins, { connectionId: 'local', name: 'default' })).toEqual([])+ expect(+ resolveRosterMentions('@ops-b ping', twins, { connectionId: 'local', name: 'default' }).map(+ bot => bot.connectionId+ )+ ).toEqual(['b'])+ })+})++describe('source-qualified keys', () => {+ it('gives the same profile name on two sources distinct React keys', () => {+ const here = row({ connectionId: 'local', name: 'default' })+ const there = row({ connectionId: 'vera', name: 'default', remoteSource: true, sourceScoped: true })++ expect(botRosterKey(here)).not.toBe(botRosterKey(there))+ })++ it('keeps selection and metadata keys from colliding across connections', () => {+ const scoped = (connectionId: string) =>+ row({+ connectionId,+ name: 'default',+ route: { connectionId, mode: 'remote', profile: 'default', targetProfile: 'default' },+ sourceScoped: true+ })++ expect(botSelectionKey(scoped('a'))).not.toBe(botSelectionKey(scoped('b')))+ expect(botMetaKey(scoped('a'))).toBe('a::default')+ expect(botMetaKey(scoped('b'))).toBe('b::default')+ })++ it('leaves an unscoped legacy row on its bare name', () => {+ expect(botSelectionKey(row({ name: 'ops' }))).toBe('ops')+ expect(botMetaKey(row({ name: 'ops' }))).toBe('ops')+ })+})++describe('which session speaks for a bot', () => {+ // The "6d ago" bug: canonical Bot Chats are hidden from session lists, so+ // last_session alone never sees them — a bot you DM all day read as a week+ // idle because its newest VISIBLE session was a week old.+ const now = 1_000_000_000++ it('prefers the fresher canonical Bot Chat over a stale visible session', () => {+ const bot = row({+ canonical_session: { id: 'bot-chat', last_active: now - 5, preview: 'fresh DM' },+ last_session: { id: 'old-scratch', last_active: now - 6 * 86_400, preview: 'ancient' }+ })++ expect(botActivitySession(bot)?.preview).toBe('fresh DM')+ })++ it('keeps last_session when that is the fresher one', () => {+ const bot = row({+ canonical_session: { id: 'bot-chat', last_active: now - 3600, preview: 'older DM' },+ last_session: { id: 'scratch', last_active: now - 10, preview: 'just now' }+ })++ expect(botActivitySession(bot)?.preview).toBe('just now')+ })++ it('degrades to whichever summary an older gateway sent', () => {+ expect(botActivitySession(row({ last_session: { last_active: 1, preview: 'visible only' } }))?.preview).toBe(+ 'visible only'+ )+ expect(+ botActivitySession(row({ canonical_session: { id: 'canonical', last_active: 1, preview: 'chat only' } }))?.preview+ ).toBe('chat only')+ expect(botActivitySession(row({}))).toBeNull()+ expect(botActivitySession(null)).toBeNull()+ })+})++describe('roster search narrows without re-ranking', () => {+ const roster = [+ row({ name: 'agency-audio-designer', title: 'Audio Designer' }),+ row({ name: 'agency-ai-engineer', title: 'AI Engineer' }),+ row({ name: 'default' })+ ]++ const meta = { 'agency-audio-designer': { title: 'Sound Studio' }, default: {} }++ it('matches the visible display name, case-insensitively', () => {+ expect(filterBots(roster, meta, 'SOUND').map(bot => bot.name)).toEqual(['agency-audio-designer'])+ })++ it('matches profile handles and preserves roster order', () => {+ expect(filterBots(roster, meta, 'agency-').map(bot => bot.name)).toEqual([+ 'agency-audio-designer',+ 'agency-ai-engineer'+ ])+ expect(filterBots(roster, meta, '@hermes').map(bot => bot.name)).toEqual(['default'])+ expect(filterBots(roster, meta, 'default').map(bot => bot.name)).toEqual(['default'])+ })++ it('also matches roles, message previews, and the source device name', () => {+ const richer = [+ row({+ connectionLabel: 'Work Studio',+ description: 'Release quality and compliance',+ last_session: { id: 's1', last_active: 1, preview: 'Checked the deployment checklist' },+ name: 'reviewer'+ }),+ row({ description: 'Editorial support', name: 'writer' })+ ]++ expect(filterBots(richer, {}, 'compliance')[0].name).toBe('reviewer')+ expect(filterBots(richer, {}, 'deployment checklist')[0].name).toBe('reviewer')+ expect(filterBots(richer, {}, 'work studio')[0].name).toBe('reviewer')+ })++ it('returns the existing roster reference for a blank query', () => {+ expect(filterBots(roster, meta, ' ')).toBe(roster)+ })+})++describe('unreachable same-name twins (#92286)', () => {+ // After Desktop moves to the built-in This-device source, the old loopback+ // row (127.0.0.1:port, not listening) still sits beside the live profile+ // and looks like a second agent. Only sidebar tiles are filtered — routing+ // identities, group members and @-mentions still see every row.+ const live = row({ connectionId: 'local', name: 'default', sourceReachable: true, sourceScoped: true })+ const dead = row({ connectionId: 'loopback', name: 'default', sourceReachable: false, sourceScoped: true })++ it('drops a dead twin when a live copy exists', () => {+ expect(preferReachableSameNameRows([live, dead]).map(bot => bot.connectionId)).toEqual(['local'])+ })++ it('keeps two live sources sharing a profile name', () => {+ const other = row({ connectionId: 'vera', name: 'default', sourceReachable: true, sourceScoped: true })++ expect(preferReachableSameNameRows([live, other])).toHaveLength(2)+ })++ it('counts connect-on-demand as reachable', () => {+ const onDemand = row({+ connectionId: 'vera',+ name: 'default',+ sourceError: 'connect-on-demand',+ sourceScoped: true+ })++ expect(preferReachableSameNameRows([live, onDemand])).toHaveLength(2)+ })++ it('keeps an unreachable row when there is no live twin, so a down source still has a tile', () => {+ expect(preferReachableSameNameRows([dead])).toHaveLength(1)+ })++ it('keeps a ghost so a selected-but-offline owner is never replaced by a twin', () => {+ expect(preferReachableSameNameRows([live, { ...dead, ghost: true }])).toHaveLength(2)+ })++ it('does not mutate the input list', () => {+ const input = [live, dead]++ preferReachableSameNameRows(input)+ expect(input).toHaveLength(2)+ })+})++describe('needs-attention badge (#93091 item 3)', () => {+ // Background failures whose class is attention-worthy (auth, quota, missing+ // config, blocked) badge the roster tile; transient failures never do; the+ // bot's next good turn clears it.+ it('passes a typed reason code straight through', () => {+ for (const code of ['agent_blocked', 'missing_config', 'provider_auth_or_access', 'provider_quota_limit']) {+ noteBotAttention('radar', code)+ expect($botAttention.get().radar.reason).toBe(code)+ }+ })++ it('classifies the raw gateway error strings current backends emit', () => {+ const reasonFor = (text: string) => {+ $botAttention.set({})+ noteBotAttention('radar', text)++ return $botAttention.get().radar?.reason ?? null+ }++ // The anthropic 401 shape observed on current main.+ expect(+ reasonFor(+ 'Error code: 401 - {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}'+ )+ ).toBe('provider_auth_or_access')+ expect(reasonFor('No LLM provider configured. Run hermes model to pick one.')).toBe('missing_config')+ expect(reasonFor('No access token found for profile')).toBe('missing_config')+ expect(reasonFor('Your account is out of funds')).toBe('provider_quota_limit')+ expect(reasonFor('quota exceeded for this billing period')).toBe('provider_quota_limit')+ expect(reasonFor('agent is blocked awaiting approval')).toBe('agent_blocked')+ })++ it('never badges a transient class — a retryable error must not stick', () => {+ for (const text of [+ 'Rate limit exceeded, retry shortly',+ 'Error code: 429 - too many requests',+ '500 Internal Server Error',+ 'upstream 503 service unavailable',+ 'the model is overloaded, try again',+ 'request timed out after 180s',+ 'temporarily unavailable',+ '',+ null,+ undefined+ ]) {+ $botAttention.set({})+ noteBotAttention('radar', text)+ expect($botAttention.get()).toEqual({})+ }+ })++ it('keeps the latest failure per bot, independently, and clears on a good turn', () => {+ noteBotAttention('radar', 'Error code: 401 authentication_error')++ const first = $botAttention.get().radar++ expect(first.reason).toBe('provider_auth_or_access')+ expect(first.at).toBeGreaterThan(0)+ expect(first.message).toMatch(/401/)++ noteBotAttention('radar', 'No LLM provider configured')+ expect($botAttention.get().radar.reason).toBe('missing_config')++ noteBotAttention('dixie', 'quota exceeded')+ expect($botAttention.get().dixie.reason).toBe('provider_quota_limit')++ clearBotAttention('radar')+ expect($botAttention.get().radar).toBeUndefined()+ expect($botAttention.get().dixie.reason).toBe('provider_quota_limit')++ // Clearing an unbadged bot is a no-op.+ clearBotAttention('radar')+ clearBotAttention('')+ expect($botAttention.get().dixie.reason).toBe('provider_quota_limit')+ })+})++describe('alias identity reaches the mention layer (#89131)', () => {+ it('keeps @moxie resolving against the hosted row after handoff', () => {+ indexAliasRoutes([{ connectionId: 'cloud-abc', mode: 'remote', profile: 'moxie', targetProfile: 'default' }])+ $botMeta.set({ 'cloud-abc::moxie': { title: 'Moxie' } })++ const hostedRow = row({+ connectionId: 'cloud-abc',+ name: 'default',+ remoteSource: true,+ sourceScoped: true,+ targetProfile: 'default'+ })++ expect(botFriendlyNames(hostedRow).filter(Boolean)).toEqual(['Moxie'])+ expect(botMentionTag(hostedRow)).toBe('moxie')+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx b/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsxnew file mode 100644index 00000000000..60f558c9b63--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/data.roster.test.tsx@@ -0,0 +1,599 @@+/**+ * The multi-source roster merge, driven through the real `useRoster` query.+ *+ * The union agent roster (`host.agents`) enumerates EVERY registered+ * connection — including the gateway that just answered `profiles.list`. The+ * merge exists to fold the active source's agents into the rich rows it+ * already has, and to append only the genuinely-other sources. Getting that+ * classification wrong is the whole bug family this suite pins:+ *+ * - #88344 — a remote-primary desktop listed every bot twice, because the+ * active gateway's own agents were appended as phantom rows;+ * - the live-id override — after the user activates a non-primary source,+ * `profiles.list` answers from THAT source, so classifying against the+ * registry primary duplicated the active source's agents all over again;+ * - #88828 + #88697 composed — a primary registered under two addresses+ * collapses to one union row carrying the PRIMARY's connection id, and the+ * boot descriptor now reports that same id, so those rows must annotate;+ * - connect-on-demand — SSH sources drop off the union the moment their+ * tunnel is not the live gateway, so clicking the local agent emptied Bot+ * Mode until previously-painted rows were carried forward.+ */++import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderHook, waitFor } from '@testing-library/react'+import type { ReactNode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $lastRoster, useRoster } from './data'+import type { RosterRow } from './types'++const { hostMock } = vi.hoisted(() => ({+ hostMock: {+ agents: vi.fn(),+ profileRoutes: undefined as unknown,+ request: vi.fn(),+ requestProfile: vi.fn(),+ state: { connectionId: { get: vi.fn(() => 'local') }, profile: { get: () => 'default' } }+ }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')+ const { useQuery } = await import('@tanstack/react-query')++ return {+ atom,+ host: hostMock,+ queryClient: { getQueryData: vi.fn(), invalidateQueries: vi.fn() },+ useQuery,+ useValue: (store: { get: () => unknown }) => store.get()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++interface UnionAgent {+ connectionId: string+ connectionKind: string+ connectionLabel?: string+ handle: string+ profile: string+}++interface Union {+ agents: UnionAgent[]+ primaryConnectionId?: string+ sources?: Array<{ connectionId: string; error?: string; kind: string; reachable?: boolean }>+}++/** Gateway rows carry a session id on `last_session` that the plugin's+ * `SessionPreview` type deliberately does not model; the merge must carry it+ * through untouched, so the fixtures keep it. */+interface RowFixture extends Omit<Partial<RosterRow>, 'last_session'> {+ last_session?: { id?: string; last_active?: number; preview?: string }+}++/** Run the real roster query once and hand back the merged rows. */+async function mergedRoster(+ local: { profiles: RowFixture[] },+ union: Union | null,+ liveConnectionId: null | string = 'local'+): Promise<RowFixture[]> {+ hostMock.state.connectionId.get.mockReturnValue(liveConnectionId as string)+ hostMock.request.mockResolvedValue(local)++ if (union) {+ hostMock.agents.mockResolvedValue(union)+ } else {+ hostMock.agents.mockRejectedValue(new Error('no union roster on this build'))+ }++ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })++ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )++ const { result } = renderHook(() => useRoster(), { wrapper })++ await waitFor(() => expect(result.current.data).toBeTruthy())++ return (result.current.data?.profiles ?? []) as RowFixture[]+}++const identities = (rows: RowFixture[]) => rows.map(row => `${row.connectionId}:${row.name}`)++beforeEach(() => {+ vi.clearAllMocks()+ $lastRoster.set([])+})++afterEach(() => {+ $lastRoster.set([])+})++describe('no union roster', () => {+ it('leaves the local list exactly as it was', async () => {+ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 's1', last_active: 1 }, name: 'default' }] },+ null+ )++ expect(rows).toHaveLength(1)+ expect(rows[0].name).toBe('default')+ expect(rows[0].last_session?.id).toBe('s1')+ })++ it('appends nothing when the union is empty', async () => {+ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 's1', last_active: 1 }, name: 'default' }] },+ { agents: [] }+ )++ expect(identities(rows)).toEqual(['undefined:default'])+ })+})++describe('the active source annotates; other sources append', () => {+ it('keeps rich fields on the annotated row and tags the rest by source', async () => {+ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 's1', last_active: 1 }, name: 'research' }] },+ {+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'research-this-device',+ profile: 'research'+ },+ {+ connectionId: 'homelab',+ connectionKind: 'remote',+ connectionLabel: 'Homelab',+ handle: 'research-homelab',+ profile: 'research'+ },+ {+ connectionId: 'homelab',+ connectionKind: 'remote',+ connectionLabel: 'Homelab',+ handle: 'coder',+ profile: 'coder'+ }+ ]+ }+ )++ expect(rows).toHaveLength(3)++ const annotated = rows.find(row => row.name === 'research' && !row.remoteSource)!++ expect(annotated.last_session?.id).toBe('s1')+ expect(annotated.handle).toBe('research-this-device')+ expect(annotated.sourceScoped).toBe(true)+ expect(annotated.remoteSource).toBeUndefined()++ expect(rows.find(row => row.name === 'research' && row.remoteSource)).toMatchObject({+ connectionId: 'homelab',+ connectionLabel: 'Homelab',+ handle: 'research-homelab'+ })+ expect(rows.find(row => row.name === 'coder')).toMatchObject({ handle: 'coder', remoteSource: true })+ })++ it('never invents a thin row for an active-source profile profiles.list did not return', async () => {+ // An older backend mid-refresh: skip rather than paint a bot that has no+ // rich row behind it.+ const rows = await mergedRoster(+ { profiles: [{ name: 'default' }] },+ {+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'ghost',+ profile: 'ghost'+ }+ ]+ }+ )++ expect(rows.map(row => row.name)).toEqual(['default'])+ })++ it('renders duplicate source and local identities once', async () => {+ const rows = await mergedRoster(+ {+ profiles: [+ { last_session: { id: 'newest', last_active: 2 }, name: 'default' },+ { last_session: { id: 'stale', last_active: 1 }, name: 'default' }+ ]+ },+ {+ agents: [+ { connectionId: 'local', connectionKind: 'local', handle: 'default-this-device', profile: 'default' },+ { connectionId: 'local', connectionKind: 'local', handle: 'default-this-device', profile: 'default' },+ {+ connectionId: 'homelab',+ connectionKind: 'remote',+ connectionLabel: 'Homelab',+ handle: 'default-homelab',+ profile: 'default'+ },+ {+ connectionId: 'homelab',+ connectionKind: 'remote',+ connectionLabel: 'Homelab',+ handle: 'default-homelab',+ profile: 'default'+ }+ ]+ }+ )++ expect(rows).toHaveLength(2)+ expect(rows[0].last_session?.id).toBe('newest')+ expect(rows[0].handle).toBe('default-this-device')+ expect(rows[1].connectionId).toBe('homelab')+ })++ it('follows the ACTIVE remote source, so the local twin is the appended one', async () => {+ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 'remote-session', last_active: 1 }, name: 'default' }] },+ {+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default-this-device',+ profile: 'default'+ },+ {+ connectionId: 'work',+ connectionKind: 'remote',+ connectionLabel: 'Work',+ handle: 'default-work',+ profile: 'default'+ }+ ]+ },+ 'work'+ )++ const active = rows.find(row => row.connectionId === 'work')!++ expect(active.remoteSource).toBeUndefined()+ expect(active.sourceScoped).toBe(true)+ expect(active.last_session?.id).toBe('remote-session')+ expect(rows.find(row => row.connectionId === 'local')).toMatchObject({+ remoteSource: true,+ sourceScoped: true+ })+ })++ it('annotates every active-gateway agent instead of duplicating them (#88344)', async () => {+ const primary = '10-244-108-128-9119'++ const rows = await mergedRoster(+ {+ profiles: [+ { last_session: { id: 's-default', last_active: 1 }, name: 'default' },+ { last_session: { id: 's-dev', last_active: 1 }, name: 'dev' }+ ]+ },+ {+ agents: [+ // The ACTIVE remote gateway itself — same identities as the rich+ // rows, so it must annotate in place.+ {+ connectionId: primary,+ connectionKind: 'remote',+ connectionLabel: '10.244.108.128:9119',+ handle: `default-${primary}`,+ profile: 'default'+ },+ {+ connectionId: primary,+ connectionKind: 'remote',+ connectionLabel: '10.244.108.128:9119',+ handle: 'dev',+ profile: 'dev'+ },+ // A genuinely separate source with a same-named profile keeps its row.+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default-this-device',+ profile: 'default'+ },+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'agent-mentor',+ profile: 'agent-mentor'+ }+ ],+ primaryConnectionId: primary+ },+ primary+ )++ // 2 annotated rows + 2 other-source rows = 4, NOT 6.+ expect(rows).toHaveLength(4)+ expect(rows.filter(row => row.remoteSource)).toHaveLength(2)++ const annotated = rows.find(row => row.name === 'default' && !row.remoteSource)!++ expect(annotated.last_session?.id).toBe('s-default')+ expect(annotated.handle).toBe(`default-${primary}`)+ expect(rows.find(row => row.name === 'default' && row.remoteSource)).toMatchObject({+ connectionId: 'local',+ handle: 'default-this-device'+ })+ })++ it('keeps single-source behavior on a primary-local desktop', async () => {+ const rows = await mergedRoster(+ { profiles: [{ name: 'default' }, { name: 'dev' }] },+ {+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default-this-device',+ profile: 'default'+ },+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'dev',+ profile: 'dev'+ }+ ],+ primaryConnectionId: 'local'+ }+ )++ expect(rows).toHaveLength(2)+ expect(rows.filter(row => row.remoteSource)).toHaveLength(0)+ expect(rows[0].handle).toBe('default-this-device')+ })++ it('lets the live id beat primaryConnectionId', async () => {+ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 's1', last_active: 1 }, name: 'default' }] },+ {+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default-this-device',+ profile: 'default'+ },+ {+ connectionId: 'vps',+ connectionKind: 'remote',+ connectionLabel: 'VPS',+ handle: 'default-vps',+ profile: 'default'+ }+ ],+ primaryConnectionId: 'local'+ },+ 'vps'+ )++ expect(rows).toHaveLength(2)+ expect(rows.find(row => row.last_session)?.handle).toBe('default-vps')+ expect(rows.filter(row => row.remoteSource).map(row => row.connectionId)).toEqual(['local'])+ })++ it('composes the install_id collapse with the live id, with no re-append (#88828 + #88697)', async () => {+ const rows = await mergedRoster(+ {+ profiles: [+ { last_session: { id: 's-default', last_active: 1 }, name: 'default' },+ { last_session: { id: 's-dev', last_active: 1 }, name: 'dev' }+ ]+ },+ {+ agents: [+ // Post-#88828 union: the tailscale twin of the primary collapsed+ // into these rows — one per profile, keyed to the PRIMARY id.+ {+ connectionId: 'spark-lan',+ connectionKind: 'remote',+ connectionLabel: 'Spark',+ handle: 'default-spark',+ profile: 'default'+ },+ {+ connectionId: 'spark-lan',+ connectionKind: 'remote',+ connectionLabel: 'Spark',+ handle: 'dev',+ profile: 'dev'+ },+ // A real second backend survives the collapse as its own row.+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default-this-device',+ profile: 'default'+ }+ ],+ primaryConnectionId: 'spark-lan'+ },+ 'spark-lan'+ )++ // Pre-fix (live id null) this was 5: both primary rows re-appended.+ expect(rows).toHaveLength(3)+ expect(rows.filter(row => row.remoteSource).map(row => row.connectionId)).toEqual(['local'])+ expect(rows.find(row => row.name === 'default' && !row.remoteSource)).toMatchObject({+ connectionId: 'spark-lan',+ handle: 'default-spark'+ })+ })+})++describe('a null live id', () => {+ it('does not treat the registry primary as active on a local window', async () => {+ // Clicking the local agent leaves host.state.connectionId null while the+ // registry primary stays on Spark. That must not skip Spark's bots or+ // invent a second "This device" shadow of default.+ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 'this-chat', last_active: 1 }, name: 'default' }] },+ {+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default-this-device',+ profile: 'default'+ },+ { connectionId: 'spark', connectionKind: 'ssh', connectionLabel: 'Spark', handle: 'bob', profile: 'bob' },+ { connectionId: 'spark', connectionKind: 'ssh', connectionLabel: 'Spark', handle: 'kai', profile: 'kai' },+ { connectionId: 'spark', connectionKind: 'ssh', connectionLabel: 'Spark', handle: 'rook', profile: 'rook' }+ ],+ primaryConnectionId: 'spark'+ },+ null+ )++ expect(rows.filter(row => row.name === 'default')).toHaveLength(1)+ expect(rows.find(row => row.name === 'default')?.last_session?.id).toBe('this-chat')+ expect(rows.filter(row => row.remoteSource && row.connectionId === 'local')).toHaveLength(0)+ expect(+ rows+ .filter(row => row.remoteSource)+ .map(row => row.name)+ .sort()+ ).toEqual(['bob', 'kai', 'rook'])+ })++ it('infers a matching remote primary when the local inventory does not match', async () => {+ // Legacy remote descriptors carry mode:'remote' but no connectionId, so+ // the host state reads null even though profiles.list is answering from+ // the registry primary.+ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 'noah-chat', last_active: 1 }, name: 'default' }] },+ {+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'archie',+ profile: 'archie'+ },+ {+ connectionId: 'noah',+ connectionKind: 'remote',+ connectionLabel: 'Noah',+ handle: 'default',+ profile: 'default'+ }+ ],+ primaryConnectionId: 'noah'+ },+ null+ )++ expect(rows).toHaveLength(2)++ const inferred = rows.find(row => row.name === 'default')!++ expect(inferred.connectionId).toBe('noah')+ expect(inferred.remoteSource).toBeUndefined()+ expect(rows.find(row => row.name === 'archie')).toMatchObject({ connectionId: 'local', remoteSource: true })+ })+})++describe('connect-on-demand sources', () => {+ const previouslyPainted = (connectionId: string) =>+ [+ { last_session: { id: 'this-chat', last_active: 1 }, name: 'default' },+ {+ connectionId,+ connectionKind: 'ssh',+ connectionLabel: 'Spark',+ handle: 'bob',+ name: 'bob',+ remoteSource: true,+ sourceScoped: true+ }+ ] as RosterRow[]++ const localOnlyUnion = (sources: Union['sources']): Union => ({+ agents: [+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default',+ profile: 'default'+ }+ ],+ primaryConnectionId: 'local',+ sources+ })++ it('carries a previously painted remote row through an empty union', async () => {+ $lastRoster.set(previouslyPainted('spark'))++ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 'this-chat', last_active: 1 }, name: 'default' }] },+ localOnlyUnion([{ connectionId: 'spark', error: 'connect-on-demand', kind: 'ssh' }])+ )++ expect(rows.find(row => row.name === 'bob' && row.connectionId === 'spark')).toMatchObject({ remoteSource: true })+ expect(rows.filter(row => row.name === 'default')).toHaveLength(1)+ })++ it('does not resurrect a row whose connection was removed from the registry', async () => {+ $lastRoster.set(previouslyPainted('gone'))++ const rows = await mergedRoster(+ { profiles: [{ last_session: { id: 'this-chat', last_active: 1 }, name: 'default' }] },+ localOnlyUnion([{ connectionId: 'local', kind: 'local' }])+ )++ expect(rows.find(row => row.connectionId === 'gone')).toBeUndefined()+ })+})++describe('a stalled profiles.list cannot pin the spinner forever', () => {+ it('gives up after bounded retries and surfaces the error', async () => {+ // `retry: true` keeps React Query in isLoading until the first success, so+ // a stalled profiles.list (live state.db write lock, SSH flap) left the+ // Bots sidebar on a spinner with no error card. The 5s refetchInterval and+ // the gateway-open effect already recover drops.+ hostMock.state.connectionId.get.mockReturnValue('local')+ hostMock.request.mockRejectedValue(new Error('state.db is locked'))++ const client = new QueryClient({ defaultOptions: { queries: { retryDelay: 0 } } })++ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )++ const { result } = renderHook(() => useRoster(), { wrapper })++ await waitFor(() => expect(result.current.isError).toBe(true), { timeout: 5000 })++ expect(result.current.isLoading).toBe(false)+ expect(hostMock.request.mock.calls.length).toBeGreaterThan(1)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-activity.test.ts b/apps/desktop/src/plugins/hermes-bots/group-activity.test.tsnew file mode 100644index 00000000000..dab490020b7--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-activity.test.ts@@ -0,0 +1,271 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as data from './data'+import type { GroupActivityEntry } from './group-activity'+import type * as groupActivity from './group-activity'+import type * as groupChat from './group-chat'+import type * as groupRounds from './group-rounds'+import { createGroupGateway, drain, runTimersInline, scriptedStorage } from './group-test-utils'+import type { GatewayOptions, ScriptedGateway } from './group-test-utils'+import type { GroupMember } from './types'++// Collapsible group Activity view: a runtime-only, bounded feed of truthful+// turn events (queued / working / replied / passed / timed-out / failed /+// cancelled / settled / delivered) that the room shows in a quiet disclosure.+// The transcript stays the only durable record — activity is never persisted.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')++ return pluginSdkMock(host)+})++const MEMBERS: GroupMember[] = [+ { name: 'research', title: '' },+ { name: 'builder', title: '' },+ { name: 'ops', title: 'The Ops' }+]++/** A failed turn's activity row carries the typed reason the gateway sent.+ * `recordGroupActivity` spreads it through, so it isn't on the entry type. */+type ActivityRow = GroupActivityEntry & { reason?: string }++interface Room {+ activity: typeof groupActivity+ chat: typeof groupChat+ data: typeof data+ gateway: ScriptedGateway+ rounds: typeof groupRounds+}++async function loadRoom(options: GatewayOptions = {}): Promise<Room> {+ vi.resetModules()+ const gateway = createGroupGateway(options)++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [activity, chat, data, rounds, shared] = await Promise.all([+ import('./group-activity'),+ import('./group-chat'),+ import('./data'),+ import('./group-rounds'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { activity, chat, data, gateway, rounds }+}++function feed(room: Room, group: string): ActivityRow[] {+ return (room.activity.$groupActivity.get()[group]?.events || []) as ActivityRow[]+}++beforeEach(() => {+ runTimersInline()+})++describe('turn arc', () => {+ it('a settled turn records the full truthful arc: queued, working, replies and passes, settled', async () => {+ const room = await loadRoom({+ turn: ({ profile, prompt }) =>+ profile === 'research' && !prompt.includes('(you)') ? 'I looked into it — ship it.' : '(pass)'+ })++ room.rounds.sendToGroupChat('Room', MEMBERS, 'please review')+ await drain(() => Boolean(room.chat.$groupChats.get().Room?.running))++ const events = feed(room, 'Room')+ const kinds = events.map(event => event.kind)++ expect(kinds[0]).toBe('queued')+ expect(kinds[kinds.length - 1]).toBe('settled')+ expect(kinds.filter(kind => kind === 'working').length).toBeGreaterThanOrEqual(3)+ expect(kinds).toContain('replied')+ expect(kinds.filter(kind => kind === 'passed').length).toBeGreaterThanOrEqual(2)+ expect(events.find(event => event.kind === 'replied')?.member).toBe('research')+ })++ it('a failed member turn records failed instead of a phantom reply', async () => {+ const room = await loadRoom({+ turn: ({ profile }) => {+ if (profile === 'builder') {+ throw new Error('gateway hiccup')+ }++ return '(pass)'+ }+ })++ room.rounds.sendToGroupChat('Flaky', MEMBERS, 'anyone around?')+ await drain(() => Boolean(room.chat.$groupChats.get().Flaky?.running))++ expect(feed(room, 'Flaky').some(event => event.kind === 'failed' && event.member === 'builder')).toBe(true)+ })++ it('a failed member turn preserves and prefers its typed reason', async () => {+ const room = await loadRoom({+ turn: ({ profile }) => {+ if (profile === 'builder') {+ throw Object.assign(new Error('generic gateway failure'), {+ data: { reason: 'provider_auth_or_access' }+ })+ }++ return '(pass)'+ }+ })++ room.rounds.sendToGroupChat('Typed failure', MEMBERS, 'anyone around?')+ await drain(() => Boolean(room.chat.$groupChats.get()['Typed failure']?.running))++ const failed = feed(room, 'Typed failure').find(event => event.kind === 'failed' && event.member === 'builder')++ expect(failed?.reason).toBe('provider_auth_or_access')+ expect(Object.values(room.data.$botAttention.get())[0]?.reason).toBe('provider_auth_or_access')+ })++ it('an untyped failed member turn keeps the message-classification fallback', async () => {+ const room = await loadRoom({+ turn: ({ profile }) => {+ if (profile === 'builder') {+ throw new Error('No LLM provider configured')+ }++ return '(pass)'+ }+ })++ room.rounds.sendToGroupChat('Untyped failure', MEMBERS, 'anyone around?')+ await drain(() => Boolean(room.chat.$groupChats.get()['Untyped failure']?.running))++ const failed = feed(room, 'Untyped failure').find(event => event.kind === 'failed' && event.member === 'builder')++ expect(failed?.reason).toBeUndefined()+ expect(Object.values(room.data.$botAttention.get())[0]?.reason).toBe('missing_config')+ })+})++describe('epoch scoping', () => {+ it('a newer send interrupts the previous run and records cancelled in the CURRENT epoch', async () => {+ const gates = new Map<number, { promise: Promise<string>; resolve: (value: string) => void }>()++ const gate = (n: number) => {+ const existing = gates.get(n)++ if (existing) {+ return existing.promise+ }++ let resolve!: (value: string) => void++ const promise = new Promise<string>(settle => {+ resolve = settle+ })++ gates.set(n, { promise, resolve })++ return promise+ }++ const room = await loadRoom({ turn: ({ n }) => gate(n) })+ const member: GroupMember[] = [{ name: 'research', title: '' }]++ room.rounds.sendToGroupChat('Busy', member, 'first ask')+ await drain(() => room.gateway.calls.length < 1, 50)+ room.rounds.sendToGroupChat('Busy', member, 'second ask, supersede')+ await drain(() => room.gateway.calls.length < 2, 50)++ gates.get(2)?.resolve('from the new run')+ await drain(() => Boolean(room.chat.$groupChats.get().Busy?.running))+ gates.get(1)?.resolve('late from the old run')+ await drain(() => false)++ const epoch = room.chat.$groupChats.get().Busy?.epoch || 0++ expect(feed(room, 'Busy').some(event => event.kind === 'cancelled')).toBe(true)+ // The view shows only the current run: every visible event is this epoch.+ expect(room.activity.currentGroupActivity('Busy').every(event => (event.epoch || 0) === epoch)).toBe(true)+ expect(room.activity.currentGroupActivity('Busy').some(event => event.kind === 'cancelled')).toBe(true)+ })++ it('epoch filtering drops events from a superseded run', async () => {+ const room = await loadRoom()+ room.chat.updateGroupChat('Epoch', current => {+ current.log = []+ current.epoch = 5++ return current+ })+ room.activity.recordGroupActivity('Epoch', { kind: 'queued', member: 'You' })+ room.activity.recordGroupActivity('Epoch', { kind: 'working', member: 'research' })++ room.chat.updateGroupChat('Epoch', current => {+ current.epoch = 6++ return current+ })++ expect(room.activity.currentGroupActivity('Epoch')).toHaveLength(0)++ room.activity.recordGroupActivity('Epoch', { kind: 'working', member: 'research' })+ const current = room.activity.currentGroupActivity('Epoch')++ expect(current).toHaveLength(1)+ expect(current[0].kind).toBe('working')+ })+})++describe('feed shape', () => {+ it('the feed is bounded: it stops growing and keeps the newest events', async () => {+ const room = await loadRoom()+ room.chat.updateGroupChat('Cap', current => {+ current.log = []++ return current+ })++ for (let i = 0; i < 500; i++) {+ room.activity.recordGroupActivity('Cap', { kind: 'working', member: `member-${i}` })+ }++ const bounded = feed(room, 'Cap')++ expect(bounded.length).toBeLessThan(500)+ expect(bounded[bounded.length - 1].member).toBe('member-499')+ expect(bounded.some(event => event.member === 'member-0')).toBe(false)++ room.activity.recordGroupActivity('Cap', { kind: 'working', member: 'one more' })++ expect(feed(room, 'Cap')).toHaveLength(bounded.length)+ })++ it('activity is runtime-only: never persisted, never hydrated', async () => {+ const room = await loadRoom()++ room.rounds.sendToGroupChat('Volatile', MEMBERS, 'hello')+ await drain(() => Boolean(room.chat.$groupChats.get().Volatile?.running))++ expect(feed(room, 'Volatile').length).toBeGreaterThan(0)+ expect([...room.gateway.storage.keys()]).not.toContain('group-activity')+ })++ it('labels read like a person wrote them, with settled/cancelled as room-level lines', async () => {+ const { activity } = await loadRoom()++ const label = (event: Omit<GroupActivityEntry, 'at' | 'epoch'>) =>+ activity.groupActivityLabel({ at: 0, epoch: 0, ...event })++ expect(label({ kind: 'queued', member: 'You' })).toBe('You sent a message')+ expect(label({ kind: 'replied', member: 'research' })).toBe('research replied')+ expect(label({ kind: 'timed-out', member: 'ops' })).toBe('ops took too long')+ expect(label({ kind: 'cancelled', member: null })).toBe('turn interrupted by a newer message')+ expect(label({ kind: 'settled', member: null })).toBe('turn settled')+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-bot-handoff.test.ts b/apps/desktop/src/plugins/hermes-bots/group-bot-handoff.test.tsnew file mode 100644index 00000000000..cfc21bdc0ec--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-bot-handoff.test.ts@@ -0,0 +1,175 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as groupChat from './group-chat'+import type * as groupChatView from './group-chat-view'+import type * as groupPanes from './group-panes'+import { createGroupGateway, runTimersInline, scriptedStorage } from './group-test-utils'+import type { ScriptedGateway } from './group-test-utils'+import type * as rosterActions from './roster-actions'+import type { GroupChat, RosterRow } from './types'++// Clicking a bot while a group room owns the center is a HANDOFF: the room's+// main-window tab has to be retired before the canonical chat opens, or two+// surfaces fight for the center. And if the open fails, the room the user was+// reading has to come back — the failed action must not steal the center.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++const { openBotCanonicalChat, prepareBotSource } = vi.hoisted(() => ({+ openBotCanonicalChat: vi.fn(),+ prepareBotSource: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')+ const base = await pluginSdkMock(host)++ return {+ ...base,+ ackStoredSessionId: vi.fn(),+ haptic: vi.fn(),+ markSessionUnreadFinished: vi.fn()+ }+})++vi.mock('./canonical-chat', () => ({+ notifyBotOpenFailure: (...args: unknown[]) => {+ failures.push(args)+ },+ openBotCanonicalChat: (...args: unknown[]) => openBotCanonicalChat(...args),+ prepareBotSource: (...args: unknown[]) => prepareBotSource(...args)+}))++const failures: unknown[][] = []++interface Room {+ actions: typeof rosterActions+ chat: typeof groupChat+ gateway: ScriptedGateway+ panes: typeof groupPanes+ view: typeof groupChatView+}++async function loadRoom(): Promise<Room> {+ vi.resetModules()+ const gateway = createGroupGateway()++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [actions, chat, panes, view, shared] = await Promise.all([+ import('./roster-actions'),+ import('./group-chat'),+ import('./group-panes'),+ import('./group-chat-view'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { actions, chat, gateway, panes, view }+}++const BOT: RosterRow = { name: 'alpha', title: 'Alpha' }++/** Seat a room and front it as a main-window tab, recording tab closes in+ * the order they happen relative to the canonical open. */+function registerGroup(room: Room, group: string, timeline: string[]) {+ room.chat.$groupChats.set({+ ...room.chat.$groupChats.get(),+ [group]: { log: [], sessions: {}, watermarks: {} }+ } as unknown as Record<string, GroupChat>)+ host.openWorkspace = (id: string) => () => timeline.push(`close:${id}`)+ room.view.openGroupChat(group)+}++beforeEach(() => {+ runTimersInline()+ failures.length = 0+ prepareBotSource.mockReset().mockResolvedValue(undefined)+ openBotCanonicalChat.mockReset().mockResolvedValue({ openedId: 'stored-chat', registryId: 'stored-chat' })+})++describe('opening a bot from a fronted room', () => {+ it('retires the group tab BEFORE the canonical open', async () => {+ const timeline: string[] = []+ const room = await loadRoom()+ registerGroup(room, 'Core', timeline)+ openBotCanonicalChat.mockImplementation(async () => {+ timeline.push('canonicalOpen')++ return { openedId: 'stored-chat', registryId: 'stored-chat' }+ })++ expect(await room.actions.openRosterBot(BOT)).toBe(true)+ expect(timeline.filter(event => event.includes(':group:'))).toHaveLength(1)+ expect(timeline.findIndex(event => event.includes(':group:'))).toBeLessThan(timeline.indexOf('canonicalOpen'))+ expect(room.panes.groupChatMainTabs.has('Core')).toBe(false)+ })++ it('is safe with no room fronted', async () => {+ const timeline: string[] = []+ const room = await loadRoom()+ host.openWorkspace = (id: string) => () => timeline.push(`close:${id}`)++ expect(await room.actions.openRosterBot(BOT)).toBe(true)+ expect(timeline).toHaveLength(0)+ })+})++describe('a failed open must not steal the center', () => {+ it('restores the group and surfaces the error when the canonical open rejects', async () => {+ const timeline: string[] = []+ const room = await loadRoom()+ registerGroup(room, 'Core', timeline)+ openBotCanonicalChat.mockRejectedValue(new Error('canonical open failed'))++ expect(await room.actions.openRosterBot(BOT)).toBe(false)+ expect(timeline.filter(event => event.includes(':group:'))).toHaveLength(1)+ expect(room.chat.$groupChatWorkspace.get()).toBe('Core')+ // Re-fronted, not merely re-selected: the tab is registered again.+ expect(room.panes.groupChatMainTabs.has('Core')).toBe(true)+ expect(failures).toHaveLength(1)+ })++ it('restores the group when source preparation rejects', async () => {+ const room = await loadRoom()+ registerGroup(room, 'Core', [])+ prepareBotSource.mockRejectedValue(new Error('source preparation failed'))++ expect(await room.actions.openRosterBot({ ...BOT, connectionId: 'local', sourceScoped: true })).toBe(false)+ expect(room.chat.$groupChatWorkspace.get()).toBe('Core')+ })++ it('restores the room by its immutable roomId, so a rename mid-open still finds it', async () => {+ const room = await loadRoom()+ room.chat.$groupChats.set({+ Core: { log: [], roomId: 'r-core', sessions: {}, watermarks: {} }+ } as unknown as Record<string, GroupChat>)+ host.openWorkspace = () => () => undefined+ room.view.openGroupChat('Core')+ openBotCanonicalChat.mockImplementation(async () => {+ const rooms = room.chat.$groupChats.get()+ room.chat.$groupChats.set({ Renamed: rooms.Core } as unknown as Record<string, GroupChat>)+ throw new Error('canonical open failed')+ })++ expect(await room.actions.openRosterBot(BOT)).toBe(false)+ expect(room.chat.$groupChatWorkspace.get()).toBe('Renamed')+ })++ it('does not resurrect a room that was disbanded during the open', async () => {+ const room = await loadRoom()+ registerGroup(room, 'Core', [])+ openBotCanonicalChat.mockImplementation(async () => {+ room.chat.$groupChats.set({})+ throw new Error('canonical open failed')+ })++ expect(await room.actions.openRosterBot(BOT)).toBe(false)+ expect(room.chat.$groupChatWorkspace.get()).toBeNull()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-parts.test.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-parts.test.tsxnew file mode 100644index 00000000000..08823603726--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-parts.test.tsx@@ -0,0 +1,209 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { useState } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { GroupMember } from './types'++// Group-composer mentions (#89049): the core composer's @-completion area+// doesn't mount inside workspace tiles, so the room's composers wrap the SDK+// input with a member-scoped popover of their own. Everything it inserts has+// to be a string parseGroupChatMentions resolves.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')+ const base = await pluginSdkMock(host)++ return {+ ...base,+ Button: (props: React.ComponentProps<'button'>) => <button type="button" {...props} />,+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+ Codicon: () => null,+ Input: (props: React.ComponentProps<'input'>) => <input {...props} />,+ RowButton: (props: React.ComponentProps<'button'>) => <button type="button" {...props} />,+ Textarea: (props: React.ComponentProps<'textarea'>) => <textarea {...props} />,+ useI18n: () => ({ t: (_key: string, fallback: string) => fallback })+ }+})++const MEMBERS: GroupMember[] = [+ { handle: 'alpha', name: 'alpha', title: '' },+ { handle: 'builder', name: 'builder', title: '' }+]++/** Render the composer the way a room does: value owned by the caller (the+ * draft atom in production), popover scoped to the seated members. */+async function mount(initial = '') {+ const { GroupMentionInput } = await import('./group-chat-parts')+ const onChange = vi.fn()+ const onSubmitDraft = vi.fn()++ function Harness() {+ const [value, setValue] = useState(initial)++ return (+ <GroupMentionInput+ aria-label="Message Core"+ members={MEMBERS}+ onChange={next => {+ onChange(next)+ setValue(next)+ }}+ onSubmitDraft={onSubmitDraft}+ value={value}+ />+ )+ }++ render(<Harness />)++ return { input: screen.getByLabelText('Message Core') as HTMLTextAreaElement, onChange, onSubmitDraft }+}++/** Type `text`, then park the caret at `caret` (default: end of the text).+ * The click is how the component re-reads the caret without a keystroke —+ * jsdom does not preserve a selection across React's controlled re-write. */+function typeInto(input: HTMLTextAreaElement, text: string, caret = text.length) {+ fireEvent.change(input, { target: { value: text } })+ input.setSelectionRange(caret, caret)+ fireEvent.click(input)+}++const options = () => screen.queryAllByRole('button').map(button => button.textContent || '')++beforeEach(() => {+ vi.resetModules()+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('the @-token at the caret', () => {+ it('opens the popover on a token that begins a word', async () => {+ const { input } = await mount()++ typeInto(input, 'hey @al')++ expect(options().some(label => label.startsWith('@alpha'))).toBe(true)+ })++ it('offers @everyone and @all as the room-wide broadcast quick picks', async () => {+ const { input } = await mount()++ typeInto(input, '@')++ expect(options().some(label => label.startsWith('@everyone'))).toBe(true)+ expect(options().some(label => label.startsWith('@all'))).toBe(true)+ })++ it('narrows to @everyone as the query grows', async () => {+ const { input } = await mount()++ typeInto(input, 'ping @every')++ expect(options().filter(label => label.startsWith('@everyone'))).toHaveLength(1)+ expect(options().some(label => label.startsWith('@alpha'))).toBe(false)+ })++ it('stays closed mid-word, on plain text, and with the caret before the @', async () => {+ const { input } = await mount()++ typeInto(input, 'email me a@b')++ expect(options()).toHaveLength(0)++ typeInto(input, 'plain text')++ expect(options()).toHaveLength(0)++ typeInto(input, 'hey @al', 3)++ expect(options()).toHaveLength(0)+ })+})++describe('insertion', () => {+ it('writes exactly "@handle " — the shape parseGroupChatMentions resolves', async () => {+ const { input, onChange } = await mount()++ typeInto(input, 'hey @al')+ const option = screen.getAllByRole('button').find(button => button.textContent?.startsWith('@alpha'))+ fireEvent.mouseDown(option!)++ expect(onChange).toHaveBeenLastCalledWith('hey @alpha ')+ })++ it('preventDefaults the mousedown so the input keeps focus', async () => {+ const { input } = await mount()++ typeInto(input, 'hey @al')+ const option = screen.getAllByRole('button').find(button => button.textContent?.startsWith('@alpha'))++ // fireEvent returns false when a handler called preventDefault.+ expect(fireEvent.mouseDown(option!)).toBe(false)+ })++ it('replaces the whole token, not just the typed suffix', async () => {+ const { input, onChange } = await mount()++ typeInto(input, '@bui and then some', 4)+ const option = screen.getAllByRole('button').find(button => button.textContent?.startsWith('@builder'))+ fireEvent.mouseDown(option!)++ expect(onChange).toHaveBeenLastCalledWith('@builder and then some')+ })++ it('lists every seated member under a bare @, keyed by handle', async () => {+ const { input } = await mount()++ typeInto(input, '@')++ // Handles only — a profile name that never resolved would surface as+ // "@undefined" and route to nobody.+ expect(options().some(label => label.startsWith('@alpha'))).toBe(true)+ expect(options().some(label => label.startsWith('@builder'))).toBe(true)+ expect(options().some(label => label.startsWith('@undefined'))).toBe(false)+ })+})++// #89884: the composer used to be a single-line Input whose form submitted on+// every Enter, so multi-line room prompts were impossible.+describe('keyboard (#89884)', () => {+ it('submits on Enter and leaves Shift+Enter to the textarea', async () => {+ const { input, onSubmitDraft } = await mount('a room prompt')++ fireEvent.keyDown(input, { key: 'Enter' })++ expect(onSubmitDraft).toHaveBeenCalledTimes(1)++ fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })++ expect(onSubmitDraft).toHaveBeenCalledTimes(1)+ })++ it('inserts the highlighted mention on Enter while the popover is open', async () => {+ const { input, onChange, onSubmitDraft } = await mount()++ typeInto(input, 'hey @alp')+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(onChange).toHaveBeenLastCalledWith('hey @alpha ')+ expect(onSubmitDraft).not.toHaveBeenCalled()+ })++ // #93528: Enter here confirms composed Chinese/Japanese/Korean text. It must+ // neither insert a mention nor submit the draft. isComposing covers Chromium;+ // keyCode 229 covers macOS Chinese IMEs that fire Enter after compositionend+ // with isComposing already false.+ it('swallows IME composition Enters (#93528)', async () => {+ const { input, onSubmitDraft } = await mount('中文')++ fireEvent.keyDown(input, { isComposing: true, key: 'Enter' })+ fireEvent.keyDown(input, { key: 'Enter', keyCode: 229 })++ expect(onSubmitDraft).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.test.ts b/apps/desktop/src/plugins/hermes-bots/group-chat-view.test.tsnew file mode 100644index 00000000000..4c07972f242--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.test.ts@@ -0,0 +1,291 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as data from './data'+import type * as groupChat from './group-chat'+import type * as groupChatView from './group-chat-view'+import type * as groupMembership from './group-membership'+import type * as groupPanes from './group-panes'+import { createGroupGateway, drain, runTimersInline, scriptedStorage } from './group-test-utils'+import type { ScriptedGateway } from './group-test-utils'+import type { GroupChat, RosterRow } from './types'++// The room surface's two lifecycle mutations — opening a room into the MAIN+// window, and disbanding one — plus the ordering rules that keep the in-pane+// fallback from painting a duplicate beside the main tab.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')++ return pluginSdkMock(host)+})++interface Room {+ chat: typeof groupChat+ data: typeof data+ gateway: ScriptedGateway+ membership: typeof groupMembership+ panes: typeof groupPanes+ view: typeof groupChatView+}++async function loadRoom(): Promise<Room> {+ vi.resetModules()+ const gateway = createGroupGateway()++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [chat, data, membership, panes, view, shared] = await Promise.all([+ import('./group-chat'),+ import('./data'),+ import('./group-membership'),+ import('./group-panes'),+ import('./group-chat-view'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { chat, data, gateway, membership, panes, view }+}++const durable = (room: Room) => (room.gateway.storage.get('group-chats') || {}) as Record<string, GroupChat>++beforeEach(() => {+ runTimersInline()+})++describe('opening a room', () => {+ it('follows the main-window tab open and close', async () => {+ const room = await loadRoom()+ let onClose: () => void = () => undefined++ host.openWorkspace = (_id: string, options: { onClose: () => void }) => {+ onClose = options.onClose++ return () => onClose()+ }++ room.view.openGroupChat('Core')++ expect(room.chat.$groupChatWorkspace.get()).toBe('Core')+ // #89788: the main tab owns the room, so the pane keeps its roster.+ expect(room.panes.shouldRenderGroupChatInPane('Core')).toBe(false)++ onClose()++ expect(room.chat.$groupChatWorkspace.get()).toBeNull()+ expect(room.panes.shouldRenderGroupChatInPane('Core')).toBe(true)+ })++ it('keeps the in-pane fallback on older hosts and when the door throws', async () => {+ const older = await loadRoom()++ older.view.openGroupChat('Core')++ expect(older.chat.$groupChatWorkspace.get()).toBe('Core')+ expect(older.panes.shouldRenderGroupChatInPane('Core')).toBe(true)++ const failed = await loadRoom()++ host.openWorkspace = () => {+ throw new Error('workspace unavailable')+ }++ failed.view.openGroupChat('Ops')++ expect(failed.chat.$groupChatWorkspace.get()).toBe('Ops')+ expect(failed.panes.shouldRenderGroupChatInPane('Ops')).toBe(true)+ })++ it('records main-tab ownership before the selection atom paints (#89788 follow-up)', async () => {+ const room = await loadRoom()+ // Simulate a BotsPane render racing the open: sample the gate at the+ // moment the selection atom flips. If the tab were recorded after the atom+ // set, this probe would observe selected-but-unowned and the in-pane+ // duplicate would paint beside the main tab.+ let gateAtSelection: boolean | null = null++ const unsubscribe = room.chat.$groupChatWorkspace.listen(value => {+ if (value === 'Core' && gateAtSelection === null) {+ gateAtSelection = room.panes.shouldRenderGroupChatInPane('Core')+ }+ })++ host.openWorkspace = () => () => undefined++ room.view.openGroupChat('Core')+ unsubscribe()++ expect(gateAtSelection).toBe(false)+ })++ it('does not let an older group closing clear the newer selection', async () => {+ const room = await loadRoom()+ host.openWorkspace = () => () => undefined++ room.view.openGroupChat('Core')+ room.view.openGroupChat('Ops')+ room.panes.closeGroupChatMainTab('Core')++ expect(room.chat.$groupChatWorkspace.get()).toBe('Ops')+ })+})++describe('disband', () => {+ it('removes only this membership, room log, workspace and needs-you state', async () => {+ const room = await loadRoom()+ room.chat.$groupChats.set({+ Gone: { log: [{ at: 2, from: { kind: 'user', name: 'You' }, id: 'g1', text: 'hello goners' }], watermarks: {} },+ Keep: {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'k1', text: 'hello keepers' }],+ members: [{ connectionId: 'remote-1', name: 'remote', remoteSource: true, sourceScoped: true }],+ watermarks: {}+ }+ } as unknown as Record<string, GroupChat>)+ room.data.$botMeta.set({+ builder: { group: 'Gone', groups: ['Gone', 'Keep'] },+ research: { group: 'Keep', groups: ['Keep'] }+ })+ room.chat.$groupChatWorkspace.set('Gone')+ room.chat.$groupNeedsYou.set({ Gone: true, Keep: true })++ await room.view.disbandGroupChat('Gone', [{ name: 'builder' }])++ // Room state: gone from the atom (no running drive, so no tombstone).+ expect(room.chat.$groupChats.get().Gone).toBeUndefined()+ expect(room.chat.$groupChats.get().Keep).toBeTruthy()+ // The open room view closed; needs-you cleared for the disbanded room only.+ expect(room.chat.$groupChatWorkspace.get()).toBeNull()+ expect(room.chat.$groupNeedsYou.get().Gone).toBeUndefined()+ expect(room.chat.$groupNeedsYou.get().Keep).toBe(true)+ // Disband removes only this membership; other groups survive.+ expect(room.data.$botMeta.get().builder.groups).toEqual(['Keep'])+ expect(room.data.$botMeta.get().builder.group).toBe('Keep')+ expect(room.data.$botMeta.get().research.groups).toEqual(['Keep'])+ expect('Gone' in durable(room)).toBe(false)+ expect(durable(room).Keep.members).toHaveLength(1)+ expect(durable(room).Keep.members?.[0].connectionId).toBe('remote-1')+ })++ it('cannot leave a metadata-only group row behind when the rendered roster is empty', async () => {+ const room = await loadRoom()+ room.data.$botMeta.set({ builder: { group: 'Remote', groups: ['Remote'] } })+ room.chat.$groupChats.set({+ Remote: { log: [], members: [], running: false, sessions: {}, watermarks: {} }+ } as unknown as Record<string, GroupChat>)++ await room.view.disbandGroupChat('Remote', [])++ expect(room.chat.$groupChats.get().Remote).toBeUndefined()+ expect(room.data.$botMeta.get().builder.groups).toEqual([])+ expect(room.data.$botMeta.get().builder.group).toBeNull()+ // Stale bot metadata cannot reconstruct a deleted zero-member row.+ expect(room.membership.groupChatNames(room.data.$botMeta.get(), room.chat.$groupChats.get())).toEqual([])+ })++ it('recovers the exact source-qualified metadata owner from an empty roster', async () => {+ const room = await loadRoom()++ const remote: RosterRow = {+ connectionId: 'remote-1',+ connectionKind: 'remote',+ name: 'builder',+ remoteSource: true,+ route: { connectionId: 'remote-1', mode: 'remote', profile: 'builder', targetProfile: 'builder' },+ sourceScoped: true+ }++ room.data.$lastRoster.set([remote])+ room.data.$botMeta.set({+ builder: { group: 'Keep', groups: ['Keep'] },+ 'remote-1::builder': { group: 'Remote', groups: ['Remote'] }+ })+ room.chat.$groupChats.set({+ Remote: { log: [], members: [], running: false, sessions: {}, watermarks: {} }+ } as unknown as Record<string, GroupChat>)++ await room.view.disbandGroupChat('Remote', [])++ expect(room.data.$botMeta.get()['remote-1::builder'].groups).toEqual([])+ expect(room.data.$botMeta.get()['remote-1::builder'].group).toBeNull()+ // Same-named local metadata is untouched.+ expect(room.data.$botMeta.get().builder.groups).toEqual(['Keep'])+ expect(room.data.$botMeta.get().builder.group).toBe('Keep')+ })++ it('skips source-qualified remote members instead of mutating same-named local metadata', async () => {+ const room = await loadRoom()+ room.data.$botMeta.set({ builder: { group: 'Keep', groups: ['Keep'] } })++ await room.view.disbandGroupChat('Remote', [+ { connectionId: 'remote-1', name: 'builder', remoteSource: true, sourceScoped: true }+ ])++ expect(room.data.$botMeta.get().builder.groups).toEqual(['Keep'])+ expect(room.data.$botMeta.get().builder.group).toBe('Keep')+ expect(room.data.$botMeta.get()['[object Object]']).toBeUndefined()+ })++ it('leaves an epoch-bumped empty tombstone while a drive is mid-turn', async () => {+ const room = await loadRoom()+ room.chat.$groupChats.set({+ Live: {+ epoch: 3,+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'l1', text: 'kick off' }],+ running: true,+ watermarks: {}+ }+ } as unknown as Record<string, GroupChat>)++ await room.view.disbandGroupChat('Live', [{ name: 'research' }])++ const tomb = room.chat.$groupChats.get().Live++ expect(tomb).toBeTruthy()+ expect(tomb.log).toHaveLength(0)+ expect(tomb.running).toBe(false)+ // Epoch bumped so the loop bails at its member boundary; flagged so+ // persistence and name-dedup skip it.+ expect(tomb.epoch).toBe(4)+ expect(tomb.tombstone).toBe(true)+ expect('Live' in durable(room)).toBe(false)++ // Regression (#90028 live E2E): updateGroupChat persists the WHOLE atom+ // map — an unrelated room write while the tombstone lingers must not+ // smuggle it into durable storage, and the disbanded name must be+ // immediately reusable (uniqueGroupChatName would suffix it otherwise).+ room.chat.updateGroupChat('Other', current => {+ current.log.push({ at: Date.now(), from: { kind: 'user', name: 'You' }, id: 'o1', text: 'x', thread: 't' })++ return current+ })++ expect('Other' in durable(room)).toBe(true)+ expect('Live' in durable(room)).toBe(false)+ expect(room.chat.uniqueGroupChatName('Live', new Set(room.membership.liveGroupChatNames()))).toBe('Live')+ })++ it('drops the disbanded room from the gateway mirror', async () => {+ const room = await loadRoom()+ room.chat.$groupChats.set({+ Gone: { log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'g1', text: 'bye' }], watermarks: {} }+ } as unknown as Record<string, GroupChat>)++ await room.view.disbandGroupChat('Gone', [])+ await drain(() => room.gateway.rpcFor('profiles.configure').length < 1, 50)++ const configure = room.gateway.rpcFor('profiles.configure').at(-1)++ const envelope = (configure?.params.ui_meta as Record<string, { deleted?: Record<string, number> }>)[+ 'hermes-bots-groups'+ ]++ expect(envelope.deleted?.['name:Gone']).toBeGreaterThan(0)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat.test.ts b/apps/desktop/src/plugins/hermes-bots/group-chat.test.tsnew file mode 100644index 00000000000..e3e6efc2b6a--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-chat.test.ts@@ -0,0 +1,947 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as groupChat from './group-chat'+import type * as groupRounds from './group-rounds'+import { createGroupGateway, deferTimers, drain, runTimersInline, scriptedStorage } from './group-test-utils'+import type { GatewayOptions, ScriptedGateway } from './group-test-utils'+import type { GroupChat, GroupMessage } from './types'++// The room store: the atom every group surface reads, the durable projection+// written to plugin storage, and the bounded mirror published to the gateway's+// profile ui_meta so mobile sees the same rooms. Identity is the load-bearing+// part — a room is a roomId, not a display name, and every merge has to agree+// about that across devices that were offline for different windows.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')++ return pluginSdkMock(host)+})++interface Room {+ chat: typeof groupChat+ gateway: ScriptedGateway+ rounds: typeof groupRounds+}++/** The sync envelope, borrowed from the merge entry point — the interface+ * itself is private to group-chat.ts. */+type SyncSnapshot = Parameters<typeof groupChat.mergeGroupChatSyncSnapshots>[0]++async function loadRoom(options: GatewayOptions = {}): Promise<Room> {+ vi.resetModules()+ const gateway = createGroupGateway(options)++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [chat, rounds, shared] = await Promise.all([+ import('./group-chat'),+ import('./group-rounds'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { chat, gateway, rounds }+}++const durable = (room: Room) => (room.gateway.storage.get('group-chats') || {}) as Record<string, GroupChat>++/** The last mirror the sync worker published to the default profile. */+function published(room: Room) {+ const configure = room.gateway.rpcFor('profiles.configure').at(-1)++ return (configure?.params.ui_meta as Record<string, Record<string, unknown>>)?.['hermes-bots-groups']+}++beforeEach(() => {+ runTimersInline()+})++describe('log window', () => {+ it('trimming keeps watermarks consistent with the trimmed array', async () => {+ const { chat } = await loadRoom()++ const log = Array.from({ length: 200 }, (_, i) => ({+ at: i,+ from: { kind: 'user', name: 'You' },+ text: `m${i}`+ })) as GroupMessage[]++ const trimmed = chat.trimGroupChatLog(log, { builder: 10, research: 150 }, 96)++ expect(trimmed.log).toHaveLength(96)+ expect(trimmed.watermarks.research).toBe(150 - 104)+ expect(trimmed.watermarks.builder).toBe(0)+ })+})++describe('room naming', () => {+ it('same-name dedup reserves suffix length at the 64-char cap', async () => {+ const { chat } = await loadRoom()++ expect(chat.uniqueGroupChatName('Team', new Set(['Other']))).toBe('Team')++ // Slicing the joined string would chop the " 2"/" 3" suffix off a+ // max-length base and collide with the original forever.+ const base = 'x'.repeat(64)+ const next = chat.uniqueGroupChatName(base, new Set([base, `${base.slice(0, 62)} 2`]))++ expect(next).not.toBe(base)+ expect(next).toHaveLength(64)+ expect(next).toBe(`${base.slice(0, 62)} 3`)+ })+})++describe('speaker labels', () => {+ it('the default profile speaks as Hermes in transcripts, not @default', async () => {+ const { rounds } = await loadRoom()++ const line = rounds.formatGroupChatLine(+ { from: { kind: 'member', name: 'default' }, text: 'hello room' } as GroupMessage,+ 'builder'+ )++ expect(line).toBe('Hermes: hello room')++ // Other members keep their profile name; the (you) suffix survives.+ expect(+ rounds.formatGroupChatLine({ from: { kind: 'member', name: 'default' }, text: 'hi' } as GroupMessage, 'default')+ ).toBe('Hermes (you): hi')+ expect(+ rounds.formatGroupChatLine({ from: { kind: 'member', name: 'builder' }, text: 'yo' } as GroupMessage, 'research')+ ).toBe('builder: yo')+ })++ it('honor friendly identity: Bot Mode title, then display_name, never a stale Hermes', async () => {+ const { chat, rounds } = await loadRoom()+ const data = await import('./data')++ // A renamed default (core display_name via `hermes profile rename`) must+ // read as its new name — the community report was "Lucy" still showing+ // "Hermes is thinking…" in group rooms.+ data.$lastRoster.set([{ display_name: 'Lucy', name: 'default' }])++ expect(chat.groupSpeakerLabel('default')).toBe('Lucy')+ expect(+ rounds.formatGroupChatLine({ from: { kind: 'member', name: 'default' }, text: 'hi' } as GroupMessage, 'builder')+ ).toBe('Lucy: hi')++ // A Bot Mode title outranks display_name (same precedence as displayName).+ data.$botMeta.set({ default: { title: 'Moxie' } })++ expect(chat.groupSpeakerLabel('default')).toBe('Moxie')++ // Secondary profiles get their title too — the thinking line names the+ // renamed bot, not the raw profile slug.+ data.$botMeta.set({ research: { title: 'Radar' } })+ data.$lastRoster.set([])++ expect(chat.groupSpeakerLabel('research')).toBe('Radar')++ // Untitled rows keep today's behavior: default → Hermes, others verbatim.+ data.$botMeta.set({})++ expect(chat.groupSpeakerLabel('default')).toBe('Hermes')+ expect(chat.groupSpeakerLabel('builder')).toBe('builder')+ })++ it("never borrow a remote row's display_name for a local speaker", async () => {+ const { chat } = await loadRoom()+ const data = await import('./data')+ // Only a remote/thin row named default exists — its display_name belongs+ // to that connection, not to the active gateway's default.+ data.$lastRoster.set([{ display_name: 'HomelabBot', name: 'default', remoteSource: true }])++ expect(chat.groupSpeakerLabel('default')).toBe('Hermes')+ })+})++// #93127: duplicate room delivery. Two raceable paths existed: a member turn+// mid-flight when the room epoch bumps still committed its reply + watermark+// (the stale loop only noticed supersession at the NEXT member boundary), and+// the stale loop and the fresh loop could both append the same reply.+describe('turn commit gate (#93127)', () => {+ it('discards a superseded turn — the epoch moved on while the turn ran', async () => {+ const { chat } = await loadRoom()++ expect(chat.shouldCommitMemberTurn(3, 4)).toBe(false)+ expect(chat.shouldCommitMemberTurn(3, 7)).toBe(false)+ // Explicit same-thread supersession.+ expect(chat.shouldCommitMemberTurn(3, 4, true)).toBe(false)+ })++ it('commits a current turn — the epoch is unchanged since dispatch', async () => {+ const { chat } = await loadRoom()++ expect(chat.shouldCommitMemberTurn(3, 3)).toBe(true)+ expect(chat.shouldCommitMemberTurn(0, 0)).toBe(true)+ })++ it('does NOT discard finished work on a cross-thread epoch bump', async () => {+ const { chat } = await loadRoom()++ // Epoch moved, but no newer user entry landed in THIS thread: the+ // superseding send lives in another thread whose loop filters this one+ // out — dropping the reply would lose completed work forever.+ expect(chat.shouldCommitMemberTurn(3, 4, false)).toBe(true)+ })+})++describe('duplicate append guard (#93127)', () => {+ const seed = (chat: typeof groupChat, entry: GroupMessage) => {+ chat.$groupChats.set({ Room: { log: [entry], watermarks: {} } })+ }++ const lastEntry = (name: string, text: string, thread = 't1', at = Date.now(), source?: string): GroupMessage =>+ ({+ at,+ from: { kind: 'member', name, ...(source ? { source } : {}) },+ id: 'x',+ text,+ thread+ }) as GroupMessage++ it('drops an adjacent identical member reply', async () => {+ const { chat } = await loadRoom()+ seed(chat, lastEntry('impl', 'Stopped. Standing by.'))++ chat.appendGroupChatEntry('Room', { kind: 'member', name: 'impl' }, 'Stopped. Standing by.', 't1')++ expect(chat.$groupChats.get().Room.log).toHaveLength(1)+ })++ it('keeps identical text from a DIFFERENT member', async () => {+ const { chat } = await loadRoom()+ seed(chat, lastEntry('impl', 'Confirmed.'))++ chat.appendGroupChatEntry('Room', { kind: 'member', name: 'reviewer' }, 'Confirmed.', 't1')++ expect(chat.$groupChats.get().Room.log).toHaveLength(2)+ })++ it('keeps identical text from the same member on another SOURCE', async () => {+ const { chat } = await loadRoom()+ seed(chat, lastEntry('impl', 'Confirmed.', 't1', Date.now(), 'laptop'))++ chat.appendGroupChatEntry('Room', { kind: 'member', name: 'impl' }, 'Confirmed.', 't1')++ expect(chat.$groupChats.get().Room.log).toHaveLength(2)+ })++ it('keeps the same text after an intervening entry — only the LAST entry is checked', async () => {+ const { chat } = await loadRoom()+ seed(chat, lastEntry('reviewer', 'ack'))++ chat.appendGroupChatEntry('Room', { kind: 'member', name: 'impl' }, 'Confirmed.', 't1')++ expect(chat.$groupChats.get().Room.log).toHaveLength(2)+ })++ it('keeps identical text in a DIFFERENT thread', async () => {+ const { chat } = await loadRoom()+ seed(chat, lastEntry('impl', 'Confirmed.', 'thread-a'))++ chat.appendGroupChatEntry('Room', { kind: 'member', name: 'impl' }, 'Confirmed.', 'thread-b')++ expect(chat.$groupChats.get().Room.log).toHaveLength(2)+ })++ it('keeps identical text outside the recency window', async () => {+ const { chat } = await loadRoom()+ seed(chat, lastEntry('impl', 'Done.', 't1', Date.now() - 60 * 60 * 1000))++ chat.appendGroupChatEntry('Room', { kind: 'member', name: 'impl' }, 'Done.', 't1')++ expect(chat.$groupChats.get().Room.log).toHaveLength(2)+ })++ it('never dedupes user entries', async () => {+ const { chat } = await loadRoom()+ seed(chat, { at: Date.now(), from: { kind: 'user', name: 'You' }, id: 'x', text: 'stop', thread: 't1' })++ chat.appendGroupChatEntry('Room', { kind: 'user', name: 'You' }, 'stop', 't1')++ expect(chat.$groupChats.get().Room.log).toHaveLength(2)+ })+})++describe('threads', () => {+ it('hydration assigns legacy thread ids — a lull splits, follow-ups stay together', async () => {+ const { chat } = await loadRoom()+ const minute = 60000+ const user = (text: string, at: number) => ({ at, from: { kind: 'user', name: 'You' }, text }) as GroupMessage++ const member = (name: string, text: string, at: number) =>+ ({ at, from: { kind: 'member', name }, text }) as GroupMessage++ const log = chat.assignLegacyThreads([+ user('task one', 0),+ member('a', 'r1', 1 * minute),+ user('quick follow-up', 3 * minute), // inside the 15-min window: SAME thread+ member('a', 'r2', 4 * minute),+ user('new topic much later', 60 * minute), // after the lull: new thread+ member('a', 'r3', 61 * minute)+ ])++ expect(log[0].thread).toBe(log[2].thread)+ expect(log[2].thread).toBe(log[3].thread)+ expect(log[0].thread).not.toBe(log[4].thread)+ expect(log[4].thread).toBe(log[5].thread)+ })+})++describe('durable projection', () => {+ it('excludes tombstoned rooms', async () => {+ const { chat } = await loadRoom()++ const rooms = chat.durableGroupChatRooms({+ Keep: { log: [{ at: 1, from: { kind: 'user' }, text: 'hi' }], members: [], watermarks: {} },+ Live: { epoch: 4, log: [], running: false, tombstone: true, watermarks: {} }+ } as unknown as Record<string, GroupChat>)++ expect('Live' in rooms).toBe(false)+ expect('Keep' in rooms).toBe(true)+ })++ it('carries roomId — omitting it would drop the durable id on the next cold hydrate', async () => {+ const { chat } = await loadRoom()++ const rooms = chat.durableGroupChatRooms({+ Legacy: { log: [{ at: 1, from: { kind: 'user' }, text: 'hi' }], members: [], watermarks: {} },+ Team: { log: [{ at: 1, from: { kind: 'user' }, text: 'hi' }], members: [], roomId: 'room-abc123', watermarks: {} }+ } as unknown as Record<string, GroupChat>)++ expect(rooms.Team.roomId).toBe('room-abc123')+ // An explicit null, not undefined — the key has to survive JSON.+ expect(rooms.Legacy.roomId).toBeNull()+ })++ it('never persists a tombstone that a remote merge forwarded', async () => {+ const room = await loadRoom()+ // A drive still mid-turn at disband time leaves a live tombstone.+ room.chat.$groupChats.set({+ Live: { epoch: 4, log: [], running: false, tombstone: true, watermarks: {} }+ } as unknown as Record<string, GroupChat>)++ // The remote gateway has NOT yet received the delete (plausible now that+ // sync fans out to every reachable default-profile gateway independently)+ // — its snapshot still carries a live copy under the same display name.+ const merged = room.chat.mergeRemoteGroupChatSnapshotIntoRooms(+ {+ rooms: {+ Live: {+ log: [{ at: 1, from: { kind: 'member', name: 'research' }, text: 'still going' }],+ members: [{ name: 'research' }]+ }+ },+ version: 3+ },+ room.chat.$groupChats.get()+ )++ // The merge spreads `...existing` before its explicit field overrides,+ // none of which touch `tombstone` — so the flag survives into the merged+ // room. Without that reachability step durableGroupChatRooms would never+ // see a tombstoned room from this path at all.+ expect(merged.Live.tombstone).toBe(true)++ await room.chat.persistGroupChatRooms(merged)++ expect('Live' in durable(room)).toBe(false)+ })++ it('stranded markers ride the durable map so late replies survive a reload', async () => {+ const room = await loadRoom()++ room.chat.updateGroupChat('Persist', current => {+ current.stranded = { research: 3 }++ return current+ })++ expect(durable(room).Persist.stranded?.research).toBe(3)+ })+})++describe('gateway mirror', () => {+ it('mirrors room messages and members through bounded profile metadata', async () => {+ const room = await loadRoom()++ room.rounds.sendToGroupChat(+ 'Research',+ [+ { handle: 'research', name: 'research' },+ { handle: 'builder', name: 'builder' }+ ],+ 'What changed?'+ )+ await drain(() => Boolean(room.chat.$groupChats.get().Research?.running))++ const envelope = published(room)+ const rooms = envelope.rooms as Record<string, Record<string, unknown>>+ const key = Object.keys(rooms).find(name => rooms[name].name === 'Research')++ expect(envelope.version).toBe(3)+ expect(key).toBeDefined()+ expect((rooms[key!].log as GroupMessage[])[0].text).toBe('What changed?')+ expect((rooms[key!].members as { name: string }[]).map(member => member.name)).toEqual(['research', 'builder'])+ expect(room.chat.groupChatGatewayJsonSize(envelope)).toBeLessThanOrEqual(48000)+ })++ it('is size bounded and favors recent messages', async () => {+ const { chat } = await loadRoom()+ const long = 'x'.repeat(5000)++ const snapshot = chat.groupChatSyncSnapshot({+ Large: {+ log: Array.from({ length: 100 }, (_, index) => ({+ at: index,+ from: { kind: index % 2 ? 'member' : 'user', name: index % 2 ? 'research' : 'You' },+ text: `${index}:${long}`+ }))+ }+ } as unknown as Record<string, GroupChat>)++ const log = snapshot.rooms['name:Large'].log++ expect(chat.groupChatGatewayJsonSize(snapshot)).toBeLessThanOrEqual(48000)+ expect(log.length).toBeLessThanOrEqual(16)+ expect(log.at(-1)?.text).toMatch(/^99:/)+ expect(log.at(-1)?.text.length).toBeLessThanOrEqual(1200)+ })++ it('preserves threads and budgets escaped Unicode', async () => {+ const { chat } = await loadRoom()++ const snapshot = chat.groupChatSyncSnapshot({+ Unicode: {+ log: Array.from({ length: 16 }, (_, index) => ({+ at: index,+ from: { kind: 'member', name: 'research' },+ text: `message ${index} ${'🧠'.repeat(1200)}`,+ thread: `thread-${index}`+ }))+ }+ } as unknown as Record<string, GroupChat>)++ expect(chat.groupChatGatewayJsonSize(snapshot)).toBeLessThanOrEqual(48000)+ expect(snapshot.rooms['name:Unicode'].log.at(-1)?.thread).toBe('thread-15')+ })++ it('omits empty runtime rooms', async () => {+ const { chat } = await loadRoom()++ const snapshot = chat.groupChatSyncSnapshot({+ Disbanded: { log: [], members: [{ name: 'research' }] }+ } as unknown as Record<string, GroupChat>)++ expect(Object.keys(snapshot.rooms)).toEqual([])+ })++ it('an empty hydrate cannot erase a shared room mirror', async () => {+ const room = await loadRoom()+ const before = room.gateway.rpc.length++ room.chat.scheduleGroupChatServerSync({})++ expect(room.gateway.rpc).toHaveLength(before)+ })++ it('an explicit final-room disband may clear the mirror', async () => {+ const room = await loadRoom()++ room.chat.scheduleGroupChatServerSync({}, { allowEmpty: true, deletedRooms: ['Research'] })+ await drain(() => room.gateway.rpcFor('profiles.configure').length < 1, 50)++ const envelope = published(room)++ expect(Object.keys(envelope.rooms as object)).toEqual([])+ expect((envelope.deleted as Record<string, number>)['name:Research']).toBeGreaterThan(0)+ })+})++describe('snapshot merge', () => {+ it('pull-before-push preserves disjoint rooms, messages and members', async () => {+ const { chat } = await loadRoom()++ const merged = chat.mergeGroupChatSyncSnapshots(+ {+ rooms: {+ RemoteOnly: {+ log: [{ at: 2, from: { kind: 'member', name: 'ops' }, text: 'kept' }],+ members: [{ name: 'ops' }]+ },+ Shared: {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, text: 'remote', thread: 'one' }],+ members: [{ handle: 'research', name: 'research' }]+ }+ },+ version: 1+ },+ {+ rooms: {+ Shared: {+ log: [{ at: 3, from: { kind: 'member', name: 'builder' }, text: 'local', thread: 'one' }],+ members: [{ handle: 'builder', name: 'builder' }]+ }+ },+ version: 1+ }+ )++ expect(merged.rooms['name:Shared'].log.map(entry => entry.text)).toEqual(['remote', 'local'])+ expect(merged.rooms['name:Shared'].members?.map(member => member.name)).toEqual(['research', 'builder'])+ expect(merged.rooms['name:RemoteOnly'].log[0].text).toBe('kept')+ })++ it('a deletion tombstone wins over stale history but not a later recreation', async () => {+ const { chat } = await loadRoom()++ const stale = chat.mergeGroupChatSyncSnapshots(+ {+ rooms: {+ Research: { log: [{ at: 10, from: { kind: 'user', name: 'You' }, id: 'old', text: 'old' }], revision: 1 }+ },+ version: 2+ },+ { deleted: { Research: 2 }, rooms: {}, version: 2 }+ )++ expect(stale.rooms['name:Research']).toBeUndefined()+ expect(stale.deleted?.['name:Research']).toBe(2)++ const recreated = chat.mergeGroupChatSyncSnapshots(stale, {+ rooms: {+ Research: { log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'new', text: 'new' }], revision: 3 }+ },+ version: 2+ })++ expect(recreated.rooms['name:Research'].log[0].text).toBe('new')+ expect(recreated.deleted).toBeUndefined()+ })++ it('orders deletion and recreation by gateway revision, not device clocks', async () => {+ const { chat } = await loadRoom()++ const merged = chat.mergeGroupChatSyncSnapshots(+ {+ rooms: {+ ClockSkewed: {+ log: [{ at: 9999999999999, from: { kind: 'user', name: 'You' }, id: 'future-clock', text: 'old' }],+ revision: 8+ }+ },+ version: 2+ },+ { deleted: { ClockSkewed: 9 }, rooms: {}, version: 2 }+ )++ expect(merged.rooms['name:ClockSkewed']).toBeUndefined()+ expect(merged.deleted?.['name:ClockSkewed']).toBe(9)+ })++ it('lets a conflicting writer merge the winner and preserve both stable message ids', async () => {+ const { chat } = await loadRoom()++ const winner: SyncSnapshot = {+ rooms: {+ Shared: {+ log: [{ at: 100, from: { kind: 'user', name: 'You' }, id: 'writer-a:1', text: 'alpha' }],+ members: [{ name: 'alpha' }],+ revision: 1+ }+ },+ version: 2+ }++ const loserRetry = chat.mergeGroupChatSyncSnapshots(+ winner,+ {+ rooms: {+ Shared: {+ log: [{ at: 1, from: { kind: 'member', name: 'beta' }, id: 'writer-b:1', text: 'beta' }],+ members: [{ name: 'beta' }],+ revision: 0+ }+ },+ version: 2+ },+ { changedRooms: ['Shared'], writeRevision: 2 }+ )++ expect(loserRetry.rooms['name:Shared'].log.map(entry => entry.id).sort()).toEqual(['writer-a:1', 'writer-b:1'])+ expect(loserRetry.rooms['name:Shared'].revision).toBe(2)+ })+})++describe('cold hydrate', () => {+ it('projects gateway rooms without dropping local runtime fields', async () => {+ const { chat } = await loadRoom()++ const merged = chat.mergeRemoteGroupChatSnapshotIntoRooms(+ {+ rooms: {+ Shared: {+ log: [+ { at: 10, from: { kind: 'user', name: 'You' }, text: 'remote question', thread: 'thread-1' },+ { at: 20, from: { kind: 'member', name: 'research' }, text: 'remote answer', thread: 'thread-1' }+ ],+ members: [{ connectionId: 'mini', name: 'research', sourceScoped: true }]+ }+ },+ version: 3+ },+ {+ Local: {+ epoch: 7,+ log: [{ at: 5, from: { kind: 'user', name: 'You' }, text: 'local', thread: 'thread-local' }],+ members: [{ name: 'builder' }],+ running: true,+ sessions: { builder: 'session-1' },+ watermarks: { builder: 1 }+ }+ } as unknown as Record<string, GroupChat>+ )++ expect(merged.Shared.log.map(entry => entry.text)).toEqual(['remote question', 'remote answer'])+ expect(merged.Shared.members?.[0].remoteSource).toBe(true)+ expect(merged.Local.sessions?.builder).toBe('session-1')+ expect(merged.Local.epoch).toBe(7)+ expect(merged.Local.running).toBe(true)+ })++ it('read-back does not clobber a newer local edit queued during an in-flight write', async () => {+ const { chat } = await loadRoom()++ const merged = chat.mergeRemoteGroupChatSnapshotIntoRooms(+ {+ rooms: {+ Shared: {+ image: 'data:image/png;base64,old',+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'remote', text: 'remote message' }],+ members: [{ name: 'old-member' }],+ revision: 5+ }+ },+ version: 2+ },+ {+ Shared: {+ image: 'data:image/png;base64,new',+ log: [{ at: 2, from: { kind: 'user', name: 'You' }, id: 'local', text: 'local message' }],+ members: [{ name: 'new-member' }],+ syncRevision: 4+ }+ } as unknown as Record<string, GroupChat>,+ { preserveRooms: ['Shared'] }+ )++ expect(merged.Shared.members?.map(member => member.name)).toEqual(['new-member'])+ expect(merged.Shared.image).toBe('data:image/png;base64,new')+ expect(merged.Shared.syncRevision).toBe(4)+ expect(merged.Shared.log.map(entry => entry.id).sort()).toEqual(['local', 'remote'])+ })+})++// A room's identity is its roomId. Display names are labels: renaming one is a+// field update on the same key, and a name-keyed tombstone must never be able+// to kill an id-keyed room (or vice versa).+describe('room identity', () => {+ it('rename publishes a new room plus an old-name tombstone that cold hydrate cannot resurrect', async () => {+ const { chat } = await loadRoom()++ const before: SyncSnapshot = {+ rooms: {+ Old: {+ image: 'data:image/png;base64,room',+ log: [{ at: 10, from: { kind: 'user', name: 'You' }, id: 'turn-1', text: 'history' }],+ members: [{ name: 'research' }],+ revision: 4+ }+ },+ version: 2+ }++ const after = chat.mergeGroupChatSyncSnapshots(+ before,+ {+ rooms: {+ New: {+ image: before.rooms.Old.image,+ log: before.rooms.Old.log,+ members: before.rooms.Old.members,+ revision: 4+ }+ },+ version: 2+ },+ { changedRooms: ['New'], deletedRooms: ['Old'], writeRevision: 5 }+ )++ const hydrated = chat.mergeRemoteGroupChatSnapshotIntoRooms(after, {})++ expect(after.rooms['name:Old']).toBeUndefined()+ expect(after.deleted?.['name:Old']).toBe(5)+ expect(after.rooms['name:New'].revision).toBe(5)+ expect(after.rooms['name:New'].image).toBe('data:image/png;base64,room')+ expect(hydrated.Old).toBeUndefined()+ expect(hydrated.New.log[0].text).toBe('history')+ expect(hydrated.New.image).toBe('data:image/png;base64,room')+ })++ it('a rename with a roomId is a same-key field update, never delete+create', async () => {+ const { chat } = await loadRoom()++ const before: SyncSnapshot = {+ rooms: {+ 'id:room-42': {+ log: [{ at: 10, from: { kind: 'user', name: 'You' }, id: 'turn-1', text: 'history' }],+ members: [{ name: 'research' }],+ name: 'Old',+ revision: 4,+ roomId: 'room-42'+ }+ },+ version: 3+ }++ const after = chat.mergeGroupChatSyncSnapshots(+ before,+ { rooms: { 'id:room-42': { ...before.rooms['id:room-42'], name: 'New' } }, version: 3 },+ { changedRooms: ['id:room-42'], writeRevision: 5 }+ )++ // Same durable key, new display name, no tombstone needed at all.+ expect(Object.keys(after.rooms)).toHaveLength(1)+ expect(after.rooms['id:room-42'].name).toBe('New')+ expect(after.rooms['id:room-42'].revision).toBe(5)+ expect(after.deleted).toBeUndefined()++ // A lagging gateway still holding the OLD name under the same id cannot+ // resurrect it: same key, lower revision, identity follows the winner.+ expect(chat.mergeGroupChatSyncSnapshots(before, after).rooms['id:room-42'].name).toBe('New')+ })++ it('id tombstones are final even against a higher-revision lagging copy', async () => {+ const { chat } = await loadRoom()++ const merged = chat.mergeGroupChatSyncSnapshots(+ {+ // A gateway that was OFFLINE during the disband still carries the room+ // with a high revision from busy pre-disband traffic.+ rooms: {+ 'id:room-9': {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'stale', text: 'stale' }],+ name: 'Zombie',+ revision: 40,+ roomId: 'room-9'+ }+ },+ version: 3+ },+ { deleted: { 'id:room-9': 3 }, rooms: {}, version: 3 }+ )++ expect(merged.rooms['id:room-9']).toBeUndefined()+ expect(merged.deleted?.['id:room-9']).toBe(3)++ // Same-name RECREATION is unaffected: the new room minted a fresh id.+ const recreated = chat.mergeGroupChatSyncSnapshots(merged, {+ rooms: {+ 'id:room-10': {+ log: [{ at: 2, from: { kind: 'user', name: 'You' }, id: 'fresh', text: 'fresh' }],+ name: 'Zombie',+ revision: 1,+ roomId: 'room-10'+ }+ },+ version: 3+ })++ expect(recreated.rooms['id:room-10'].log[0].text).toBe('fresh')+ expect(recreated.rooms['id:room-9']).toBeUndefined()+ })++ it('cold hydrate follows a remote rename via roomId instead of duplicating', async () => {+ const { chat } = await loadRoom()++ const merged = chat.mergeRemoteGroupChatSnapshotIntoRooms(+ {+ rooms: {+ 'id:room-7': {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'm1', text: 'hello' }],+ members: [{ name: 'research' }],+ name: 'Renamed',+ revision: 6,+ roomId: 'room-7'+ }+ },+ version: 3+ },+ {+ // Local copy still under the pre-rename display name, same roomId.+ Original: {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'm1', text: 'hello' }],+ members: [{ name: 'research' }],+ roomId: 'room-7',+ sessions: { research: 'sid-1' },+ syncRevision: 5,+ watermarks: {}+ }+ } as unknown as Record<string, GroupChat>+ )++ expect(merged.Original).toBeUndefined()+ expect(merged.Renamed.roomId).toBe('room-7')+ expect(merged.Renamed.sessions?.research).toBe('sid-1')+ })++ it('renaming an id-keyed room via the rename job shape never tombstones it', async () => {+ const { chat } = await loadRoom()++ const remote: SyncSnapshot = {+ rooms: {+ 'id:room-3': {+ log: [{ at: 5, from: { kind: 'user', name: 'You' }, id: 'h1', text: 'history' }],+ members: [{ name: 'research' }],+ name: 'Old',+ revision: 2,+ roomId: 'room-3'+ }+ },+ version: 3+ }++ // Exactly what renameGroupChat schedules: changed [new], deleted [old].+ const after = chat.mergeGroupChatSyncSnapshots(+ remote,+ { rooms: { 'id:room-3': { ...remote.rooms['id:room-3'], name: 'New' } }, version: 3 },+ { changedRooms: ['New'], deletedRooms: ['Old'], writeRevision: 3 }+ )++ expect(after.rooms['id:room-3']).toBeDefined()+ expect(after.rooms['id:room-3'].name).toBe('New')+ expect(after.deleted?.['id:room-3']).toBeUndefined()+ // A residual name:Old tombstone is correct — it retires stale v2/legacy+ // copies of this room that older clients published under the name key.+ expect(after.deleted?.['name:Old']).toBe(3)++ // Hydrate path: the pull that races the rename write must not delete the+ // locally re-keyed record just because the remote copy still says Old.+ const merged = chat.mergeRemoteGroupChatSnapshotIntoRooms(+ remote,+ {+ New: {+ log: remote.rooms['id:room-3'].log,+ members: [{ name: 'research' }],+ roomId: 'room-3',+ sessions: { research: 'sid-9' },+ syncRevision: 2,+ watermarks: {}+ }+ } as unknown as Record<string, GroupChat>,+ { deletedRooms: ['Old'], preserveRooms: ['New'] }+ )++ expect(merged.New).toBeDefined()+ expect(merged.New.sessions?.research).toBe('sid-9')+ expect(merged.Old).toBeUndefined()+ })+})++describe('sync worker', () => {+ it('retries a gateway CAS conflict and publishes the merged room', async () => {+ deferTimers()++ // A concurrent writer lands between our read and our write: the gateway+ // rejects the CAS, and the retry has to merge rather than overwrite.+ const room = await loadRoom({+ conflictOnce: {+ key: 'hermes-bots-groups',+ value: {+ rooms: {+ 'name:Shared': {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'writer-a:1', text: 'alpha' }],+ members: [{ name: 'alpha' }],+ revision: 1+ }+ },+ version: 3+ }+ }+ })++ room.chat.$groupChats.set({+ Shared: {+ log: [{ at: 2, from: { kind: 'member', name: 'beta' }, id: 'writer-b:1', text: 'beta' }],+ members: [{ name: 'beta' }],+ sessions: {},+ syncRevision: 0,+ watermarks: {}+ }+ } as unknown as Record<string, GroupChat>)++ room.chat.scheduleGroupChatServerSync(room.chat.$groupChats.get(), { changedRooms: ['Shared'] })+ await drain(() => (room.gateway.uiMetaRevisions['hermes-bots-groups'] || 0) < 2, 60)++ const stored = room.gateway.uiMeta['hermes-bots-groups'] as {+ rooms: Record<string, { log: GroupMessage[] }>+ }++ expect(room.gateway.uiMetaRevisions['hermes-bots-groups']).toBe(2)+ expect(stored.rooms['name:Shared'].log.map(entry => entry.id).sort()).toEqual(['writer-a:1', 'writer-b:1'])+ expect(room.gateway.rpcFor('profiles.configure')).toHaveLength(2)+ })++ it('fans a room write out to every reachable default-profile gateway', async () => {+ const room = await loadRoom()+ const remote: { connectionId: string; method: string }[] = []+ host.profileRoutes = async () => [+ { connectionId: 'gw-a', profile: 'default' },+ { connectionId: 'gw-b', profile: 'default' },+ { connectionId: 'gw-b', profile: 'other' }+ ]++ host.requestProfile = async (route: { connectionId: string }, method: string) => {+ remote.push({ connectionId: route.connectionId, method })++ if (method === 'profiles.list') {+ return { profiles: [{ name: 'default', ui_meta: {}, ui_meta_revisions: {} }] }+ }++ if (method === 'profiles.configure') {+ return { applied: { ui_meta: true, ui_meta_revisions: { 'hermes-bots-groups': 1 } } }+ }++ return {}+ }++ room.chat.$groupChats.set({+ Shared: {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'w1', text: 'hi' }],+ members: [{ name: 'research' }],+ sessions: {},+ syncRevision: 0,+ watermarks: {}+ }+ } as unknown as Record<string, GroupChat>)++ room.chat.scheduleGroupChatServerSync(room.chat.$groupChats.get(), { changedRooms: ['Shared'] })+ await drain(() => remote.filter(entry => entry.method === 'profiles.configure').length < 2, 80)++ const configured = new Set(+ remote.filter(entry => entry.method === 'profiles.configure').map(entry => entry.connectionId)+ )++ expect(configured.has('gw-a')).toBe(true)+ expect(configured.has('gw-b')).toBe(true)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts b/apps/desktop/src/plugins/hermes-bots/group-membership.test.tsnew file mode 100644index 00000000000..8c3476e551c--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts@@ -0,0 +1,372 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as data from './data'+import type * as groupChat from './group-chat'+import type * as groupMembership from './group-membership'+import { createGroupGateway, scriptedStorage } from './group-test-utils'+import type * as labels from './labels'+import type { BotMeta, GroupChat, GroupMember, RosterRow } from './types'++// Who is seated in a room, and how a room's membership is written down.+// Membership lives in two places on purpose: local bots carry it in bot-meta+// (`groups`, syncable via ui_meta), while remote members can only be described+// by the room record itself — so seating is a union, and the two halves have+// to agree about identity.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')++ return pluginSdkMock(host)+})++interface Modules {+ chat: typeof groupChat+ data: typeof data+ labels: typeof labels+ membership: typeof groupMembership+}++async function load(): Promise<Modules> {+ vi.resetModules()+ const gateway = createGroupGateway()++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [chat, data, labels, membership, shared] = await Promise.all([+ import('./group-chat'),+ import('./data'),+ import('./labels'),+ import('./group-membership'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { chat, data, labels, membership }+}++let modules: Modules++/** Room records as the store holds them, built from the handful of fields a+ * case actually cares about. */+function rooms(map: Record<string, Partial<GroupChat>>): Record<string, GroupChat> {+ return Object.fromEntries(Object.entries(map).map(([name, room]) => [name, { log: [], watermarks: {}, ...room }]))+}++beforeEach(async () => {+ modules = await load()+})++describe('membership metadata', () => {+ it('botGroups normalizes canonical and legacy membership without duplicates', () => {+ const { botGroups } = modules.membership++ expect(+ botGroups({+ group: 'Operations',+ groups: [' Engineering ', '', 'Research', 'Engineering', null, 7, { name: 'Nope' }]+ } as BotMeta)+ ).toEqual(['Engineering', 'Research'])+ expect(botGroups({ group: 'Legacy' })).toEqual(['Legacy'])+ expect(botGroups({ groups: [] })).toEqual([])+ })++ it('groupMembershipPatch toggles one membership and keeps the legacy projection compatible', () => {+ const { groupMembershipPatch } = modules.membership+ const meta: BotMeta = { group: 'Engineering', groups: ['Engineering', 'Research'] }++ expect(groupMembershipPatch(meta, 'Engineering', true)).toEqual({+ group: 'Engineering',+ groups: ['Engineering', 'Research']+ })+ expect(groupMembershipPatch(meta, 'Operations', true)).toEqual({+ group: 'Engineering',+ groups: ['Engineering', 'Research', 'Operations']+ })+ expect(groupMembershipPatch(meta, 'Engineering', false)).toEqual({ group: 'Research', groups: ['Research'] })+ expect(groupMembershipPatch({ group: 'Legacy' }, 'Legacy', false)).toEqual({ group: null, groups: [] })+ })++ it('knownGroups is unique, trimmed and alphabetical', () => {+ expect(+ modules.membership.knownGroups({+ a: { group: 'research' },+ b: { group: 'Ops', groups: ['Ops', 'research'] },+ c: { groups: ['Design'] },+ d: { group: '' },+ e: {}+ })+ ).toEqual(['Design', 'Ops', 'research'])+ })+})++describe('room listing', () => {+ it('groupChatNames unions bot-meta groups with room records that carry members or a log', () => {+ const meta: Record<string, BotMeta> = {+ pm: { group: 'Ops', groups: ['Ops', 'Research'] },+ researcher: { group: 'Research' },+ scout: { group: 'Stale', groups: ['External'] }+ }++ const known = rooms({+ Chatty: { log: [{ at: 5, from: { kind: 'user', name: 'You' }, id: '1', text: 'hi' }] },+ Empty: { members: [] }, // nothing behind it — no row+ Remote: { members: [{ name: 'spark', remoteSource: true }] },+ Research: { members: [] } // already known via meta+ })++ expect([...modules.membership.groupChatNames(meta, known)].sort()).toEqual([+ 'Chatty',+ 'External',+ 'Ops',+ 'Remote',+ 'Research'+ ])+ })++ it('groupLastActivity is the newest room-log timestamp, 0 for silence', () => {+ const { groupLastActivity } = modules.membership++ expect(groupLastActivity({ log: [{ at: 3 }, { at: 9 }] } as GroupChat)).toBe(9)+ expect(groupLastActivity({ log: [], watermarks: {} })).toBe(0)+ expect(groupLastActivity(undefined)).toBe(0)+ })++ it('stripPreviewMarkdown flattens bold, quotes, code and links out of row previews', () => {+ const { stripPreviewMarkdown } = modules.labels++ expect(stripPreviewMarkdown('**Plan**: ship the `thing`')).toBe('Plan: ship the thing')+ expect(stripPreviewMarkdown('> quoted wisdom')).toBe('quoted wisdom')+ expect(stripPreviewMarkdown('see [the doc](https://x.y/z) now')).toBe('see the doc now')+ expect(stripPreviewMarkdown('## Heading\nbody')).toBe('Heading body')+ expect(stripPreviewMarkdown('')).toBe('')+ })+})++describe('seating a room', () => {+ it('seats local meta members plus stored remote descriptors, preferring live rows', () => {+ const roster: RosterRow[] = [+ { name: 'researcher' },+ { name: 'builder' },+ { connectionId: 'c1', name: 'spark', remoteSource: true, sourceScoped: true }+ ]++ modules.chat.$groupChats.set(+ rooms({+ Research: {+ log: [],+ members: [{ connectionId: 'c1', name: 'spark', remoteSource: true, sourceScoped: true }]+ }+ })+ )++ const members = modules.membership.groupChatMemberBots('Research', roster, {+ builder: { group: 'Ops', groups: ['Ops', 'Research'] },+ researcher: { group: 'Research' }+ })++ expect(members.map(row => row.name)).toEqual(['researcher', 'builder', 'spark'])+ // The LIVE roster row was preferred over the stored descriptor.+ expect(members[2]).toBe(roster[2])+ })++ it('keeps a persisted unreachable source member seated next to a live same-name twin', () => {+ const live: RosterRow = {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'profile-a-this-device',+ name: 'profile-a',+ sourceReachable: true+ }++ const stored: RosterRow = {+ connectionId: 'loopback-19119',+ connectionKind: 'remote',+ connectionLabel: '127.0.0.1:19119',+ handle: 'profile-a-127-0-0-1-19119',+ name: 'profile-a',+ remoteSource: true,+ sourceReachable: false,+ sourceScoped: true+ }++ modules.chat.$groupChats.set(rooms({ Research: { log: [], members: [stored] } }))++ const members = modules.membership.groupChatMemberBots('Research', [live, stored], {+ 'profile-a': { group: 'Research' }+ })++ expect(members).toHaveLength(2)+ expect(members[0]).toBe(live)+ expect(members[1]).toBe(stored)+ expect(members[1].handle).toBe('profile-a-127-0-0-1-19119')+ })++ it('lets a stored descriptor beat a presentation-only ghost', () => {+ // A selected-but-offline ghost carries only enough identity to paint the+ // roster; the durable descriptor owns the handle mentions resolve against.+ const ghost: RosterRow = {+ connectionId: 'c1',+ connectionLabel: 'Workshop',+ ghost: true,+ name: 'spark',+ remoteSource: true,+ sourceScoped: true+ }++ const stored: RosterRow = {+ connectionId: 'c1',+ connectionLabel: 'Workshop',+ handle: 'spark-work',+ name: 'spark',+ remoteSource: true,+ sourceScoped: true,+ title: 'Spark'+ }++ modules.chat.$groupChats.set(rooms({ Research: { log: [], members: [stored] } }))++ const members = modules.membership.groupChatMemberBots('Research', [ghost], {})++ expect(members).toHaveLength(1)+ expect(members[0]).toBe(stored)+ expect(members[0].handle).toBe('spark-work')+ })++ it('durableGroupChatMembers retains active and remote source identities', () => {+ const members = modules.membership.durableGroupChatMembers([+ {+ connectionId: 'noah',+ connectionKind: 'remote',+ connectionLabel: 'Noah',+ handle: 'noah',+ name: 'default',+ sourceScoped: true+ },+ {+ connectionId: 'maya',+ connectionKind: 'remote',+ connectionLabel: 'Maya',+ handle: 'maya',+ name: 'default',+ remoteSource: true,+ sourceScoped: true+ }+ ])++ expect(members).toEqual([+ {+ connectionId: 'noah',+ connectionKind: 'remote',+ connectionLabel: 'Noah',+ handle: 'noah',+ name: 'default',+ remoteSource: true,+ route: { connectionId: 'noah', mode: 'remote', profile: 'default', targetProfile: 'default' },+ sourceScoped: true,+ targetProfile: 'default'+ },+ {+ connectionId: 'maya',+ connectionKind: 'remote',+ connectionLabel: 'Maya',+ handle: 'maya',+ name: 'default',+ remoteSource: true,+ route: { connectionId: 'maya', mode: 'remote', profile: 'default', targetProfile: 'default' },+ sourceScoped: true,+ targetProfile: 'default'+ }+ ])+ })+})++// #92794: older builds persisted group members with a FRIENDLY name as `name`+// (e.g. `name: '大司命'` for the profile slug `taiyi`). Key matching alone+// seats such a descriptor as a ghost NEXT TO its own live roster row ("4 bots"+// in a 2-bot room — reproduced live), and any path that passes the ghost's+// identity onward targets a profile that does not exist on disk. Seating+// re-tries an unmatched descriptor by friendly name against same-connection+// roster rows first.+describe('legacy display-name descriptors', () => {+ const TAIYI: RosterRow = { connectionId: 'local', display_name: '大司命', name: 'taiyi', remoteSource: false }+ const TESTBOT: RosterRow = { connectionId: 'local', display_name: '', name: 'testbot', remoteSource: false }++ it('seat their live row once, not as extra ghosts', () => {+ modules.chat.$groupChats.set(+ rooms({+ room: {+ log: [],+ // The legacy shape: friendly names persisted as `name`.+ members: [+ { connectionId: 'local', handle: '大司命', name: '大司命' },+ { connectionId: 'local', handle: 'Testbot', name: 'Testbot' }+ ]+ }+ })+ )+ modules.data.$botMeta.set({ taiyi: { groups: ['room'] }, testbot: { groups: ['room'], title: 'Testbot' } })++ const seated = modules.membership.groupChatMemberBots('room', [TAIYI, TESTBOT], {+ taiyi: { groups: ['room'] },+ testbot: { groups: ['room'], title: 'Testbot' }+ })++ // Two members, not four: each legacy descriptor resolved to its live row.+ expect(seated.map(row => row.name).sort()).toEqual(['taiyi', 'testbot'])+ })++ it('still seat a genuinely unknown descriptor as a degraded ghost', () => {+ modules.chat.$groupChats.set(rooms({ room: { log: [], members: [{ connectionId: 'gone', name: 'vanished' }] } }))++ const seated = modules.membership.groupChatMemberBots('room', [TAIYI], { taiyi: { groups: ['room'] } })++ expect(seated).toHaveLength(2)+ expect(seated.some(row => row.name === 'vanished')).toBe(true)+ })++ it('resolve a connectionless pre-scoping descriptor against local rows', () => {+ // The oldest legacy shape: no connectionId at all (pre-connection-scoping+ // rooms only ever held this machine's bots). Reproduced live: such ghosts+ // keyed as legacy::<display-name> and doubled the seated roster.+ modules.chat.$groupChats.set(rooms({ room: { log: [], members: [{ name: '大司命' }] } }))++ expect(modules.membership.groupChatMemberBots('room', [TAIYI], {}).map(row => row.name)).toEqual(['taiyi'])+ })++ it('never match a friendly name across connections', () => {+ const remoteTwin: RosterRow = {+ connectionId: 'other-box',+ display_name: '大司命',+ name: 'shadow',+ remoteSource: true+ }++ modules.chat.$groupChats.set(rooms({ room: { log: [], members: [{ connectionId: 'local', name: '大司命' }] } }))++ const seated = modules.membership.groupChatMemberBots('room', [remoteTwin], {})++ // Same friendly name on ANOTHER connection must not capture the member.+ expect(seated.map(row => row.name)).toEqual(['大司命'])+ expect(seated[0].connectionId).toBe('local')+ })++ it('pass an exact slug descriptor through untouched', () => {+ const descriptor = {+ connectionId: 'local',+ name: 'taiyi',+ route: { connectionId: 'local', mode: 'local', profile: 'taiyi', targetProfile: 'taiyi' }+ } as GroupMember++ modules.chat.$groupChats.set(rooms({ room: { log: [], members: [descriptor] } }))++ expect(modules.membership.groupChatMemberBots('room', [TAIYI], {})[0]).toBe(TAIYI)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-panes.test.ts b/apps/desktop/src/plugins/hermes-bots/group-panes.test.tsnew file mode 100644index 00000000000..4ad669dfd78--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-panes.test.ts@@ -0,0 +1,140 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { GroupChatRoom } from './group-chat'+import type { Attachment } from './types'++// group-panes is a leaf over the room store, and the room store reaches the+// gateway through `host`. Nothing here talks to a gateway, so the mock only+// has to satisfy the import graph.+const { host } = vi.hoisted(() => ({+ host: {+ request: vi.fn(async () => ({})),+ requestProfile: vi.fn(async () => ({})),+ state: { connectionId: { get: () => 'local', listen: () => () => undefined } }+ }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const nanostores = await import('nanostores')++ return {+ atom: nanostores.atom,+ computed: nanostores.computed,+ host,+ queryClient: { invalidateQueries: vi.fn() },+ useQuery: () => ({ data: [], isLoading: false }),+ useValue: <T>(store: { get: () => T }) => store.get()+ }+})++// The draft map is module-scope, which is the whole point of it (it has to+// outlive a pane), so every test needs a fresh module.+async function loadDrafts() {+ vi.resetModules()++ return import('./group-panes')+}++/** A room record from just the field a draft key is derived from. */+const room = (partial: Partial<GroupChatRoom>): GroupChatRoom => ({ log: [], watermarks: {}, ...partial })++beforeEach(() => {+ vi.clearAllMocks()+})++describe('group composer drafts', () => {+ it('workspace retirement and re-registration restore the exact room draft', async () => {+ const drafts = await loadDrafts()+ const key = drafts.groupComposerDraftKey('Launch room', room({ roomId: 'room-1' }))+ const attachment: Attachment = { data: 'data:image/png;base64,abc', kind: 'image', name: 'plan.png' }++ drafts.updateGroupComposerDraft(key, state => ({+ ...state,+ activeReplyThread: 'thread-1',+ main: 'main draft',+ pendingAttachments: { main: [attachment], 'thread-1': [attachment] },+ replies: { 'thread-1': 'reply draft' }+ }))++ // Dropping the component reference simulates pane retirement. A fresh+ // registration reads the same module-scope, roomId-qualified snapshot.+ const remounted = drafts.groupComposerDraftSnapshot(key)++ expect(remounted.main).toBe('main draft')+ expect(remounted.replies['thread-1']).toBe('reply draft')+ expect(remounted.activeReplyThread).toBe('thread-1')+ expect(remounted.pendingAttachments.main[0].name).toBe('plan.png')+ })++ it('legacy name-keyed drafts migrate when an immutable room id appears', async () => {+ const drafts = await loadDrafts()+ const legacy = drafts.groupComposerDraftKey('Launch room', room({}))+ const current = drafts.groupComposerDraftKey('Renamed room', room({ roomId: 'room-1' }))++ drafts.updateGroupComposerDraft(legacy, state => ({ ...state, main: 'keep me' }))+ drafts.migrateGroupComposerDraft(legacy, current)++ expect(drafts.groupComposerDraftSnapshot(current).main).toBe('keep me')+ expect(drafts.groupComposerDraftSnapshot(legacy).main).toBe('')+ })++ it('a failed send cannot overwrite text entered after the optimistic clear', async () => {+ const drafts = await loadDrafts()+ const key = 'id:room-1'++ drafts.updateGroupComposerDraft(key, state => ({ ...state, main: 'send this' }))+ const before = drafts.groupComposerDraftSnapshot(key)+ const cleared = drafts.updateGroupComposerDraft(key, state => ({ ...state, main: '' }))++ drafts.updateGroupComposerDraft(key, state => ({ ...state, main: 'newer typing' }))++ expect(drafts.restoreGroupComposerDraft(key, cleared.revision, before)).toBeNull()+ expect(drafts.groupComposerDraftSnapshot(key).main).toBe('newer typing')+ })++ it('disband removes only that room draft', async () => {+ const drafts = await loadDrafts()++ drafts.updateGroupComposerDraft('id:a', state => ({ ...state, main: 'a' }))+ drafts.updateGroupComposerDraft('id:b', state => ({ ...state, main: 'b' }))+ drafts.clearGroupComposerDraft('id:a')++ expect(drafts.groupComposerDraftSnapshot('id:a').main).toBe('')+ expect(drafts.groupComposerDraftSnapshot('id:b').main).toBe('b')+ })+})++describe('main-window tab registry', () => {+ // #89788: the in-panel room is a FALLBACK surface. The Map alone can't+ // notify React, so ownership has to move the rev atom too — the first fix+ // read the Map non-reactively and left two live panes driving one engine.+ it('the in-pane room yields to a main tab, and the gate is reactive', async () => {+ const panes = await loadDrafts()++ expect(panes.shouldRenderGroupChatInPane('Launch room')).toBe(true)++ const rev = panes.$groupMainTabsRev.get()+ panes.recordGroupMainTab('Launch room', () => undefined)++ expect(panes.shouldRenderGroupChatInPane('Launch room')).toBe(false)+ expect(panes.$groupMainTabsRev.get()).toBeGreaterThan(rev)++ panes.dropGroupMainTab('Launch room')++ expect(panes.shouldRenderGroupChatInPane('Launch room')).toBe(true)+ })++ it('closing the tab runs its closer and releases the workspace', async () => {+ vi.resetModules()+ const [panes, chat] = await Promise.all([import('./group-panes'), import('./group-chat')])+ const close = vi.fn()++ chat.$groupChatWorkspace.set('Launch room')+ panes.recordGroupMainTab('Launch room', close)+ panes.closeGroupChatMainTab('Launch room')++ expect(close).toHaveBeenCalledOnce()+ expect(chat.$groupChatWorkspace.get()).toBeNull()+ expect(panes.groupChatMainTabs.has('Launch room')).toBe(false)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.test.tsnew file mode 100644index 00000000000..fd9ec778bf9--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts@@ -0,0 +1,857 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as groupActivity from './group-activity'+import type * as groupChat from './group-chat'+import type * as groupRounds from './group-rounds'+import { createGroupGateway, drain, runTimersInline, scriptedStorage } from './group-test-utils'+import type { GatewayOptions, ScriptedGateway } from './group-test-utils'+import type * as groupTurns from './group-turns'+import type { Attachment, GroupChat, GroupMember, GroupMessage } from './types'++// The round engine: who answers a room message, in what order, with what+// delta, and how a round ends. Every contract here is about a SERIAL loop that+// can be superseded mid-flight — a second send, a stop, or a hold all have to+// take effect at a member boundary without losing finished work.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')++ return pluginSdkMock(host)+})++interface Room {+ activity: typeof groupActivity+ chat: typeof groupChat+ gateway: ScriptedGateway+ rounds: typeof groupRounds+ turns: typeof groupTurns+}++async function loadRoom(options: GatewayOptions = {}): Promise<Room> {+ vi.resetModules()+ const gateway = createGroupGateway(options)++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [activity, chat, rounds, turns, shared] = await Promise.all([+ import('./group-activity'),+ import('./group-chat'),+ import('./group-rounds'),+ import('./group-turns'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { activity, chat, gateway, rounds, turns }+}++const MEMBERS: GroupMember[] = [+ { name: 'research', title: '' },+ { name: 'builder', title: '' },+ { name: 'ops', title: 'The Ops' }+]++const IMG: Attachment = { data: 'data:image/png;base64,iVBORw0KGgo=', kind: 'image', name: 'screenshot.png' }++const log = (room: Room, group: string) => room.chat.$groupChats.get()[group]?.log || []++/** Run the room's drive to completion. */+async function settle(room: Room, group: string) {+ await drain(() => Boolean(room.chat.$groupChats.get()[group]?.running))+}++beforeEach(() => {+ runTimersInline()+})++describe('routing', () => {+ it('reads (pass), pass, pass. and empty as silence, but not real text', async () => {+ const { turns } = await loadRoom()++ expect(turns.isGroupPassText('(pass)')).toBe(true)+ expect(turns.isGroupPassText('pass')).toBe(true)+ expect(turns.isGroupPassText('Pass.')).toBe(true)+ expect(turns.isGroupPassText(' ')).toBe(true)+ expect(turns.isGroupPassText('I will pass this to ops')).toBe(false)+ })++ it('answers only @-mentioned members; @everyone or no mention means all', async () => {+ const { rounds } = await loadRoom()++ const user = (text: string): GroupMessage[] =>+ [{ at: 1, from: { kind: 'user', name: 'You' }, text }] as GroupMessage[]++ expect(rounds.resolveGroupResponders(user('@builder take this one'), MEMBERS).map(m => m.name)).toEqual(['builder'])+ expect(rounds.resolveGroupResponders(user('hello team'), MEMBERS)).toHaveLength(3)+ expect(rounds.resolveGroupResponders(user('@everyone standup'), MEMBERS)).toHaveLength(3)+ })++ it('resolves display titles to the member and never matches @user against a bot', async () => {+ const { rounds } = await loadRoom()++ const parsed = rounds.parseGroupChatMentions('@theops please check, then ping @user', MEMBERS)++ expect(parsed.mentioned.has('ops')).toBe(true)+ expect(parsed.mentioned.size).toBe(1)+ })++ it('resolves @hermes to the default member', async () => {+ const { rounds } = await loadRoom()++ const members: GroupMember[] = [+ { name: 'default', title: '' },+ { name: 'builder', title: '' }+ ]++ const parsed = rounds.parseGroupChatMentions('@hermes take a look', members)++ expect(parsed.mentioned.has('default')).toBe(true)+ expect(parsed.mentioned.size).toBe(1)+ })++ it('rotates the lead speaker each round', async () => {+ const { rounds } = await loadRoom()++ expect(rounds.rotateGroupSpeakers(MEMBERS, 1).map(m => m.name)).toEqual(['builder', 'ops', 'research'])+ expect(rounds.rotateGroupSpeakers([MEMBERS[0]], 3)).toHaveLength(1)+ })++ it('pulls a member mentioned by another bot into the NEXT round', async () => {+ const room = await loadRoom({+ turn: ({ profile, prompt }) => {+ if (profile === 'research' && !prompt.includes('(you)')) {+ return 'Interesting — @builder should own this.'+ }++ return profile === 'builder' ? 'On it. OWNER: @builder.' : '(pass)'+ }+ })++ room.rounds.sendToGroupChat(+ 'Core',+ [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ '@research thoughts?'+ )+ await settle(room, 'Core')++ const lines = log(room, 'Core').map(entry => `${entry.from.name}: ${entry.text}`)++ expect(lines.some(line => line.startsWith('research:'))).toBe(true)+ expect(lines.some(line => line.startsWith('builder: On it'))).toBe(true)+ })+})++describe('round lifecycle', () => {+ it('settles when everyone passes, logging only the user message', async () => {+ const room = await loadRoom()++ room.rounds.sendToGroupChat('Quiet', MEMBERS, 'fyi, deploy went out')+ await settle(room, 'Quiet')++ expect(log(room, 'Quiet')).toHaveLength(1)+ expect(log(room, 'Quiet')[0].from.kind).toBe('user')+ // Every member took exactly one turn (round 1), then the settle exit fired.+ expect(room.gateway.calls).toHaveLength(3)+ })++ it('stops chatty members at GROUP_CHAT_MAX_MESSAGES', async () => {+ const room = await loadRoom({ turn: ({ n }) => `message ${n} — @everyone keep going` })++ room.rounds.sendToGroupChat('Loud', MEMBERS, 'go wild')+ await settle(room, 'Loud')++ const posted = log(room, 'Loud').filter(entry => entry.from.kind === 'member')++ expect(posted.length).toBeLessThanOrEqual(room.chat.GROUP_CHAT_MAX_MESSAGES)+ })++ it('treats a failed member turn as a pass, not a room error', async () => {+ const room = await loadRoom({+ turn: ({ profile }) => {+ if (profile === 'builder') {+ throw new Error('gateway hiccup')+ }++ return '(pass)'+ }+ })++ room.rounds.sendToGroupChat('Flaky', MEMBERS, 'anyone around?')+ await settle(room, 'Flaky')++ // Just the user message; no error entries.+ expect(log(room, 'Flaky')).toHaveLength(1)+ })++ it('badges needs-you when a member addresses @user, and clears it on the next user send', async () => {+ const room = await loadRoom({+ turn: ({ profile }) => (profile === 'research' ? 'Blocked on billing access — @user which account?' : '(pass)')+ })++ const member: GroupMember[] = [{ name: 'research', title: '' }]++ room.rounds.sendToGroupChat('Escalate', member, 'sort out the invoices')+ await settle(room, 'Escalate')++ expect(room.chat.$groupNeedsYou.get().Escalate).toBe(true)++ room.rounds.sendToGroupChat('Escalate', member, 'use the ops account')++ expect(room.chat.$groupNeedsYou.get().Escalate).toBe(false)+ })++ it('converts an "(empty)" member reply like the gateway does, never appending it raw', async () => {+ const room = await loadRoom({ turn: ({ profile }) => (profile === 'research' ? '(empty)' : '(pass)') })++ room.rounds.sendToGroupChat('Sentinel', [{ name: 'research', title: '' }], '@research thoughts?')+ await settle(room, 'Sentinel')++ const replies = log(room, 'Sentinel').filter(entry => entry.from.kind === 'member')++ expect(replies).toHaveLength(1)+ expect(replies[0].text).toContain('The model returned no response after processing tool results')+ expect(replies[0].text).not.toContain('(empty)')+ })++ it('leaves normal replies untouched', async () => {+ const room = await loadRoom({ turn: ({ profile }) => (profile === 'research' ? 'I am not empty.' : '(pass)') })++ room.rounds.sendToGroupChat('Sentinel2', [{ name: 'research', title: '' }], '@research hi')+ await settle(room, 'Sentinel2')++ const replies = log(room, 'Sentinel2').filter(entry => entry.from.kind === 'member')++ expect(replies).toHaveLength(1)+ expect(replies[0].text).toBe('I am not empty.')+ })+})++describe('per-member delta', () => {+ it('feeds a second send only the NEW messages', async () => {+ const room = await loadRoom()+ const member: GroupMember[] = [{ name: 'research', title: '' }]++ room.rounds.sendToGroupChat('Delta', member, 'first message')+ await settle(room, 'Delta')+ const firstCount = room.gateway.calls.length+ room.rounds.sendToGroupChat('Delta', member, 'second message')+ await settle(room, 'Delta')++ const second = room.gateway.calls.slice(firstCount).find(call => call.prompt.includes('second message'))++ expect(second).toBeDefined()+ expect(second?.prompt).not.toContain('first message')+ })++ it('keeps concurrent rooms sharing one member isolated in sessions, deltas and context', async () => {+ const room = await loadRoom()+ const shared: GroupMember[] = [{ name: 'research', title: '' }]+ const quiet = () => !room.chat.$groupChats.get().Alpha?.running && !room.chat.$groupChats.get().Beta?.running++ // Start both rooms without waiting for either drive to finish.+ room.rounds.sendToGroupChat('Alpha', shared, 'ALPHA_ONLY_1')+ room.rounds.sendToGroupChat('Beta', shared, 'BETA_ONLY_1')+ await drain(() => !quiet())++ const alphaFirst = room.gateway.calls.find(call => call.title === 'Group: Alpha')+ const betaFirst = room.gateway.calls.find(call => call.title === 'Group: Beta')++ expect(alphaFirst && betaFirst).toBeTruthy()+ expect(alphaFirst?.stored).not.toBe(betaFirst?.stored)+ expect(alphaFirst?.runtime).not.toBe(betaFirst?.runtime)+ expect(alphaFirst?.prompt).toContain('ALPHA_ONLY_1')+ expect(alphaFirst?.prompt).not.toContain('BETA_ONLY_1')+ expect(betaFirst?.prompt).toContain('BETA_ONLY_1')+ expect(betaFirst?.prompt).not.toContain('ALPHA_ONLY_1')+ expect(room.chat.$groupChats.get().Alpha.sessions?.research).toBe(alphaFirst?.stored)+ expect(room.chat.$groupChats.get().Beta.sessions?.research).toBe(betaFirst?.stored)++ // Interleave a second pair. Each room resumes its own session and receives+ // only its unseen room delta, never the sibling room's messages.+ const firstCallCount = room.gateway.calls.length+ room.rounds.sendToGroupChat('Alpha', shared, 'ALPHA_ONLY_2')+ room.rounds.sendToGroupChat('Beta', shared, 'BETA_ONLY_2')+ await drain(() => !quiet())++ const second = room.gateway.calls.slice(firstCallCount)+ const alphaSecond = second.find(call => call.title === 'Group: Alpha')+ const betaSecond = second.find(call => call.title === 'Group: Beta')++ expect(alphaSecond?.stored).toBe(alphaFirst?.stored)+ expect(betaSecond?.stored).toBe(betaFirst?.stored)+ expect(alphaSecond?.prompt).toContain('ALPHA_ONLY_2')+ expect(alphaSecond?.prompt).not.toContain('ALPHA_ONLY_1')+ expect(alphaSecond?.prompt).not.toContain('BETA_ONLY_2')+ expect(betaSecond?.prompt).toContain('BETA_ONLY_2')+ expect(betaSecond?.prompt).not.toContain('BETA_ONLY_1')+ expect(betaSecond?.prompt).not.toContain('ALPHA_ONLY_2')++ const alphaSession = room.gateway.sessions.get(String(alphaFirst?.stored))+ const betaSession = room.gateway.sessions.get(String(betaFirst?.stored))++ expect(alphaSession?.messages.some(message => message.content.includes('BETA_ONLY'))).toBe(false)+ expect(betaSession?.messages.some(message => message.content.includes('ALPHA_ONLY'))).toBe(false)+ })+})++describe('threads', () => {+ it('mints a new thread per composer send and lands replies in it', async () => {+ const room = await loadRoom()+ const member: GroupMember[] = [{ name: 'research', title: '' }]++ const first = room.rounds.sendToGroupChat('Rooms', member, 'first topic')+ await settle(room, 'Rooms')+ const second = room.rounds.sendToGroupChat('Rooms', member, 'second topic')+ await settle(room, 'Rooms')++ expect(first).toBeTruthy()+ expect(second).toBeTruthy()+ expect(first).not.toBe(second)+ expect(log(room, 'Rooms')[0].thread).toBe(first)+ expect(log(room, 'Rooms')[1].thread).toBe(second)+ })++ it('continues an explicit thread and scopes the member delta to it', async () => {+ const room = await loadRoom({+ turn: ({ prompt }) => (prompt.includes('billing') ? 'On the billing fix.' : '(pass)')+ })++ const member: GroupMember[] = [{ name: 'research', title: '' }]++ const billing = room.rounds.sendToGroupChat('Scoped', member, 'fix the billing bug')+ await settle(room, 'Scoped')+ room.rounds.sendToGroupChat('Scoped', member, 'research pricing')+ await settle(room, 'Scoped')+ const again = room.rounds.sendToGroupChat('Scoped', member, 'billing follow-up: ship it', billing)+ await settle(room, 'Scoped')++ const followUp = room.gateway.calls.find(call => call.prompt.includes('ship it'))+ const replies = log(room, 'Scoped').filter(entry => entry.from.kind === 'member')++ expect(again).toBe(billing)+ expect(followUp).toBeDefined()+ expect(followUp?.prompt).not.toContain('research pricing')+ expect(replies.length).toBeGreaterThanOrEqual(1)+ expect(replies.every(entry => entry.thread === billing)).toBe(true)+ })+})++describe('turn prompt', () => {+ it('addresses the default profile as @hermes', async () => {+ const { rounds } = await loadRoom()++ const members: GroupMember[] = [+ { name: 'default', title: '' },+ { name: 'builder', title: '' }+ ]++ const own = rounds.buildGroupChatTurnPrompt({+ deltaLines: [],+ groupName: 'Core',+ members,+ viewer: { name: 'default', title: '' }+ })++ expect(own).toMatch(/You are @hermes,/)+ expect(own).not.toMatch(/@default\b/)++ const peer = rounds.buildGroupChatTurnPrompt({+ deltaLines: [],+ groupName: 'Core',+ members,+ viewer: { name: 'builder', title: '' }+ })++ expect(peer).toMatch(/group chat with @hermes/)+ })++ it('asks for full-quality results and short chatter, not short results', async () => {+ const { rounds } = await loadRoom()++ const prompt = rounds.buildGroupChatTurnPrompt({+ deltaLines: [],+ groupName: 'Core',+ members: [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ viewer: { name: 'research', title: '' }+ })++ expect(prompt).toMatch(/never thin out real content/i)+ expect(prompt).toMatch(/Keep chatter short/i)+ })+})++describe('attachments', () => {+ it('stages them into EVERY responding member session before that member submits', async () => {+ const room = await loadRoom()++ const members: GroupMember[] = [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ]++ room.rounds.sendToGroupChat('Vision', members, 'what does this show?', null, [IMG])+ await settle(room, 'Vision')++ expect(room.gateway.attaches).toHaveLength(2)+ expect(room.gateway.attaches.map(entry => entry.profile).sort()).toEqual(['builder', 'research'])++ for (const attach of room.gateway.attaches) {+ expect(attach.filename).toBe('screenshot.png')+ expect(attach.data).toBe(IMG.data)+ }++ // Each attach landed before that member's prompt.submit: the first attach+ // happens before any submit, the second before the second submit.+ expect(room.gateway.attaches[0].order).toBe(0)+ expect(room.gateway.attaches[1].order).toBeLessThanOrEqual(1)+ expect(room.gateway.calls).toHaveLength(2)+ })++ it('scopes attachments by mention: only the mentioned member receives the image', async () => {+ const room = await loadRoom()++ room.rounds.sendToGroupChat(+ 'Scoped',+ [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ '@builder look at this',+ null,+ [IMG]+ )+ await settle(room, 'Scoped')++ expect(room.gateway.attaches.map(entry => entry.profile)).toEqual(['builder'])+ })++ it('accepts an image-only send and carries the attachment on the room entry', async () => {+ const room = await loadRoom()++ const minted = room.rounds.sendToGroupChat(+ 'Silent',+ [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ '',+ null,+ [IMG]+ )++ await settle(room, 'Silent')++ expect(minted).toBeTruthy()+ expect(log(room, 'Silent')).toHaveLength(1)+ expect(log(room, 'Silent')[0].images?.[0].name).toBe('screenshot.png')+ // Members still got prompted (with the image staged).+ expect(room.gateway.attaches).toHaveLength(2)+ expect(room.gateway.calls).toHaveLength(2)+ })++ it('never re-attaches an old entry on a later turn', async () => {+ const room = await loadRoom()++ const members: GroupMember[] = [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ]++ room.rounds.sendToGroupChat('Plain', members, 'with image', null, [IMG])+ await settle(room, 'Plain')++ expect(room.gateway.attaches).toHaveLength(2)++ // The image already sits behind every member's watermark.+ room.rounds.sendToGroupChat('Plain', members, 'plain follow-up')+ await settle(room, 'Plain')++ expect(room.gateway.attaches).toHaveLength(2)+ })++ it('skips an invalid attachment and still runs the member turn text-only', async () => {+ const room = await loadRoom()++ room.rounds.sendToGroupChat(+ 'Degraded',+ [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ 'look',+ null,+ [{ data: null, name: 'bad' } as unknown as Attachment]+ )+ await settle(room, 'Degraded')++ expect(room.gateway.attaches).toHaveLength(0)+ expect(room.gateway.calls).toHaveLength(2)+ })++ it('routes PDFs through pdf.attach and files through file.attach, per member', async () => {+ const room = await loadRoom()+ const pdf: Attachment = { data: 'data:application/pdf;base64,JVBERi0=', kind: 'pdf', name: 'spec.pdf' }+ const doc: Attachment = { data: 'data:text/plain;base64,aGVsbG8=', kind: 'file', name: 'notes.txt' }++ room.rounds.sendToGroupChat(+ 'Mixed',+ [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ 'review these',+ null,+ [IMG, pdf, doc]+ )+ await settle(room, 'Mixed')++ const byMethod: Record<string, number> = {}++ for (const attach of room.gateway.attaches) {+ byMethod[attach.method] = (byMethod[attach.method] || 0) + 1+ }++ // 3 attachments × 2 members, each via its own RPC.+ expect(room.gateway.attaches).toHaveLength(6)+ expect(byMethod).toEqual({ 'file.attach': 2, 'image.attach_bytes': 2, 'pdf.attach': 2 })++ const staged = room.gateway.attaches.find(attach => attach.method === 'pdf.attach')++ expect(staged?.filename).toBe('spec.pdf')+ expect(staged?.data).toBe(pdf.data)+ })++ it('appends the file.attach ref_text to the member turn prompt', async () => {+ const room = await loadRoom()+ const doc: Attachment = { data: 'data:text/plain;base64,aGVsbG8=', kind: 'file', name: 'notes.txt' }++ room.rounds.sendToGroupChat(+ 'Refs',+ [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ 'read the notes',+ null,+ [doc]+ )+ await settle(room, 'Refs')++ expect(room.gateway.calls).toHaveLength(2)++ for (const call of room.gateway.calls) {+ expect(call.prompt).toContain('Attached files staged in your session workspace:')+ expect(call.prompt).toContain('notes.txt → @file:attachments/notes.txt')+ }+ })++ it('names attachments in the transcript line, labelling PDFs and files distinctly', async () => {+ const { rounds } = await loadRoom()+ const pdf: Attachment = { data: 'data:application/pdf;base64,JVBERi0=', kind: 'pdf', name: 'spec.pdf' }+ const doc: Attachment = { data: 'data:text/plain;base64,aGVsbG8=', kind: 'file', name: 'notes.txt' }+ const line = (entry: Partial<GroupMessage>) => rounds.formatGroupChatLine(entry as GroupMessage, 'research')++ expect(line({ from: { kind: 'user', name: 'You' }, images: [IMG], text: 'see attached' })).toBe(+ 'You (user): see attached [attached image: screenshot.png]'+ )+ expect(line({ from: { kind: 'user', name: 'You' }, text: 'plain' })).toBe('You (user): plain')+ expect(+ line({+ from: { kind: 'member', name: 'builder' },+ images: [{ data: 'data:image/png;base64,x' } as Attachment],+ text: 'made this'+ })+ ).toBe('builder: made this [attached image: image]')+ expect(line({ from: { kind: 'user', name: 'You' }, images: [pdf, doc, IMG], text: 'here' })).toBe(+ 'You (user): here [attached PDF: spec.pdf] [attached file: notes.txt] [attached image: screenshot.png]'+ )+ })+})++// #93129: a bot told to stop must STAY stopped.+describe('member holds (#93129)', () => {+ it('holds the mentioned member on an explicit stop', async () => {+ const { rounds } = await loadRoom()++ for (const text of ['stop @impl', '@impl stop', '@impl please halt', 'pause @impl for now']) {+ const action = rounds.classifyGroupHoldDirective(text, ['impl'], false)++ expect([...action.hold]).toEqual(['impl'])+ expect([...action.release]).toEqual([])+ }+ })++ it('holds nobody when a stop word carries no mention', async () => {+ const { rounds } = await loadRoom()++ expect([...rounds.classifyGroupHoldDirective('stop', [], false).hold]).toEqual([])+ })++ it('still holds on "don\'t stop @x" — the documented conservative trade-off', async () => {+ const { rounds } = await loadRoom()++ expect([...rounds.classifyGroupHoldDirective("don't stop @impl", ['impl'], false).hold]).toEqual(['impl'])+ })++ it('does not trigger on "stop" inside another word', async () => {+ const { rounds } = await loadRoom()++ // \b(stop|halt|pause)\b — "unstoppable" is a different token.+ const action = rounds.classifyGroupHoldDirective('@impl unstoppable work ahead', ['impl'], false)++ expect([...action.hold]).toEqual([])+ // A plain non-stop mention releases instead (direct address overrides hold).+ expect([...action.release]).toEqual(['impl'])+ })++ it('sets a hold on stop and clears it on resume for the same member', async () => {+ const { rounds } = await loadRoom()+ const stamp = { at: 1000, byMessageId: 'm1', thread: 't1' }++ const held = rounds.applyGroupHoldDirective({}, { everyone: false, mentioned: ['impl'] }, 'stop @impl', stamp)++ expect(held.impl).toBeTruthy()+ expect(held.impl.at).toBe(1000)+ expect(+ rounds.applyGroupHoldDirective(held, { everyone: false, mentioned: ['impl'] }, '@impl resume', stamp).impl+ ).toBeUndefined()+ })++ it('releases a held member on a direct non-stop mention', async () => {+ const { rounds } = await loadRoom()++ const next = rounds.applyGroupHoldDirective(+ { impl: { at: 1, byMessageId: null, thread: null } },+ { everyone: false, mentioned: ['impl'] },+ '@impl what is your status?',+ {}+ )++ expect(next.impl).toBeUndefined()+ })++ it('releases every hold on @all resume and sets every hold on @all stop', async () => {+ const { rounds } = await loadRoom()++ expect(+ rounds.applyGroupHoldDirective(+ { docs: { at: 2 }, impl: { at: 1 } },+ { everyone: true, mentioned: [] },+ '@all resume',+ {}+ )+ ).toEqual({})++ const held = rounds.applyGroupHoldDirective({}, { everyone: true, mentioned: [] }, '@all stop', { at: 5 }, [+ 'impl',+ 'docs'+ ])++ expect(held.impl).toBeTruthy()+ expect(held.docs).toBeTruthy()+ expect(held.impl.at).toBe(5)+ })++ it('leaves holds untouched on an unrelated room message', async () => {+ const { rounds } = await loadRoom()+ const held = { impl: { at: 1 } }++ expect(rounds.applyGroupHoldDirective(held, { everyone: false, mentioned: [] }, 'receipt round complete', {})).toBe(+ held+ )+ })++ it("does not disturb another member's hold", async () => {+ const { rounds } = await loadRoom()++ const next = rounds.applyGroupHoldDirective(+ { impl: { at: 1 } },+ { everyone: false, mentioned: ['docs'] },+ 'stop @docs',+ {+ at: 2+ }+ )++ expect(next.impl).toBeTruthy()+ expect(next.docs).toBeTruthy()+ })++ it('consumes a held skip exactly once so the loop cannot spin', async () => {+ const { rounds } = await loadRoom()++ // Fresh delta → advance to log length.+ expect(rounds.heldMemberWatermarkAdvance(3, 7)).toBe(7)+ // Already consumed → no write, no spin.+ expect(rounds.heldMemberWatermarkAdvance(7, 7)).toBeNull()+ expect(rounds.heldMemberWatermarkAdvance(9, 7)).toBeNull()+ // Unset watermark treated as 0.+ expect(rounds.heldMemberWatermarkAdvance(undefined, 2)).toBe(2)+ })+})++// #91868/#94569: a REAL stop path for group-chat rounds. Before+// stopGroupThread the loop's only cancellation primitives were the epoch bump+// (checked at member boundaries only) and #93129 holds (which skip FUTURE+// turns) — the plugin issued ZERO session.interrupt RPCs, so "stop" meant+// "wait for the in-flight member to finish its whole model turn".+describe('stopGroupThread (#91868/#94569)', () => {+ const STOP_MEMBERS: GroupMember[] = [+ { name: 'alpha', title: '' },+ { name: 'beta', title: '' },+ { name: 'gamma', title: '' }+ ]++ /** Seed a room mid-round: epoch 3, running, alpha on turn with a live+ * session id, nobody held yet. */+ function seedRoom(room: Room, turn: null | string = 'alpha') {+ room.chat.$groupChats.set({+ Room: {+ epoch: 3,+ holds: {},+ log: [],+ members: STOP_MEMBERS,+ running: true,+ sessions: { alpha: 'live-alpha-sid' },+ turn,+ watermarks: {}+ }+ } as unknown as Record<string, GroupChat>)+ }++ it('bumps the epoch, clears running/turn, and holds every member', async () => {+ const room = await loadRoom()+ seedRoom(room)++ await room.rounds.stopGroupThread('Room', 't1', STOP_MEMBERS)++ const state = room.chat.$groupChats.get().Room++ expect(state.epoch).toBe(4)+ expect(state.running).toBe(false)+ expect(state.turn).toBeNull()++ for (const member of STOP_MEMBERS) {+ expect(state.holds?.[member.name]).toBeTruthy()+ expect(state.holds?.[member.name].thread).toBe('t1')+ }+ })++ it('interrupts the member ON TURN via its live session', async () => {+ const room = await loadRoom()+ seedRoom(room)++ await room.rounds.stopGroupThread('Room', 't1', STOP_MEMBERS)++ const interrupts = room.gateway.rpcFor('session.interrupt')++ // Exactly one — the serial loop has one member in flight.+ expect(interrupts).toHaveLength(1)+ expect(interrupts[0].params.session_id).toBe('live-alpha-sid')+ })++ it('stops a room with nobody on turn without any interrupt RPC', async () => {+ const room = await loadRoom()+ seedRoom(room, null)++ await room.rounds.stopGroupThread('Room', 't1', STOP_MEMBERS)++ expect(room.gateway.rpcFor('session.interrupt')).toHaveLength(0)+ expect(room.chat.$groupChats.get().Room.running).toBe(false)+ expect(room.chat.$groupChats.get().Room.epoch).toBe(4)+ })++ it('records a stopped activity event visible in the CURRENT run', async () => {+ const room = await loadRoom()+ seedRoom(room)++ await room.rounds.stopGroupThread('Room', 't1', STOP_MEMBERS)++ const stopped = room.activity.currentGroupActivity('Room').find(event => event.kind === 'stopped')++ // Tagged with the POST-bump epoch, so it survives the epoch filter.+ expect(stopped).toBeTruthy()+ expect(stopped?.member).toBe('You')+ expect(stopped?.thread).toBe('t1')+ // The label comes from the shared activity label map and stays plain+ // English — no hardcoded localized text (the #94570 shell shipped a 停止).+ expect(room.activity.groupActivityLabel(stopped!)).toBeTruthy()+ expect(room.activity.groupActivityLabel(stopped!)).not.toMatch(/[\u4e00-\u9fff]/)+ expect(room.activity.GROUP_ACTIVITY_GLYPHS.stopped).toBeTruthy()+ })++ it('falls back to the durable room roster when called without members', async () => {+ const room = await loadRoom()+ seedRoom(room)++ await room.rounds.stopGroupThread('Room', 't1')++ expect(Object.keys(room.chat.$groupChats.get().Room.holds || {})).toHaveLength(STOP_MEMBERS.length)+ expect(room.gateway.rpcFor('session.interrupt')).toHaveLength(1)+ })++ it('abandons an in-flight turn once a stop bumps the epoch and holds the member', async () => {+ let live: Room | null = null++ const room = await loadRoom({+ onResumePoll: polls => {+ // Fire the stop from inside the poll cadence, after the second busy+ // poll — exactly the mid-turn click the Stop button produces.+ if (polls === 2) {+ void live?.rounds.stopGroupThread('Room', 't1', [{ name: 'helper', title: '' }])+ }+ },+ pollsBusy: 50,+ turn: () => 'long answer'+ })++ live = room++ const reply = await room.turns.runGroupChatMemberTurn('Room', { name: 'helper', title: '' }, 'long task', 't1', [])++ expect(reply).toBeNull()+ // The poll loop exited promptly after the stop, not at the deadline.+ expect(room.gateway.rpcFor('session.resume').length).toBeLessThanOrEqual(6)+ expect(room.chat.$groupChats.get().Room.running).toBe(false)+ })++ it('keeps polling through an ordinary newer-send epoch bump so late work still lands', async () => {+ let live: Room | null = null++ const room = await loadRoom({+ onResumePoll: polls => {+ if (polls === 1) {+ // A newer user send bumps the epoch but holds nobody. The in-flight+ // poll must keep going so the finished reply can still be delivered+ // (the #93127 commit check decides its fate at the boundary).+ live?.chat.updateGroupChat('Room', current => {+ current.epoch = (current.epoch || 0) + 1++ return current+ })+ }+ },+ pollsBusy: 3,+ turn: () => 'finished anyway'+ })++ live = room++ const reply = await room.turns.runGroupChatMemberTurn('Room', { name: 'helper', title: '' }, 'long task', 't1', [])++ expect(reply).toBe('finished anyway')+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.unaddressed.test.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.unaddressed.test.tsnew file mode 100644index 00000000000..a78f8eed959--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.unaddressed.test.ts@@ -0,0 +1,101 @@+/**+ * #94478 — the unresolved-handoff detector.+ *+ * A bot's @mention of a teammate inside its own reply IS visible to the next+ * round's responder selection, but the round loop exits before that round+ * runs: `spokeThisRound === 0` fires whenever the round's responders had no new+ * delta to read (everyone already spoke; the only new entry is the citing+ * reply), and a `GROUP_CHAT_MAX_*` cap can land in the same gap. The room then+ * records "settled" while a called bot never answered.+ *+ * `unaddressedGroupMentions` is what the quiet-round exit consults before+ * settling, so the continuation round it drives is only as correct as this+ * detector. Two subtleties it has to get right:+ *+ * - **Log INDEX, not entry id, is the ordering.** Entry ids are UUIDs+ * (`groupChatEntryId`), so "answered after the citing entry" can only mean+ * positional order. Sorting by id marked answered handoffs as pending and+ * re-drove them — a loop.+ * - **A self-citation is not a handoff**, and neither is a user entry: a user+ * send re-drives everyone anyway.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import { $groupChats } from './group-chat'+import { unaddressedGroupMentions } from './group-rounds'+import type { GroupMember, GroupMessage } from './types'++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ host: {+ request: vi.fn(),+ state: { connectionId: { get: () => 'local' }, profile: { get: () => 'default' } }+ },+ queryClient: { invalidateQueries: vi.fn() },+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++const members = [{ name: 'alpha' }, { name: 'beta' }, { name: 'gamma' }] as GroupMember[]++const from = (name: string, id: string, text: string): GroupMessage =>+ ({ at: 0, from: { kind: 'member', name }, id, text, thread: 't1' }) as GroupMessage++const fromUser = (id: string, text: string): GroupMessage =>+ ({ at: 0, from: { kind: 'user', name: 'You' }, id, text, thread: 't1' }) as GroupMessage++function room(log: GroupMessage[]) {+ $groupChats.set({ g: { log, members, roomId: 'room-1' } as never })+}++beforeEach(() => {+ $groupChats.set({})+})++describe('unaddressedGroupMentions', () => {+ it('flags a cited member with no later post', () => {+ room([from('alpha', 'zzzz-0002', 'hello'), from('beta', 'aaaa-0003', 'ping @gamma — take this')])++ expect(unaddressedGroupMentions('g', members, 't1')).toEqual(['gamma'])+ })++ it('counts a reply that follows in LOG order even when its id sorts lower', () => {+ room([from('beta', 'aaaa-0003', 'ping @gamma — take this'), from('gamma', '9999-0004', 'on it')])++ expect(unaddressedGroupMentions('g', members, 't1')).toEqual([])+ })++ it('re-flags a handoff cited again after the answer', () => {+ room([from('beta', 'a', 'ping @gamma'), from('gamma', 'b', 'on it'), from('beta', 'c', 'one more thing @gamma')])++ expect(unaddressedGroupMentions('g', members, 't1')).toEqual(['gamma'])+ })++ it('never treats a self-citation or a user entry as a handoff', () => {+ room([+ from('alpha', 'bbbb-0001', 'I will do @alpha things myself'),+ fromUser('cccc-0002', '@beta @gamma look here')+ ])++ expect(unaddressedGroupMentions('g', members, 't1')).toEqual([])+ })++ it('ignores citations in another thread', () => {+ const other = { ...from('beta', 'x', 'ping @gamma'), thread: 't2' } as GroupMessage++ room([other, from('alpha', 'y', 'unrelated')])++ expect(unaddressedGroupMentions('g', members, 't1')).toEqual([])+ })++ it('reports nothing for an unknown room', () => {+ expect(unaddressedGroupMentions('missing', members, 't1')).toEqual([])+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts b/apps/desktop/src/plugins/hermes-bots/group-test-utils.tsnew file mode 100644index 00000000000..d8cd15679cf--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts@@ -0,0 +1,483 @@+/**+ * A scripted gateway for the group-chat room-engine tests.+ *+ * A member turn is a session-scoped RPC SEQUENCE (create/resume → attach →+ * prompt.submit → poll), so nearly every room contract is only observable in+ * what those RPCs saw. This models the parts of the gateway's session+ * lifecycle those contracts depend on:+ *+ * - the STORED id is the durable identity and every `session.resume` mints a+ * FRESH runtime id, which is why a turn that loses its socket mid-sequence+ * has to recover through the stored id (#93602);+ * - a missing session answers JSON-RPC 4007 — the real "genuinely not found"+ * code that `ensureGroupChatSession`'s fail-closed branch keys on, so a+ * plain failure here is NOT read as "no session, mint a new one";+ * - `host.requestProfile` takes a per-request socket lease and disposes the+ * socket at refcount 0, the reap that made routed members go silent.+ *+ * Its predecessors sliced `plugin.js` out of the bundle with string offsets+ * and ran it under `vm`; this drives the real modules through the real+ * `host` surface instead.+ */++import type { PluginContext } from '@hermes/plugin-sdk'+import { vi } from 'vitest'++/** One message in a scripted session transcript, in the gateway's own shape. */+export interface ScriptedMessage {+ content: string+ role: string+}++export interface ScriptedSession {+ messages: ScriptedMessage[]+ profile: string+ runtime: string+ stored: string+ title: string+}++/** What the scripted member "said" this turn: one reply, or the whole tail of+ * messages a real turn can append (a substantive answer plus a continuation+ * nudge and its synthetic pass, #94376). */+export type TurnReply = ScriptedMessage[] | string++export interface ScriptedTurn {+ /** 1-based index across every prompt.submit the gateway has seen. */+ n: number+ profile: string+ prompt: string+ session: ScriptedSession+}++export type TurnScript = (turn: ScriptedTurn) => Promise<TurnReply> | TurnReply++/** Every prompt.submit the gateway received, with the session it landed on. */+export interface PromptCall {+ profile: string+ prompt: string+ runtime: string+ stored: string+ title: string+}++/** Every attachment staging RPC, and how many submits preceded it. */+export interface AttachCall {+ data: string+ filename: string+ method: string+ order: number+ profile: null | string+ runtime: string+}++export interface RpcCall {+ method: string+ params: Record<string, unknown>+ /** Socket refcount after this request released its own lease. */+ refcountAfter: number+}++export interface GatewayOptions {+ /** Per profile: report inflight/running on its first N `session.resume`s. */+ busyResumes?: Record<string, number>+ /** Per profile: carry `pending_approval` on its first `until` resumes. */+ approvalUntil?: Record<string, { payload: Record<string, unknown>; until: number }>+ /** Per profile: carry `pending_clarify` on its first `until` resumes. */+ clarifyUntil?: Record<string, { payload: Record<string, unknown>; until: number }>+ /** Land a competing writer's `ui_meta` under `key` during the FIRST+ * `profiles.configure`, then reject it as a CAS conflict — the race the+ * sync worker's pull-merge-retry exists for. */+ conflictOnce?: { key: string; value: unknown }+ /** Reject every prompt.submit with this — a fatal, non-recoverable failure. */+ failEverySubmitWith?: unknown+ /** Reject only the FIRST prompt.submit — the 4001 reap the retry recovers. */+ failFirstSubmitWith?: unknown+ /** Fired on each post-submit poll, so a test can land a stop mid-turn. */+ onResumePoll?: (polls: number) => void+ /** Report the member inflight for the first N post-submit polls. */+ pollsBusy?: number+ turn?: TurnScript+}++/** A gateway-shaped rejection: `.code` is what the engine branches on. */+function gatewayError(message: string, code: number) {+ return Object.assign(new Error(message), { code })+}++export interface ScriptedGateway {+ /** Attachment staging RPCs, in order. */+ attaches: AttachCall[]+ /** prompt.submit calls, in order. */+ calls: PromptCall[]+ /** Times the socket refcount fell to zero — each one reaps a runtime session. */+ disposals: () => number+ /** The mock `host` the `@hermes/plugin-sdk` mock should expose. */+ host: Record<string, unknown>+ /** Every RPC, for methods the typed recorders above don't cover. */+ rpc: RpcCall[]+ /** Filter `rpc` by method. */+ rpcFor: (method: string) => RpcCall[]+ /** Live socket refcount — zero between turns, never zero during one. */+ refcount: () => number+ /** Sessions by stored id, so a test can pre-seed a finished transcript. */+ sessions: Map<string, ScriptedSession>+ /** Plugin storage writes, by key. */+ storage: Map<string, unknown>+ /** `retain`/`release`/method names in call order — the lease lifetime. */+ timeline: string[]+ /** The default profile's `ui_meta`, as `profiles.list` reports it. */+ uiMeta: Record<string, unknown>+ /** CAS revisions for `uiMeta`, advanced by every applied configure. */+ uiMetaRevisions: Record<string, number>+}++export function createGroupGateway(options: GatewayOptions = {}): ScriptedGateway {+ const { turn = () => '(pass)' } = options+ const sessions = new Map<string, ScriptedSession>()+ const runtimeToStored = new Map<string, string>()+ const titleToStored = new Map<string, string>()+ const resumesByProfile = new Map<string, number>()+ const calls: PromptCall[] = []+ const attaches: AttachCall[] = []+ const rpc: RpcCall[] = []+ const timeline: string[] = []+ const storage = new Map<string, unknown>()+ const uiMeta: Record<string, unknown> = {}+ const uiMetaRevisions: Record<string, number> = {}+ let sequence = 0+ let submits = 0+ let polls = 0+ let refcount = 0+ let disposals = 0+ let conflicted = false++ const resolveSession = (profile: unknown, target: unknown) => {+ const key = String(target ?? '')++ const stored =+ runtimeToStored.get(key) || (sessions.has(key) ? key : titleToStored.get(`${String(profile)}::${key}`))++ return stored ? sessions.get(stored) || null : null+ }++ const handle = async (method: string, params: Record<string, unknown>): Promise<unknown> => {+ if (method === 'profiles.list') {+ return {+ profiles: [{ name: 'default', ui_meta: { ...uiMeta }, ui_meta_revisions: { ...uiMetaRevisions } }]+ }+ }++ if (method === 'profiles.configure') {+ if (options.conflictOnce && !conflicted) {+ conflicted = true+ const { key, value } = options.conflictOnce+ uiMeta[key] = value+ uiMetaRevisions[key] = (uiMetaRevisions[key] || 0) + 1++ return {+ applied: {+ ui_meta: false,+ ui_meta_conflicts: { [key]: { actual: uiMetaRevisions[key], expected: uiMetaRevisions[key] - 1 } },+ ui_meta_revisions: { ...uiMetaRevisions }+ }+ }+ }++ const expected = params.ui_meta_expected_revisions as Record<string, number> | undefined+ const incoming = (params.ui_meta || {}) as Record<string, unknown>++ if (expected) {+ for (const key of Object.keys(incoming)) {+ if ((uiMetaRevisions[key] || 0) !== expected[key]) {+ return {+ applied: {+ ui_meta: false,+ ui_meta_conflicts: { [key]: { actual: uiMetaRevisions[key] || 0, expected: expected[key] } }+ }+ }+ }+ }+ }++ for (const [key, value] of Object.entries(incoming)) {+ if (value === null) {+ delete uiMeta[key]+ } else {+ uiMeta[key] = value+ }++ uiMetaRevisions[key] = (uiMetaRevisions[key] || 0) + 1+ }++ return { applied: { ui_meta: true, ui_meta_revisions: { ...uiMetaRevisions } } }+ }++ if (method === 'session.create') {+ sequence += 1+ const profile = String(params.profile ?? '')+ const title = String(params.title ?? '')++ const session: ScriptedSession = {+ messages: [],+ profile,+ runtime: `rt-${profile}-${sequence}`,+ stored: `sid-${profile}-${sequence}`,+ title+ }++ sessions.set(session.stored, session)+ runtimeToStored.set(session.runtime, session.stored)+ titleToStored.set(`${profile}::${title}`, session.stored)++ return { message_count: 0, messages: [], session_id: session.runtime, stored_session_id: session.stored }+ }++ if (method === 'session.resume') {+ const session = resolveSession(params.profile, params.session_id)++ if (!session) {+ throw gatewayError(`session not found: ${String(params.session_id)}`, 4007)+ }++ // Every resume mints a fresh runtime id; the stored id is the durable+ // identity. Old runtime ids stay resolvable so an in-flight turn that+ // still holds one is not spuriously reaped by the harness itself.+ sequence += 1+ session.runtime = `rt-${session.profile}-${sequence}`+ runtimeToStored.set(session.runtime, session.stored)++ const seen = (resumesByProfile.get(session.profile) || 0) + 1+ resumesByProfile.set(session.profile, seen)+ let busy = Boolean(options.busyResumes?.[session.profile] && seen <= options.busyResumes[session.profile])++ if (session.messages.length > 0) {+ polls += 1+ busy = busy || Boolean(options.pollsBusy && polls <= options.pollsBusy)+ options.onResumePoll?.(polls)+ }++ const clarify = options.clarifyUntil?.[session.profile]+ const approval = options.approvalUntil?.[session.profile]++ return {+ inflight: busy,+ message_count: busy ? 0 : session.messages.length,+ messages: busy || params.omit_messages ? [] : [...session.messages],+ running: false,+ session_id: session.runtime,+ session_key: session.stored,+ ...(clarify && seen <= clarify.until ? { pending_clarify: clarify.payload } : {}),+ ...(approval && seen <= approval.until ? { pending_approval: approval.payload } : {})+ }+ }++ if (method === 'image.attach_bytes' || method === 'pdf.attach' || method === 'file.attach') {+ const session = resolveSession(null, params.session_id)++ if (!session) {+ throw gatewayError(`session-scoped RPC rejected: ${String(params.session_id)} not in memory`, 4001)+ }++ attaches.push({+ data: String(params.content_base64 ?? params.data_url ?? ''),+ filename: String(params.filename ?? params.name ?? ''),+ method,+ order: calls.length,+ profile: session.profile,+ runtime: String(params.session_id ?? '')+ })++ return method === 'file.attach'+ ? { attached: true, ref_text: `@file:attachments/${String(params.name ?? 'attachment')}` }+ : { attached: true }+ }++ if (method === 'prompt.submit') {+ submits += 1++ if (options.failEverySubmitWith) {+ throw options.failEverySubmitWith+ }++ if (submits === 1 && options.failFirstSubmitWith) {+ throw options.failFirstSubmitWith+ }++ const session = resolveSession(null, params.session_id)++ if (!session) {+ throw gatewayError(`session-scoped RPC rejected: ${String(params.session_id)} not in memory`, 4001)+ }++ const prompt = String(params.text ?? '')+ session.messages.push({ content: prompt, role: 'user' })+ calls.push({+ profile: session.profile,+ prompt,+ runtime: session.runtime,+ stored: session.stored,+ title: session.title+ })+ const reply = await turn({ n: calls.length, profile: session.profile, prompt, session })++ for (const message of typeof reply === 'string' ? [{ content: reply, role: 'assistant' }] : reply) {+ session.messages.push(message)+ }++ return {}+ }++ return {}+ }++ const record = async (method: string, params: Record<string, unknown>) => {+ try {+ return await handle(method, params)+ } finally {+ rpc.push({ method, params, refcountAfter: refcount })+ }+ }++ const host: Record<string, unknown> = {+ activeConnectionId: () => 'local',+ notify: vi.fn(),+ notifyError: vi.fn(),+ request: async (method: string, params: Record<string, unknown> = {}) => record(method, params),+ requestProfile: async (_route: unknown, method: string, params: Record<string, unknown> = {}) => {+ refcount += 1++ try {+ return await handle(method, params)+ } finally {+ refcount -= 1++ if (refcount === 0) {+ disposals += 1+ }++ rpc.push({ method, params, refcountAfter: refcount })+ timeline.push(method)+ }+ },+ retainProfile: async () => {+ timeline.push('retain')+ refcount += 1+ let released = false++ return () => {+ if (released) {+ return+ }++ released = true+ timeline.push('release')+ refcount -= 1++ if (refcount === 0) {+ disposals += 1+ }+ }+ },+ setWorkspaceScope: vi.fn(),+ state: {+ connectionId: { get: () => 'local', listen: () => () => undefined },+ gateway: { get: () => 'open', listen: () => () => undefined },+ profile: { get: () => 'default', listen: () => () => undefined }+ }+ }++ return {+ attaches,+ calls,+ disposals: () => disposals,+ host,+ refcount: () => refcount,+ rpc,+ rpcFor: (method: string) => rpc.filter(entry => entry.method === method),+ sessions,+ storage,+ timeline,+ uiMeta,+ uiMetaRevisions+ }+}++/** The `@hermes/plugin-sdk` surface the group modules actually reach for.+ * `atom` must be the real nanostores one — the room store IS its atoms — and+ * it has to come from the CURRENT module generation, so this is built inside+ * the `vi.mock` factory rather than hoisted alongside it. */+export async function pluginSdkMock(host: Record<string, unknown>) {+ const nanostores = await import('nanostores')++ return {+ atom: nanostores.atom,+ // Feature-detected SDK members: the modules read them off the namespace+ // and fall back when absent, but vitest rejects a namespace access with+ // no matching export at all — so they have to be present and undefined.+ BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS: undefined,+ blobatarSvg: undefined,+ computed: nanostores.computed,+ createBudgetedLoop: undefined,+ host,+ SkillsView: undefined,+ Streamdown: undefined,+ queryClient: { invalidateQueries: () => undefined },+ useQuery: () => ({ data: [], isLoading: false }),+ useValue: <T>(store: { get: () => T }) => store.get()+ }+}++/** Plugin storage backed by a plain map, for `setPluginCtx`. */+export function scriptedStorage(storage: Map<string, unknown>): PluginContext {+ return {+ storage: {+ get: async (key: string) => storage.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ storage.set(key, structuredClone(value))+ }+ }+ // The modules under test only ever reach for ctx.storage; the rest of the+ // host-supplied context has no bearing on room state.+ } as unknown as PluginContext+}++/** Run the room engine's timers inline.+ *+ * The turn poll sleeps `GROUP_TURN_POLL_MS` between resumes and the sync+ * mirror debounces by 350ms; both are wall-clock waits a test must not+ * actually serve. Resolving immediately keeps the awaits (and therefore the+ * interleaving the race contracts depend on) while removing the delay. */+export function runTimersInline() {+ vi.stubGlobal('setTimeout', (fn: () => void) => {+ fn()++ return 0+ })+ vi.stubGlobal('clearTimeout', () => undefined)+}++/** Run the engine's timers on the next macrotask instead of inline.+ *+ * The sync worker's retry path stores its own timer handle AFTER scheduling+ * it (`retryTimers.set(id, setTimeout(...))`), so an inline timer deletes the+ * handle before it is written and the entry never clears. Deferring keeps+ * that ordering intact while still ignoring the backoff delay. */+export function deferTimers() {+ vi.stubGlobal('setTimeout', (fn: () => void) => {+ setImmediate(fn)++ return 1+ })+ vi.stubGlobal('clearTimeout', () => undefined)+}++/** Let the room engine's async loop run to completion. */+export async function drain(isRunning: () => boolean, limit = 400) {+ for (let i = 0; i < limit && isRunning(); i++) {+ await new Promise(resolve => setImmediate(resolve))+ }++ // One more flush so the `finally` bookkeeping after the last await lands.+ await new Promise(resolve => setImmediate(resolve))+}diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.test.tsnew file mode 100644index 00000000000..43a77c19d81--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts@@ -0,0 +1,652 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as groupChat from './group-chat'+import type * as groupRounds from './group-rounds'+import { createGroupGateway, drain, runTimersInline, scriptedStorage } from './group-test-utils'+import type { GatewayOptions, ScriptedGateway } from './group-test-utils'+import type * as groupTurns from './group-turns'+import type { Attachment, GroupChat, GroupMember } from './types'++// One member's turn: resolve its per-room session, stage attachments, submit,+// and poll until the gateway says the member is done. The session is the+// fragile part — it is addressed by a STORED id that outlives every runtime+// id, and the socket it rides can be reaped underneath a turn in flight.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')++ return pluginSdkMock(host)+})++interface Room {+ chat: typeof groupChat+ gateway: ScriptedGateway+ rounds: typeof groupRounds+ turns: typeof groupTurns+}++async function loadRoom(options: GatewayOptions = {}): Promise<Room> {+ vi.resetModules()+ const gateway = createGroupGateway(options)++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [chat, rounds, turns, shared] = await Promise.all([+ import('./group-chat'),+ import('./group-rounds'),+ import('./group-turns'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { chat, gateway, rounds, turns }+}++const LOCAL_MEMBER: GroupMember = { name: 'helper', title: '' }+const ROUTED_MEMBER: GroupMember = { connectionId: 'mini', name: 'helper', remoteSource: true }+const IMG: Attachment = { data: 'data:image/png;base64,iVBORw0KGgo=', kind: 'image', name: 'shot.png' }++const log = (room: Room, group: string) => room.chat.$groupChats.get()[group]?.log || []++beforeEach(() => {+ runTimersInline()+})++describe('session resolution', () => {+ it('pins session titles to the roomId, with a legacy fallback to the display name', async () => {+ const room = await loadRoom()++ // Rooms persisted before roomIds keep name-based titles so their existing+ // "Group: <name>" sessions keep resolving after an upgrade.+ room.chat.updateGroupChat('Legacy', current => current)+ const legacy = await room.turns.ensureGroupChatSession('Legacy', { name: 'research', title: '' })++ expect(room.gateway.sessions.get(String(legacy.stored))?.title).toBe('Group: Legacy')++ // New rooms pin the title to the immutable roomId, never the display name.+ room.chat.updateGroupChat('New', current => {+ current.roomId = 'r-abc'++ return current+ })+ const fresh = await room.turns.ensureGroupChatSession('New', { name: 'research', title: '' })++ expect(room.gateway.sessions.get(String(fresh.stored))?.title).toBe('Group: r-abc')+ })++ it('mints fresh member sessions when a same-name group is recreated after disband', async () => {+ const room = await loadRoom()+ const member: GroupMember = { name: 'research', title: '' }++ room.chat.updateGroupChat('Alpha', current => {+ current.roomId = 'r-one'++ return current+ })+ const first = await room.turns.ensureGroupChatSession('Alpha', member)++ // Disband: the room record is gone; the member's gateway session survives.+ const rooms = { ...room.chat.$groupChats.get() }+ delete rooms.Alpha+ room.chat.$groupChats.set(rooms)++ // Recreate under the same display name with a freshly minted roomId.+ room.chat.updateGroupChat('Alpha', current => {+ current.roomId = 'r-two'++ return current+ })+ const second = await room.turns.ensureGroupChatSession('Alpha', member)++ expect(first.stored).not.toBe(second.stored)+ expect(room.gateway.sessions.get(String(first.stored))?.title).toBe('Group: r-one')+ expect(room.gateway.sessions.get(String(second.stored))?.title).toBe('Group: r-two')+ })++ it('fails closed on a transient resume failure instead of forking the member session', async () => {+ // Mirrors findExistingCanonicalChat's fix (87b645f52c): a resume that+ // fails for any reason OTHER than "genuinely doesn't exist" (JSON-RPC code+ // 4007) must surface, not be read as "no session, mint a new one" — that+ // would fork the member's real history and silently overwrite+ // room.sessions[key] so the old session becomes unreachable.+ const room = await loadRoom()+ const member: GroupMember = { name: 'research', title: '' }++ room.chat.updateGroupChat('Alpha', current => {+ current.roomId = 'r-one'++ return current+ })+ const first = await room.turns.ensureGroupChatSession('Alpha', member)+ const before = room.chat.$groupChats.get().Alpha.sessions++ // A real gateway error on the NEXT resume of the member's own stored+ // session — backend still warming up, a network blip, not "not found".+ const request = host.request as (method: string, params: Record<string, unknown>) => Promise<unknown>++ host.request = async (method: string, params: Record<string, unknown>) => {+ if (method === 'session.resume' && params.session_id === first.stored) {+ throw Object.assign(new Error('gateway temporarily unavailable'), { code: 5000 })+ }++ return request(method, params)+ }++ await expect(room.turns.ensureGroupChatSession('Alpha', member)).rejects.toThrow(/Could not check .*group session/)++ host.request = request++ // Nothing was forked: the room's session pointer is untouched, and the+ // original session is still the only one on record for this member.+ expect(room.chat.$groupChats.get().Alpha.sessions).toEqual(before)+ expect(room.gateway.sessions.size).toBe(1)+ })++ it('falls through a genuine 4007 to the title lookup, then creates', async () => {+ const room = await loadRoom()++ room.chat.updateGroupChat('Alpha', current => {+ current.roomId = 'r-one'+ // A stored sid pointing at a session the gateway no longer has (e.g. an+ // out-of-band deletion) is a genuine 4007 on the first target.+ current.sessions = { research: 'sid-gone' }++ return current+ })++ const result = await room.turns.ensureGroupChatSession('Alpha', { name: 'research', title: '' })++ expect(result.stored).toBeTruthy()+ expect(result.stored).not.toBe('sid-gone')+ })+})++describe('session-gone classification', () => {+ it('treats 4001 and "not in memory" as recoverable, 4007 as not', async () => {+ const { turns } = await loadRoom()++ expect(turns.isSessionGoneError(Object.assign(new Error('x'), { code: 4001 }))).toBe(true)+ expect(turns.isSessionGoneError(new Error('session_id=rt-1 not in memory'))).toBe(true)+ expect(turns.isSessionGoneError(Object.assign(new Error('session not found'), { code: 4007 }))).toBe(false)+ expect(turns.isSessionGoneError(null)).toBe(false)+ expect(turns.isSessionGoneError(new Error('network blip'))).toBe(false)+ })++ it('recovers a 4001 on the first submit via the STORED id and delivers', async () => {+ const room = await loadRoom({+ failFirstSubmitWith: Object.assign(new Error("session-scoped RPC rejected: session_id='rt-1' not in memory"), {+ code: 4001+ }),+ turn: () => 'recovered reply'+ })++ const reply = await room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi there', 't1', [])++ expect(reply).toBe('recovered reply')+ // One failed submit + exactly one retry — never more.+ expect(room.gateway.rpcFor('prompt.submit')).toHaveLength(2)+ // The recovery re-resumed the durable stored id, not the dead runtime id.+ expect(room.chat.$groupChats.get().Room.sessions?.helper).toBeTruthy()+ })++ it('does not retry a persistent non-4001 submit failure', async () => {+ const room = await loadRoom({ failEverySubmitWith: new Error('backend exploded') })++ await expect(room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi', 't1', [])).rejects.toThrow(+ 'backend exploded'+ )+ expect(room.gateway.rpcFor('prompt.submit')).toHaveLength(1)+ })+})++describe('per-turn socket lease', () => {+ it('is acquired before any session RPC and held across attach + submit', async () => {+ const room = await loadRoom({ turn: () => 'routed reply' })++ const reply = await room.turns.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'look at this', 't1', [IMG])++ expect(reply).toBe('routed reply')+ // The retain landed before the first session-scoped RPC on the route.+ expect(room.gateway.timeline[0]).toBe('retain')++ // The socket was NEVER disposed mid-turn: after every per-request lease+ // released, the turn lease still held the refcount above zero.+ for (const call of room.gateway.rpc) {+ expect(call.refcountAfter).toBeGreaterThanOrEqual(1)+ }++ // Exactly one disposal, via the turn lease's own release at the end.+ expect(room.gateway.disposals()).toBe(1)+ expect(room.gateway.timeline.at(-1)).toBe('release')+ })++ it('is released after the turn — the refcount returns to zero', async () => {+ const room = await loadRoom({ turn: () => 'done' })++ await room.turns.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', [])++ expect(room.gateway.refcount()).toBe(0)+ expect(room.gateway.disposals()).toBe(1)+ })++ it('is released even when the turn fails', async () => {+ const room = await loadRoom({ failEverySubmitWith: new Error('backend exploded') })++ await expect(room.turns.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', [])).rejects.toThrow()+ expect(room.gateway.refcount()).toBe(0)+ })++ it('is feature-detected: hosts without retainProfile still run the turn', async () => {+ const room = await loadRoom({ turn: () => 'legacy ok' })+ delete host.retainProfile++ expect(await room.turns.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', [])).toBe('legacy ok')+ })+})++// #94376: a Codex intent-ack continuation nudge can land a substantive+// answer, then get a synthetic "(pass)" reply to the nudge itself.+describe('reply selection (#94376)', () => {+ it('surfaces a substantive answer followed by a synthetic continuation (pass)', async () => {+ const answer = "Yes. I welcomed them, and I'll review their first assignments with them."++ const room = await loadRoom({+ turn: () => [+ { content: answer, role: 'assistant' },+ {+ content:+ '[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.]',+ role: 'user'+ },+ { content: '(pass)', role: 'assistant' }+ ]+ })++ expect(await room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'Did you welcome them?', 't1', [])).toBe(+ answer+ )+ })++ it('still reads a genuine pass-only turn as silent', async () => {+ const room = await loadRoom({ turn: () => '(pass)' })++ expect(await room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'anything new?', 't1', [])).toBe('(pass)')+ })+})++// #90694: a member can block inside its own turn on a clarify question or a+// command approval. Those live in a hidden session the room can't see, so the+// poll mirrors them into the room and holds the turn open until they resolve.+describe('clarify and approvals (#90694)', () => {+ const CLARIFY = {+ choices: ['staging', 'prod'],+ multi_select: false,+ question: 'Which env should I target?',+ request_id: 'req-clarify-1'+ }++ const APPROVAL = {+ choices: ['once', 'session', 'deny'],+ command: 'rm -rf ./build',+ description: 'Clean the build directory',+ request_id: 'req-approval-1'+ }++ it('holds the turn open while a member is blocked on clarify, then lands the reply', async () => {+ const room = await loadRoom({+ clarifyUntil: { research: { payload: CLARIFY, until: 3 } },+ turn: () => 'targeting staging'+ })++ const thread = room.rounds.sendToGroupChat(+ 'Core',+ [{ name: 'research', title: '' }],+ '@research deploy it',+ null,+ []+ )++ await drain(() => Boolean(room.chat.$groupChats.get().Core?.running))++ const replies = log(room, 'Core').filter(entry => entry.thread === thread && entry.from.kind === 'member')++ expect(replies).toHaveLength(1)+ expect(replies[0].text).toBe('targeting staging')+ expect(Object.keys(room.chat.$groupClarify.get())).toHaveLength(0)+ // The mirror pass ran while the question was blocking, badging the room.+ // A poll that never inspects pending_clarify leaves this unset — it is the+ // observable proof the gate executed.+ expect(room.chat.$groupNeedsYou.get().Core).toBe(true)+ })++ it('mirrors a question, badges needs-you, and is idempotent per request', async () => {+ const { chat, turns } = await loadRoom()+ const member: GroupMember = { name: 'research', title: '' }++ expect(turns.syncGroupClarify('Core', member, { pending_clarify: CLARIFY })).toBe(true)++ const mirrored = Object.values(chat.$groupClarify.get())++ expect(mirrored).toHaveLength(1)+ expect(mirrored[0].requestId).toBe('req-clarify-1')+ expect(mirrored[0].question).toBe('Which env should I target?')+ expect(mirrored[0].choices).toEqual(['staging', 'prod'])+ expect(chat.$groupNeedsYou.get().Core).toBe(true)++ // Same request again: no new entry, identity preserved.+ turns.syncGroupClarify('Core', member, { pending_clarify: CLARIFY })++ expect(Object.values(chat.$groupClarify.get())[0]).toBe(mirrored[0])++ // Question resolved server-side: the mirror clears.+ expect(turns.syncGroupClarify('Core', member, {})).toBe(false)+ expect(Object.keys(chat.$groupClarify.get())).toHaveLength(0)+ })++ it('never mirrors a question for older backends without pending_clarify', async () => {+ const { chat, turns } = await loadRoom()++ expect(turns.syncGroupClarify('Core', { name: 'research' }, { messages: [] })).toBe(false)+ expect(Object.keys(chat.$groupClarify.get())).toHaveLength(0)+ })++ it('routes an answer through clarify.respond and clears the mirror', async () => {+ const room = await loadRoom()+ const member: GroupMember = { name: 'research', title: '' }++ room.turns.syncGroupClarify('Core', member, { pending_clarify: CLARIFY })+ await room.turns.answerGroupClarify(Object.values(room.chat.$groupClarify.get())[0], member, 'staging')++ expect(room.gateway.rpcFor('clarify.respond').map(call => call.params)).toEqual([+ { answer: 'staging', request_id: 'req-clarify-1' }+ ])+ expect(Object.keys(room.chat.$groupClarify.get())).toHaveLength(0)+ })++ it('sends one respond per batch question, in order', async () => {+ const room = await loadRoom()+ const member: GroupMember = { name: 'research', title: '' }++ room.turns.syncGroupClarify('Core', member, {+ pending_clarify: {+ questions: [+ { choices: ['staging', 'prod'], qid: 'q0', question: 'Env?' },+ { choices: [], qid: 'q1', question: 'Region?' }+ ],+ request_id: 'req-batch-1'+ }+ })+ await room.turns.answerGroupClarify(Object.values(room.chat.$groupClarify.get())[0], member, {+ q0: 'staging',+ q1: 'eu-west'+ })++ expect(room.gateway.rpcFor('clarify.respond').map(call => call.params)).toEqual([+ { answer: 'staging', question_id: 'q0', request_id: 'req-batch-1' },+ { answer: 'eu-west', question_id: 'q1', request_id: 'req-batch-1' }+ ])+ expect(Object.keys(room.chat.$groupClarify.get())).toHaveLength(0)+ })++ it('clears only the disbanded room’s mirrored questions', async () => {+ const room = await loadRoom()++ room.turns.syncGroupClarify('Core', { name: 'research' }, { pending_clarify: CLARIFY })+ room.turns.syncGroupClarify('Other', { name: 'ops' }, { pending_clarify: { ...CLARIFY, request_id: 'req-2' } })+ room.turns.clearGroupClarify('Core')++ const remaining = Object.values(room.chat.$groupClarify.get())++ expect(remaining).toHaveLength(1)+ expect(remaining[0].group).toBe('Other')+ })++ it('holds the turn open on a command approval too', async () => {+ const room = await loadRoom({+ approvalUntil: { research: { payload: APPROVAL, until: 3 } },+ turn: () => 'build cleaned'+ })++ const thread = room.rounds.sendToGroupChat(+ 'Core',+ [{ name: 'research', title: '' }],+ '@research clean up',+ null,+ []+ )++ await drain(() => Boolean(room.chat.$groupChats.get().Core?.running))++ const replies = log(room, 'Core').filter(entry => entry.thread === thread && entry.from.kind === 'member')++ expect(replies).toHaveLength(1)+ expect(replies[0].text).toBe('build cleaned')+ expect(Object.keys(room.chat.$groupClarify.get())).toHaveLength(0)+ expect(room.chat.$groupNeedsYou.get().Core).toBe(true)+ })++ it('mirrors an approval with its kind, command and server choices', async () => {+ const { chat, turns } = await loadRoom()++ expect(+ turns.syncGroupClarify(+ 'Core',+ { name: 'research', title: '' },+ {+ pending_approval: APPROVAL,+ session_id: 'rt-research-1'+ }+ )+ ).toBe(true)++ const entry = Object.values(chat.$groupClarify.get())[0]++ expect(entry.kind).toBe('approval')+ expect(entry.command).toBe('rm -rf ./build')+ expect(entry.question).toBe('Clean the build directory')+ expect(entry.choices).toEqual(['once', 'session', 'deny'])+ expect(entry.sessionId).toBe('rt-research-1')+ })++ it('falls back to once/deny when the server sends no choice set', async () => {+ const { chat, turns } = await loadRoom()++ turns.syncGroupClarify('Core', { name: 'research' }, { pending_approval: { command: 'ls', request_id: 'req-a2' } })++ expect(Object.values(chat.$groupClarify.get())[0].choices).toEqual(['once', 'deny'])+ })++ it('routes approvals through approval.respond with the session and choice', async () => {+ const room = await loadRoom()+ const member: GroupMember = { name: 'research', title: '' }++ room.turns.syncGroupClarify('Core', member, { pending_approval: APPROVAL, session_id: 'rt-research-1' })+ await room.turns.answerGroupClarify(Object.values(room.chat.$groupClarify.get())[0], member, 'once')++ expect(room.gateway.rpcFor('approval.respond').map(call => call.params)).toEqual([+ { choice: 'once', request_id: 'req-approval-1', session_id: 'rt-research-1' }+ ])+ expect(room.gateway.rpcFor('clarify.respond')).toHaveLength(0)+ expect(Object.keys(room.chat.$groupClarify.get())).toHaveLength(0)+ })++ it('lets clarify outrank approval when a snapshot carries both', async () => {+ const { chat, turns } = await loadRoom()++ turns.syncGroupClarify('Core', { name: 'research' }, { pending_approval: APPROVAL, pending_clarify: CLARIFY })++ const entry = Object.values(chat.$groupClarify.get())[0]++ expect(entry.kind).toBe('clarify')+ expect(entry.requestId).toBe('req-clarify-1')+ })+})++// A turn that outlives its deadline leaves a "stranded" marker. The member is+// still working; the next round harvests whatever landed instead of throwing+// the finished work away.+describe('stranded harvest', () => {+ const seedSession = (room: Room, stored: string, profile: string, title: string, messages: string[][]) => {+ room.gateway.sessions.set(stored, {+ messages: messages.map(([role, content]) => ({ content, role })),+ profile,+ runtime: `rt-${profile}`,+ stored,+ title+ })+ }++ it('posts a late reply into the room and clears the marker', async () => {+ const room = await loadRoom()++ room.chat.updateGroupChat('Late', current => {+ current.sessions = { research: 'sid-research' }+ current.stranded = { research: 0 }++ return current+ })+ // The member's session finished after we stopped waiting.+ seedSession(room, 'sid-research', 'research', 'Group: Late', [+ ['user', 'the turn prompt'],+ ['assistant', 'Here is the full research result, delivered late.']+ ])++ await room.turns.harvestStrandedGroupReply('Late', { name: 'research', title: '' })++ expect(log(room, 'Late')).toHaveLength(1)+ expect(log(room, 'Late')[0].from.name).toBe('research')+ expect(log(room, 'Late')[0].text).toMatch(/delivered late/)+ expect(room.chat.$groupChats.get().Late.stranded?.research).toBeUndefined()+ })++ it('prefers the substantive answer over a trailing synthetic (pass)', async () => {+ const room = await loadRoom()++ // #94376 class bug at the second call site: the late-landing turn ends+ // with a Codex intent-ack continuation nudge that gets a synthetic+ // "(pass)" — the harvest must still surface the substantive answer.+ room.chat.updateGroupChat('Rescue', current => {+ current.sessions = { research: 'sid-research' }+ current.stranded = { research: 0 }++ return current+ })+ seedSession(room, 'sid-research', 'research', 'Group: Rescue', [+ ['user', 'the turn prompt'],+ ['assistant', 'Here is the full research result, delivered late.'],+ [+ 'user',+ '[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.]'+ ],+ ['assistant', '(pass)']+ ])++ await room.turns.harvestStrandedGroupReply('Rescue', { name: 'research', title: '' })++ expect(log(room, 'Rescue')).toHaveLength(1)+ expect(log(room, 'Rescue')[0].text).toMatch(/delivered late/)+ expect(room.chat.$groupChats.get().Rescue.stranded?.research).toBeUndefined()+ })++ it('consumes the marker without posting when the late reply is a pass', async () => {+ const room = await loadRoom()++ room.chat.updateGroupChat('Quiet2', current => {+ current.sessions = { builder: 'sid-builder' }+ current.stranded = { builder: 2 }++ return current+ })+ seedSession(room, 'sid-builder', 'builder', 'Group: Quiet2', [+ ['user', 'p1'],+ ['user', 'prompt'],+ ['assistant', '(pass)']+ ])++ await room.turns.harvestStrandedGroupReply('Quiet2', { name: 'builder', title: '' })++ expect(log(room, 'Quiet2')).toHaveLength(0)+ expect(room.chat.$groupChats.get().Quiet2.stranded?.builder).toBeUndefined()+ })++ it('never re-submits into a member the harvest just confirmed is still running', async () => {+ // research is confirmed busy on exactly its first two session.resume calls+ // — the number of harvest-only touches the FIXED code makes across two+ // rounds. Without the responder guard research gets re-selected and picks+ // up two EXTRA resume calls of its own before its first post-resubmit+ // poll, which then reports done — so the unguarded run still finishes fast+ // while proving the resubmission happened.+ const room = await loadRoom({+ busyResumes: { research: 2 },+ turn: ({ profile }) => (profile === 'builder' ? 'builder here, all good' : '(pass)')+ })++ // The marker's pre-thread bare-number shape is still supported: presence+ // in `stranded` is what the round-loop guard checks, not the value shape.+ room.gateway.sessions.set('sid-research', {+ messages: [],+ profile: 'research',+ runtime: 'rt-research',+ stored: 'sid-research',+ title: 'Group: Grind'+ })+ room.chat.updateGroupChat('Grind', current => {+ current.log = [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'u1', text: '@research @builder status?' }]+ current.sessions = { research: 'sid-research' }+ current.stranded = { research: 0 }+ current.watermarks = { 'legacy::builder': 0, 'legacy::research': 0 }++ return current+ })++ await room.rounds.runGroupChatRounds(+ 'Grind',+ [+ { name: 'research', title: '' },+ { name: 'builder', title: '' }+ ],+ 'legacy'+ )++ expect(room.gateway.calls.filter(call => call.profile === 'research')).toHaveLength(0)+ // The marker survives untouched — the harvest confirmed research is still+ // running, so there is nothing to consume yet.+ expect(room.chat.$groupChats.get().Grind.stranded?.research).toBe(0)+ expect(room.gateway.calls.filter(call => call.profile === 'builder')).toHaveLength(1)+ })+})++describe('room record', () => {+ it('persists the roomId alongside the room and survives another room’s disband', async () => {+ const room = await loadRoom()++ room.chat.updateGroupChat('Keep', current => {+ current.log = [{ at: 1, from: { kind: 'user', name: 'You' }, id: 'k1', text: 'hi' }]+ current.roomId = 'r-keep'++ return current+ })+ room.chat.updateGroupChat('Gone', current => {+ current.roomId = 'r-gone'++ return current+ })++ const rooms = { ...room.chat.$groupChats.get() }+ delete rooms.Gone+ room.chat.$groupChats.set(rooms)+ await room.chat.persistGroupChatRooms(rooms)++ const durable = (room.gateway.storage.get('group-chats') || {}) as Record<string, GroupChat>++ expect(durable.Keep.roomId).toBe('r-keep')+ expect('Gone' in durable).toBe(false)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/hidden-bots.test.ts b/apps/desktop/src/plugins/hermes-bots/hidden-bots.test.tsnew file mode 100644index 00000000000..5ddfae7fb13--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/hidden-bots.test.ts@@ -0,0 +1,232 @@+/**+ * Per-bot Hide/Unhide.+ *+ * Right-click → Hide Bot persists `hidden: true` in bot meta (local+ * ctx.storage AND server ui_meta via saveBotMeta), hidden bots drop out of the+ * roster list, and a header eye toggle — rendered only while at least one bot+ * is hidden — reveals them dimmed for right-click → Unhide.+ *+ * Hiding is a roster-DISPLAY concern only: the bot keeps working, stays+ * mentionable, keeps its group membership, and any open chat stays open. The+ * one behavioral consequence is quiet: a hidden bot still accumulates unread,+ * it just never toasts.+ *+ * Ported from tests/hide-bots.test.mjs, which ran the whole plugin.js bundle+ * under `vm`.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import type { RosterRow } from './types'++const { markSessionUnreadFinished, notify, request } = vi.hoisted(() => ({+ markSessionUnreadFinished: vi.fn(),+ notify: vi.fn(),+ request: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()++ return {+ ...sdk,+ ackStoredSessionId: vi.fn(),+ host: { ...sdk.host, notify, request },+ markSessionUnreadFinished+ }+})++/** Every ctx.storage write the module graph made, oldest first. */+interface StorageWrite {+ key: string+ value: Record<string, { hidden?: boolean; title?: string }>+}++/** Bot Mode keeps roster/meta/watermark state in module-level atoms, so each+ * test gets a fresh graph rather than unwinding the previous one's writes. */+async function loadModules() {+ vi.resetModules()++ const writes: StorageWrite[] = []++ const [botState, data, hiddenBots, profileOps, rosterActions, shared] = await Promise.all([+ import('./bot-state'),+ import('./data'),+ import('./hidden-bots'),+ import('./profile-ops'),+ import('./roster-actions'),+ import('./shared')+ ])++ shared.setPluginCtx({+ storage: {+ get: () => null,+ remove: () => undefined,+ set: (key: string, value: unknown) => {+ writes.push({ key, value } as StorageWrite)+ }+ }+ } as unknown as Parameters<typeof shared.setPluginCtx>[0])++ return { botState, data, hiddenBots, profileOps, rosterActions, writes }+}++// Pay the graph's cold transform once, up front. `loadModules` re-imports on+// every test, and charging that one-time cost to whichever test happens to run+// first makes it time out under a loaded runner.+beforeAll(async () => {+ await loadModules()+}, 60_000)++beforeEach(() => {+ vi.clearAllMocks()+ request.mockResolvedValue({ applied: { ui_meta: true } })+})++describe('hiding persists locally and cross-machine', () => {+ it('writes hidden:true to storage and ships it in the server ui_meta', async () => {+ const { data, writes } = await loadModules()++ await data.saveBotMeta('default', { hidden: true })++ expect(data.$botMeta.get().default.hidden).toBe(true)+ expect(writes.at(-1)?.key).toBe('bot-meta')+ expect(writes.at(-1)?.value.default.hidden).toBe(true)++ const configure = request.mock.calls.find(([method]) => method === 'profiles.configure')++ expect(configure?.[1].ui_meta['hermes-bots'].hidden).toBe(true)+ })++ it('clears the flag on unhide, and the server false beats a stale local true', async () => {+ const { data, profileOps } = await loadModules()++ data.$botMeta.set({ ghost: { hidden: true, title: 'Ghost' } })+ await data.saveBotMeta('ghost', { hidden: false })++ expect(data.$botMeta.get().ghost.hidden).toBe(false)++ const configure = request.mock.calls.find(([method]) => method === 'profiles.configure')++ // The server copy carries the literal false, not an omission.+ expect(configure?.[1].ui_meta['hermes-bots'].hidden).toBe(false)++ // Machine B: its stale local copy still says hidden:true; the server+ // overlay (which merges OVER local) must win with the false.+ data.$botMeta.set({ ghost: { hidden: true, title: 'Ghost' } })+ profileOps.mergeServerMeta([+ { name: 'ghost', ui_meta: { 'hermes-bots': { hidden: false, title: 'Ghost' } } }+ ] as unknown as RosterRow[])++ expect(data.$botMeta.get().ghost.hidden).toBe(false)+ })++ it('lands a hide done on another machine and persists it to storage', async () => {+ const { data, profileOps, writes } = await loadModules()++ data.$botMeta.set({ ghost: { title: 'Ghost' } })+ profileOps.mergeServerMeta([+ { name: 'ghost', ui_meta: { 'hermes-bots': { hidden: true, title: 'Ghost' } } }+ ] as unknown as RosterRow[])++ expect(data.$botMeta.get().ghost.hidden).toBe(true)+ expect(writes.at(-1)?.value.ghost.hidden).toBe(true)+ })+})++describe('the roster drops hidden rows without touching their twins', () => {+ it('keeps a same-named remote-source row visible when the local one is hidden', async () => {+ const { data, hiddenBots } = await loadModules()++ data.$botMeta.set({ ghost: { hidden: true } })++ const roster = [+ { name: 'default' },+ { name: 'ghost' },+ { connectionId: 'mini', name: 'ghost', remoteSource: true }+ ] as RosterRow[]++ const meta = data.$botMeta.get()+ const visible = roster.filter(bot => !hiddenBots.isBotHidden(bot, meta))++ expect(visible.map(bot => `${bot.remoteSource ? 'r:' : ''}${bot.name}`)).toEqual(['default', 'r:ghost'])+ })+})++describe('hiding the selected bot re-homes the selection', () => {+ it('falls back to the first visible bot', async () => {+ const { botState, data, hiddenBots } = await loadModules()++ botState.$selectedBot.set('ghost')+ data.$botMeta.set({ ghost: { hidden: true } })+ data.$lastRoster.set([{ name: 'ghost' }, { name: 'scribe' }, { name: 'default' }] as RosterRow[])++ hiddenBots.fallbackSelectionAfterHide('ghost')++ expect(botState.$selectedBot.get()).toBe('scribe')+ })++ it('falls back to default when nothing else is visible', async () => {+ const { botState, data, hiddenBots } = await loadModules()++ botState.$selectedBot.set('ghost')+ data.$botMeta.set({ ghost: { hidden: true } })+ data.$lastRoster.set([{ name: 'ghost' }] as RosterRow[])++ hiddenBots.fallbackSelectionAfterHide('ghost')++ expect(botState.$selectedBot.get()).toBe('default')+ })++ it('keeps the selection when default itself is hidden and alone', async () => {+ // Routines is scoped to the selected bot — it must not chase a ghost.+ const { botState, data, hiddenBots } = await loadModules()++ botState.$selectedBot.set('default')+ data.$botMeta.set({ default: { hidden: true } })+ data.$lastRoster.set([{ name: 'default' }] as RosterRow[])++ hiddenBots.fallbackSelectionAfterHide('default')++ expect(botState.$selectedBot.get()).toBe('default')+ })++ it('never moves the selection when an unselected bot is hidden', async () => {+ const { botState, data, hiddenBots } = await loadModules()++ botState.$selectedBot.set('scribe')+ data.$botMeta.set({ ghost: { hidden: true } })+ data.$lastRoster.set([{ name: 'ghost' }, { name: 'scribe' }] as RosterRow[])++ hiddenBots.fallbackSelectionAfterHide('ghost')++ expect(botState.$selectedBot.get()).toBe('scribe')+ })+})++describe('a hidden bot stays quiet without going deaf', () => {+ it('accumulates unread but never toasts, even with toasts on', async () => {+ const { botState, data, rosterActions } = await loadModules()++ rosterActions.setActivityToasts(true)+ data.$botMeta.set({ ghost: { hidden: true } })+ botState.$selectedBot.set('default')++ const rosterAt = (at: number) =>+ [+ {+ canonical_session: { id: 'ghost-chat', last_active: at, preview: 'Message from writer: hi' },+ name: 'ghost'+ }+ ] as unknown as RosterRow[]++ rosterActions.trackInboundActivity(rosterAt(100)) // seeding poll+ rosterActions.trackInboundActivity(rosterAt(200)) // activity past the watermark++ // Unread goes straight into core's store, keyed by the same canonical id+ // the row's status dot reads.+ expect(markSessionUnreadFinished).toHaveBeenCalledWith('ghost-chat', 'ghost')+ expect(notify).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.runtime.test.ts b/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.runtime.test.tssimilarity index 98%rename from apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.runtime.test.tsrename to apps/desktop/src/plugins/hermes-bots/hide-bot-chats.runtime.test.tsindex 8cf1c13d7b7..ad474b759cd 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.runtime.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.runtime.test.ts@@ -41,7 +41,7 @@ vi.mock('@hermes/plugin-sdk', async importOriginal => {})const { createPluginContext } = await import('@/contrib/plugin')-const { default: plugin } = await import('../plugin.js')+const { default: plugin } = await import('./plugin')const flushSweep = async () => {await vi.advanceTimersByTimeAsync(0)diff --git a/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.test.ts b/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.test.tsnew file mode 100644index 00000000000..4c9dab7ff8f--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.test.ts@@ -0,0 +1,268 @@+/**+ * Bot Mode sessions are ALWAYS hidden from the global Sessions sidebar.+ *+ * Canonical Bot Chats and group-chat member sessions alike ride the core+ * generic `hidden` session flag. There is no user pref: `session.create`+ * passes `hidden: true` unconditionally (pinned in+ * canonical-chat-creation.test.ts), and this reconciliation sweep pushes rows+ * born visible under the old pref — or minted outside the plugin entirely —+ * back to hidden on load and on every reconnect.+ *+ * The sweep has two halves and runs BOTH, id-based first:+ * 1. by id — every group room's member sessions, which the plugin recorded;+ * 2. by title — each roster bot's own profile listing, which is the only+ * thing that reaches CLI-born "Agent Inbox" / extra "Bot Chat" rows AND+ * the only thing that hides a canonical Bot Chat. Canonical chats are+ * identified by NAME; no stored id pointer is consulted anywhere here.+ *+ * Ported from tests/hide-bot-chats.test.mjs, which sliced the sweep out of+ * the old plugin.js bundle and ran it under `vm`. The functions are module-+ * private, so this drives them through the scheduler the plugin actually+ * starts.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { GroupMember, ProfileRoute, RosterRow } from './types'++interface SweepRow {+ id: string+ started_at?: number+ title?: string+}++const { groupChats, hostMock, lastRoster, requestForBotMock } = vi.hoisted(() => ({+ groupChats: { value: {} as Record<string, unknown> },+ hostMock: {+ listPersistedSessions: vi.fn(),+ request: vi.fn(),+ setPersistedSessionHidden: vi.fn(),+ state: {+ gateway: { listen: vi.fn(() => () => undefined) },+ profile: { get: () => 'default' }+ }+ },+ lastRoster: { value: [] as RosterRow[] },+ requestForBotMock: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', () => ({ host: hostMock }))++vi.mock('./canonical-chat', () => ({ PROFILE_SESSION_LIST_LIMIT: 200 }))++vi.mock('./data', () => ({ $lastRoster: { get: () => lastRoster.value } }))++vi.mock('./group-chat', () => ({ $groupChats: { get: () => groupChats.value } }))++vi.mock('./group-membership', () => ({+ groupMemberKey: (member: GroupMember) =>+ member?.route?.connectionId ? `${member.route.connectionId}::${member.name}` : member?.name+}))++vi.mock('./routing', () => ({+ backendTargetProfile: (route: null | ProfileRoute, fallback: string) => route?.targetProfile || fallback,+ botConnectionRoute: (bot: RosterRow) =>+ bot?.route ||+ (bot?.remoteSource+ ? { connectionId: bot.connectionId, mode: 'remote', profile: bot.name, targetProfile: bot.name }+ : null),+ requestForBot: requestForBotMock+}))++/** Every (route, options) pair the sweep pushed through the REST setter. */+function hiddenCalls() {+ return hostMock.setPersistedSessionHidden.mock.calls as Array<+ [null | ProfileRoute, { hidden: boolean; profile: string; sessionId: string }]+ >+}++/** Start the scheduler the plugin starts and let its first pass settle. The+ * sweep is scheduled on a macrotask, then runs as an unawaited promise+ * chain — three turns is well past what its resolved awaits need. */+async function runSweep() {+ const { startHideSweepScheduler } = await import('./session-sweep')++ startHideSweepScheduler({})++ for (let turn = 0; turn < 3; turn += 1) {+ await new Promise(resolve => setTimeout(resolve, 0))+ }+}++beforeEach(() => {+ vi.resetModules()+ vi.clearAllMocks()+ // Date only: the scheduler's own setTimeout must stay real so runSweep can+ // simply wait for it. 1_000_000ms puts `Date.now() / 1000` at 1000s, which+ // is what the age fixtures below are written against.+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(1_000_000)+ groupChats.value = {}+ lastRoster.value = []+ hostMock.listPersistedSessions.mockResolvedValue({ sessions: [] })+ hostMock.setPersistedSessionHidden.mockResolvedValue(undefined)+ hostMock.request.mockResolvedValue({})+ requestForBotMock.mockResolvedValue({})+})++afterEach(() => {+ vi.useRealTimers()+})++describe('the id half: group room member sessions', () => {+ it('hides every room member session exactly once', async () => {+ groupChats.value = {+ Core: { sessions: { alpha: 'room-core-a', beta: 'room-core-b' } },+ // Duplicate id under the same key — must dedupe.+ Quiet: { sessions: { alpha: 'room-core-a' } },+ // Pre-sessions room shape.+ Legacy: {}+ }+ lastRoster.value = [{ name: 'alpha' } as RosterRow]++ await runSweep()++ expect(+ hiddenCalls()+ .map(([, options]) => options.sessionId)+ .sort()+ ).toEqual(['room-core-a', 'room-core-b'])+ expect(hiddenCalls().every(([, options]) => options.hidden)).toBe(true)+ })++ it('never consults a stored canonical pointer', async () => {+ // Canonical Bot Chats are hidden by the TITLE sweep below — they are+ // identified by name, not by pointer. The load-time reconciliation reads+ // no bot-meta chat id and issues no id-verification RPC.+ groupChats.value = { Core: { sessions: { alpha: 'room-core-a' } } }+ lastRoster.value = [{ name: 'alpha' } as RosterRow]++ await runSweep()++ expect(requestForBotMock).not.toHaveBeenCalled()+ expect(hostMock.request).not.toHaveBeenCalled()+ })++ it('routes a remote member session through its immutable persisted owner', async () => {+ const owner = {+ name: 'worker',+ route: { connectionId: 'source-a', mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' },+ sourceScoped: true+ }++ groupChats.value = {+ Core: { members: [owner], sessions: { 'source-a::worker': 'remote-room-1' } }+ }+ requestForBotMock.mockRejectedValue(new Error('gateway RPC must not be used'))++ await runSweep()++ expect(hiddenCalls()).toHaveLength(1)++ const [route, options] = hiddenCalls()[0]++ expect(route).toMatchObject({ connectionId: 'source-a', targetProfile: 'backend-worker' })+ expect(options.sessionId).toBe('remote-room-1')+ })++ it('keeps two remote owners of the same session id on their own routes', async () => {+ const owner = (connectionId: string) => ({+ name: 'worker',+ route: { connectionId, mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' },+ sourceScoped: true+ })++ groupChats.value = {+ A: { sessionOwners: { 'source-a::worker': owner('source-a') }, sessions: { 'source-a::worker': 'same-id' } },+ B: { sessionOwners: { 'source-b::worker': owner('source-b') }, sessions: { 'source-b::worker': 'same-id' } }+ }+ requestForBotMock.mockRejectedValue(new Error('gateway RPC must not be used'))++ await runSweep()++ expect(+ hiddenCalls()+ .map(([route]) => route?.connectionId)+ .sort()+ ).toEqual(['source-a', 'source-b'])+ expect(hiddenCalls().every(([, options]) => options.sessionId === 'same-id')).toBe(true)+ })++ it('fails closed on a source-qualified session whose persisted owner is malformed', async () => {+ // A source-qualified key without its immutable owner must never fall+ // through to ambient routing — that hides whichever session happens to+ // carry that id on the active connection.+ groupChats.value = {+ LegacyRemote: {+ sessionOwners: { 'source-a::worker': { name: 'worker' } },+ sessions: { 'source-a::worker': 'same-id' }+ }+ }+ lastRoster.value = [{ name: 'worker' } as RosterRow]++ await runSweep()++ expect(hiddenCalls()).toHaveLength(0)+ expect(requestForBotMock).not.toHaveBeenCalled()+ })+})++describe('the title half: each roster bot’s own profile listing', () => {+ const rowsByProfile: Record<string, SweepRow[]> = {+ alpha: [+ { id: 'a-1', started_at: 1, title: 'Bot Chat' },+ { id: 'a-2', started_at: 1, title: 'Agent Inbox' },+ { id: 'a-3', started_at: 1, title: 'Group: Core' },+ { id: 'a-4', started_at: 1, title: 'My real conversation' },+ // Not an exact title — kept.+ { id: 'a-5', started_at: 1, title: 'Bot Chat notes' },+ // Live draft inside the grace period — kept.+ { id: 'a-6', started_at: 701, title: 'Bot Chat' },+ // Missing age metadata — kept, fail closed.+ { id: 'a-7', title: 'Agent Inbox' },+ // Grace boundary reached — hidden.+ { id: 'a-8', started_at: 700, title: 'Bot Chat' }+ ],+ remy: [{ id: 'r-1', started_at: 1, title: 'Agent Inbox' }]+ }++ beforeEach(() => {+ lastRoster.value = [{ name: 'alpha' }, { connectionId: 'mini', name: 'remy', remoteSource: true }] as RosterRow[]+ hostMock.listPersistedSessions.mockImplementation(async (_route: unknown, options: { profile: string }) => ({+ sessions: rowsByProfile[options.profile] || []+ }))+ })++ it('hides Bot-Mode plumbing titles per roster bot, and only those', async () => {+ await runSweep()++ const lists = hostMock.listPersistedSessions.mock.calls as Array<+ [null | ProfileRoute, { include_hidden?: boolean; profile: string }]+ >++ expect(lists.map(([, options]) => options.profile).sort()).toEqual(['alpha', 'remy'])+ // Visible-rows-only listing keeps the sweep idempotent.+ expect(lists.every(([, options]) => !options.include_hidden)).toBe(true)++ // Exact plumbing titles only — user-titled and brand-new rows stay visible.+ expect(+ hiddenCalls()+ .map(([, options]) => options.sessionId)+ .sort()+ ).toEqual(['a-1', 'a-2', 'a-3', 'a-8', 'r-1'])+ expect(hiddenCalls().every(([, options]) => options.hidden)).toBe(true)+ // Remote-source rows keep their immutable source owner on the REST route.+ expect(hiddenCalls().find(([, options]) => options.sessionId === 'r-1')?.[0]?.connectionId).toBe('mini')+ })++ it('runs beside the id half, and a throwing title sweep never breaks it', async () => {+ // The load/reconnect entrypoint runs BOTH halves; the title sweep is+ // best-effort, so an unreachable source must not cost the known ids.+ groupChats.value = { Core: { sessions: { alpha: 'room-core-a' } } }+ hostMock.listPersistedSessions.mockRejectedValue(new Error('gateway not ready'))++ await runSweep()++ expect(hiddenCalls().map(([, options]) => options.sessionId)).toEqual(['room-core-a'])+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/hygiene.test.ts b/apps/desktop/src/plugins/hermes-bots/hygiene.test.tsnew file mode 100644index 00000000000..4da3bc30aa5--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/hygiene.test.ts@@ -0,0 +1,205 @@+import { describe, expect, it, vi } from 'vitest'++import type * as data from './data'+import type * as groupChat from './group-chat'+import { createGroupGateway, scriptedStorage } from './group-test-utils'+import type * as hygiene from './hygiene'+import type { GroupChat, GroupMember, RosterRow } from './types'++// #93492 root fix: deleting a connection sweeps/annotates the persisted+// group-chat member rows that referenced it (registry 'removed' push), and a+// hydrate-time pass annotates rows orphaned before the sweep existed. Rows are+// marked (sourceMissing → the existing 'Gateway removed' degraded state),+// never silently deleted — the poisoned row lives in plugin storage, so a hard+// delete would take the user's membership with it.++const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))++vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')++ return pluginSdkMock(host)+})++interface Rooms {+ chat: typeof groupChat+ data: typeof data+ hygiene: typeof hygiene+ writes: Map<string, unknown>+}++async function load(): Promise<Rooms> {+ vi.resetModules()+ const gateway = createGroupGateway()++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ Object.assign(host, gateway.host)++ const [chat, data, hygiene, shared] = await Promise.all([+ import('./group-chat'),+ import('./data'),+ import('./hygiene'),+ import('./shared')+ ])++ shared.setPluginCtx(scriptedStorage(gateway.storage))++ return { chat, data, hygiene, writes: gateway.storage }+}++function member(overrides: Partial<GroupMember> = {}): GroupMember {+ return {+ connectionId: 'conn-gone',+ handle: 'dixie',+ name: 'dixie',+ remoteSource: true,+ route: { connectionId: 'conn-gone', mode: 'remote', profile: 'dixie', targetProfile: 'dixie' },+ sourceScoped: true,+ ...overrides+ }+}++describe('removed-connection sweep', () => {+ it('annotates matching members and persists; other rows are untouched', async () => {+ const { chat, data, writes } = await load()+ chat.$groupChats.set({+ Crew: {+ log: [{ at: 1, from: { kind: 'user', name: 'You' }, id: '1', text: 'hi' }],+ members: [+ member(),+ member({+ connectionId: 'conn-live',+ name: 'bob',+ route: { connectionId: 'conn-live', mode: 'remote', profile: 'bob', targetProfile: 'bob' }+ })+ ],+ watermarks: {}+ }+ })++ expect(chat.sweepGroupChatMembersForRemovedConnection('conn-gone')).toBe(true)++ const room = chat.$groupChats.get().Crew+ const swept = room.members?.find(row => row.name === 'dixie')+ const kept = room.members?.find(row => row.name === 'bob')++ // Annotated, not deleted: identity survives, marked degraded.+ expect(room.members).toHaveLength(2)+ expect(swept?.sourceMissing).toBe(true)+ expect(swept?.sourceReachable).toBe(false)+ expect(kept?.sourceMissing).toBeUndefined()+ // The degraded mark renders as the existing 'Gateway removed' state.+ expect(data.botSourceStatus(swept).label).toBe('Gateway removed')+ // Persisted so the fix survives restarts (the poisoned row lived in storage).+ expect(writes.has('group-chats')).toBe(true)+ })++ it('is idempotent and ignores blank ids', async () => {+ const { chat } = await load()+ chat.$groupChats.set({ Crew: { log: [], members: [member()], watermarks: {} } })++ expect(chat.sweepGroupChatMembersForRemovedConnection('')).toBe(false)+ expect(chat.sweepGroupChatMembersForRemovedConnection('conn-gone')).toBe(true)+ // Already annotated: nothing left to change.+ expect(chat.sweepGroupChatMembersForRemovedConnection('conn-gone')).toBe(false)+ })+})++describe('hydrate-time annotate', () => {+ it('marks lost-connectionId rows even without a registry', async () => {+ const { data, hygiene } = await load()++ const rooms: Record<string, GroupChat> = {+ Crew: {+ log: [],+ // The exact persisted shape from #93492: remoteSource kept, connectionId+ // NULLED. The descriptor type models it as absent, but what older builds+ // actually wrote to disk is an explicit null — that is the shape the+ // annotate pass has to recognise.+ members: [+ { connectionId: null, handle: 'halakukhan', name: 'halakukhan', remoteSource: true } as unknown as GroupMember+ ],+ watermarks: {}+ }+ }++ const { rooms: next, changed } = hygiene.annotateOrphanedGroupChatMembers(rooms, null)++ expect(changed).toBe(true)+ expect(next.Crew.members?.[0].sourceMissing).toBe(true)+ expect(data.botSourceStatus(next.Crew.members?.[0]).label).toBe('Gateway removed')+ })++ it('with a live registry, marks members on dead connections and keeps live and local ones', async () => {+ const { hygiene } = await load()++ const rooms: Record<string, GroupChat> = {+ Crew: {+ log: [],+ members: [+ member(),+ member({+ connectionId: 'conn-live',+ name: 'bob',+ route: { connectionId: 'conn-live', mode: 'remote', profile: 'bob', targetProfile: 'bob' }+ }),+ { name: 'local-pal' }+ ],+ watermarks: {}+ }+ }++ const { rooms: next, changed } = hygiene.annotateOrphanedGroupChatMembers(rooms, new Set(['conn-live']))+ const seated = (name: string) => next.Crew.members?.find(row => row.name === name)++ expect(changed).toBe(true)+ expect(seated('dixie')?.sourceMissing).toBe(true)+ expect(seated('bob')?.sourceMissing).toBeUndefined()+ expect(seated('local-pal')?.sourceMissing).toBeUndefined()+ })++ it('without a registry, touches only the unresolvable-route shape', async () => {+ const { hygiene } = await load()++ // conn-gone still has an id; without a registry we cannot prove it dead.+ const { changed } = hygiene.annotateOrphanedGroupChatMembers(+ { Crew: { log: [], members: [member()], watermarks: {} } },+ null+ )++ expect(changed).toBe(false)+ })+})++describe('render-path callers', () => {+ it('degrade on an orphaned row instead of throwing', async () => {+ const { chat } = await load()+ const [membership, routing] = await Promise.all([import('./group-membership'), import('./routing')])++ // Persisted-on-disk shape, nulled connectionId included (see above).+ const orphaned = {+ connectionId: null,+ handle: 'halakukhan',+ name: 'halakukhan',+ remoteSource: true+ } as unknown as RosterRow++ // botWorkspaceOwnerKey (sidebar sync / Bots home / context menus)+ expect(routing.botWorkspaceOwnerKey(orphaned)).toBe('bot:halakukhan')+ // setBotsWorkspaceOwner (sidebar visibility listener)+ expect(() => routing.setBotsWorkspaceOwner('bot:halakukhan', orphaned)).not.toThrow()+ // durableGroupChatMembers (every group send / roster refresh)+ expect(() => membership.durableGroupChatMembers([orphaned])).not.toThrow()++ const durable = membership.durableGroupChatMembers([+ { ...orphaned, sourceMissing: true, sourceReachable: false }+ ])[0]++ // The degraded mark survives the durable rebuild.+ expect(durable.sourceMissing).toBe(true)+ expect(chat.$groupChats.get()).toEqual({})+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/i18n-test-helper.ts b/apps/desktop/src/plugins/hermes-bots/i18n-test-helper.tsnew file mode 100644index 00000000000..34c6dd0fb99--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/i18n-test-helper.ts@@ -0,0 +1,25 @@+/**+ * Resolve a Bot Mode message key against the plugin's own `en` bundle.+ *+ * Tests that render Bot Mode components stub `usePluginI18n` with this instead+ * of registering the bundle for real: registration normally happens in+ * `ctx.register`, and the registry lives behind an app-internal module a plugin+ * (or its tests) may not import.+ */++import { BOTS_LOCALES } from './i18n'++export function translateBots(key: string, ...args: unknown[]): string {+ const value = key+ .split('.')+ .reduce<unknown>(+ (node, part) => (node && typeof node === 'object' ? (node as Record<string, unknown>)[part] : undefined),+ BOTS_LOCALES.en+ )++ if (typeof value === 'function') {+ return String((value as (...params: unknown[]) => string)(...args))+ }++ return typeof value === 'string' ? value : key+}diff --git a/apps/desktop/src/plugins/hermes-bots/legacy-sdk-compat.test.ts b/apps/desktop/src/plugins/hermes-bots/legacy-sdk-compat.test.tsnew file mode 100644index 00000000000..acbf19c8ce4--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/legacy-sdk-compat.test.ts@@ -0,0 +1,77 @@+/**+ * Bot Mode has to keep linking against an OLDER desktop SDK.+ *+ * `McpTab`, `ToolsetConfigPanel` and `SkillsView` are capability exports: the+ * shell that hosts the plugin may predate any of them. Every use site is+ * therefore guarded, and the plugin module graph must evaluate — and still+ * hand back a registrable plugin — when all three are missing. A bare+ * top-level use of one of them turns a missing export into a blank Bots pane+ * on an older build, which is exactly the failure this pins.+ */++import { describe, expect, it, vi } from 'vitest'++/** Names an older SDK is allowed not to export. */+const OPTIONAL_CAPABILITY_EXPORTS = new Set(['McpTab', 'SkillsView', 'ToolsetConfigPanel'])++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ // Everything an older SDK DOES export answers as a callable stand-in, so+ // module-level `host.state.x.get()` / `foo()` evaluation succeeds without+ // pinning the real surface.+ const stub: unknown = new Proxy(function stubbed() {}, {+ apply: () => stub,+ get: (_target, key) => {+ if (key === Symbol.iterator) {+ return function* () {}+ }++ if (key === Symbol.toPrimitive) {+ return () => 0+ }++ // Never look thenable: an awaited stub would hang the import.+ if (key === 'then' || OPTIONAL_CAPABILITY_EXPORTS.has(String(key))) {+ return undefined+ }++ return stub+ }+ })++ return new Proxy({ atom } as Record<string, unknown>, {+ get: (target, key) => {+ if (typeof key === 'symbol' || key in target) {+ return target[key as string]+ }++ // The namespace itself is awaited by the loader: a callable `then`+ // would make it look thenable and never settle.+ return key === 'then' || OPTIONAL_CAPABILITY_EXPORTS.has(key) ? undefined : stub+ },+ // The loader validates namespace access against the mock, so the+ // capability names must READ as undefined rather than be absent —+ // absent would throw where an older bundled SDK simply gives undefined.+ has: () => true+ })+})++describe('an SDK without the optional capability exports', () => {+ it('still links Bot Mode into a registrable plugin', async () => {+ const plugin = (await import('./plugin')).default++ expect(plugin.id).toBe('hermes-bots')+ expect(typeof plugin.register).toBe('function')+ })++ it('leaves the SkillsView connection-routing capability off', async () => {+ // `skillsViewRoutesConnections` gates whether a source-scoped bot may open+ // the Capabilities tab at all — with no SkillsView it must read false, not+ // throw on the missing export.+ const { SkillsView, skillsViewRoutesConnections } = await import('./profile-config')++ expect(SkillsView).toBeUndefined()+ expect(skillsViewRoutesConnections).toBe(false)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/model-picker.test.tsx b/apps/desktop/src/plugins/hermes-bots/model-picker.test.tsxnew file mode 100644index 00000000000..8c88b61688a--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/model-picker.test.tsx@@ -0,0 +1,159 @@+/**+ * #95279: the Bot Mode model picker's catalog read must always SETTLE, and it+ * must not churn the network on every surface remount.+ *+ * The read rides the BOT's own socket — a second, lazily dialed pool backend+ * that can wedge (cold pool spawn, dropped remote hop) without the primary+ * socket noticing. Two defects made the picker unusable while Bots was active:+ *+ * 1. The RPC had no deadline, so a wedged dial left it pending forever and+ * the spinner never settled ("model picker never settles").+ * 2. Every fetch forced `refresh: true`, bypassing the react-query cache, so+ * each Bots view remount (tab re-front, dialog reopen, pane visibility+ * flip) knocked the picker back into loading and discarded the staged+ * selection mid-edit.+ *+ * Pinned here through the real component: bounded settlement into the+ * free-text fallback, one cached unforced read across remounts, and no+ * dispatch at all for a row whose connection is gone.+ */++import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, waitFor } from '@testing-library/react'+import type { ReactNode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { ModelPicker } from './model-picker'+import type { RosterRow } from './types'++const { hostMock } = vi.hoisted(() => ({+ hostMock: {+ request: vi.fn(),+ requestProfile: vi.fn(),+ state: { connectionId: { get: () => 'local' }, gateway: { get: () => 'open' }, profile: { get: () => 'default' } }+ }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { useQuery } = await import('@tanstack/react-query')++ return {+ Button: (props: React.ComponentProps<'button'>) => <button {...props} />,+ GlyphSpinner: () => <span data-testid="spinner" />,+ host: hostMock,+ Input: (props: React.ComponentProps<'input'>) => <input {...props} />,+ Select: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectTrigger: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectValue: () => null,+ useQuery+ }+})++vi.mock('./shared', () => ({ ID: 'hermes-bots' }))++const remoteBot = {+ connectionId: 'remote-a',+ name: 'default',+ remoteSource: true,+ route: { connectionId: 'remote-a', mode: 'remote', profile: 'default', targetProfile: 'backend-default' },+ sourceScoped: true,+ targetProfile: 'backend-default'+} as RosterRow++/** One client per render group, so "did the remount refetch?" is a real+ * question about the cache rather than about a fresh store. */+let client: QueryClient++function mount(bot: null | RosterRow) {+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )++ return render(<ModelPicker bot={bot} onChange={vi.fn()} value={{ model: '', provider: '' }} />, { wrapper })+}++/** The fallback the picker paints when the catalog is unavailable. */+const isFreeText = (container: HTMLElement) =>+ Boolean(container.querySelector('input[placeholder*="omnirouter"]')) &&+ !container.querySelector('[data-testid="spinner"]')++beforeEach(() => {+ vi.clearAllMocks()+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+})++afterEach(() => {+ vi.useRealTimers()+})++describe('a bot gateway that never answers', () => {+ it('settles into the free-text fallback instead of spinning forever', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ hostMock.requestProfile.mockReturnValue(new Promise(() => undefined))++ const { container } = mount(remoteBot)++ expect(container.querySelector('[data-testid="spinner"]')).toBeTruthy()++ await vi.advanceTimersByTimeAsync(30_000)+ await waitFor(() => expect(isFreeText(container)).toBe(true))+ })+})++describe('the catalog read', () => {+ it('rides the bot’s own route, unforced, and survives a remount from cache', async () => {+ hostMock.requestProfile.mockResolvedValue({ providers: [{ models: ['m1'], name: 'Prov', slug: 'prov' }] })++ const first = mount(remoteBot)++ await waitFor(() => expect(hostMock.requestProfile).toHaveBeenCalledTimes(1))++ expect(hostMock.requestProfile).toHaveBeenCalledWith(remoteBot.route, 'model.options', {+ explicit_only: false,+ include_unconfigured: true+ })+ // A forced refresh here is what re-entered the loading state on every+ // remount and wiped the user's in-progress pick.+ expect(hostMock.requestProfile.mock.calls[0][2]).not.toHaveProperty('refresh')++ first.unmount()++ const second = mount(remoteBot)++ await waitFor(() => expect(second.container.querySelector('[data-testid="spinner"]')).toBeNull())+ expect(hostMock.requestProfile).toHaveBeenCalledTimes(1)+ })++ it('never dispatches for a row whose connection was removed', async () => {+ const orphan = { name: 'ghost', remoteSource: true } as RosterRow+ const { container } = mount(orphan)++ await waitFor(() => expect(isFreeText(container)).toBe(true))+ expect(hostMock.request).not.toHaveBeenCalled()+ expect(hostMock.requestProfile).not.toHaveBeenCalled()+ })++ it('reads the ambient gateway for a local bot', async () => {+ hostMock.request.mockResolvedValue({ providers: [] })++ mount({ name: 'default' } as RosterRow)++ await waitFor(() => expect(hostMock.request).toHaveBeenCalledTimes(1))+ expect(hostMock.request).toHaveBeenCalledWith('model.options', {+ explicit_only: false,+ include_unconfigured: true+ })+ })++ it('shares one cache entry between two bots on the same route', async () => {+ hostMock.requestProfile.mockResolvedValue({ providers: [{ models: ['m1'], slug: 'prov' }] })++ mount(remoteBot)+ await waitFor(() => expect(hostMock.requestProfile).toHaveBeenCalledTimes(1))++ mount({ ...remoteBot, name: 'default' } as RosterRow)+ await waitFor(() => expect(hostMock.requestProfile).toHaveBeenCalledTimes(1))+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/pet.test.tsx b/apps/desktop/src/plugins/hermes-bots/pet.test.tsxnew file mode 100644index 00000000000..f12c7f6ab3a--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/pet.test.tsx@@ -0,0 +1,147 @@+/**+ * Pet tiles: frame 0 of a petdex spritesheet, extracted once and cached.+ *+ * A "spritesheet" is the FULL animation sheet (1536×1872 webp, ~2MB, an 8×9+ * grid) — using it directly as an <img> downloads megabytes per tile and shows+ * the sheet squashed. So each sheet is fetched once, cropped to frame 0,+ * downscaled, and the resulting data URL is cached per URL.+ *+ * The regression the cache created: a FAILED fetch was left parked in the+ * cache as a resolved-null promise, so one network blip poisoned that pet for+ * the rest of the session — the tile never recovered, not even on reopen. A+ * failure must be evicted; a success must not be refetched.+ */++import { render, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const { hostMock, useQueryMock } = vi.hoisted(() => ({+ hostMock: { notify: vi.fn(), request: vi.fn() },+ useQueryMock: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', () => ({+ Button: (props: React.ComponentProps<'button'>) => <button {...props} />,+ cn: (...parts: unknown[]) => parts.filter(Boolean).join(' '),+ GlyphSpinner: () => <span />,+ host: hostMock,+ Input: (props: React.ComponentProps<'input'>) => <input {...props} />,+ RowButton: (props: React.ComponentProps<'button'>) => <button {...props} />,+ useQuery: useQueryMock+}))++vi.mock('./i18n', () => ({+ useBots: () => ({+ avatar: { petLoadFailed: 'Could not load that pet.', pickPet: 'Pick a pet', removeBackToShape: 'Remove' }+ })+}))++vi.mock('./shared', () => ({ ID: 'hermes-bots' }))++const SHEET = 'https://pets.example/a.webp'++/** Record every fetch so the cache behaviour is observable. */+const fetches: Array<{ init?: RequestInit; url: string }> = []++function stubFetch(handler: () => Promise<unknown>) {+ vi.stubGlobal('fetch', async (url: string, init?: RequestInit) => {+ fetches.push({ init, url })++ return handler()+ })+}++async function loadPetTab() {+ vi.resetModules()++ return (await import('./pet')).PetTab+}++beforeEach(() => {+ vi.clearAllMocks()+ fetches.length = 0+ useQueryMock.mockReturnValue({ data: { pets: [{ displayName: 'Axolotl', slug: 'axolotl', spritesheetUrl: SHEET }] } })+ vi.stubGlobal('createImageBitmap', async () => ({ close: () => undefined }))+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({+ drawImage: () => undefined+ } as unknown as CanvasRenderingContext2D)+ vi.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockReturnValue('data:image/png;base64,ok')+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('the sprite-frame cache', () => {+ it('never leaves a failed fetch parked in the cache', async () => {+ stubFetch(async () => {+ throw new Error('network')+ })++ const PetTab = await loadPetTab()+ const first = render(<PetTab image={null} onImage={vi.fn()} />)++ await waitFor(() => expect(fetches).toHaveLength(1))+ // The fetch is abortable: a hung sheet must not hold a slot forever.+ expect(fetches[0].init?.signal).toBeTruthy()++ first.unmount()++ const second = render(<PetTab image={null} onImage={vi.fn()} />)++ // Reopening retries rather than serving the poisoned null.+ await waitFor(() => expect(fetches).toHaveLength(2))+ expect(second.container.querySelector('img')).toBeNull()+ })++ it('fetches a successful sheet once and reuses the extracted frame', async () => {+ stubFetch(async () => ({ blob: async () => new Blob() }))++ const PetTab = await loadPetTab()+ const first = render(<PetTab image={null} onImage={vi.fn()} />)++ await waitFor(() =>+ expect(first.container.querySelector('img')?.getAttribute('src')).toBe('data:image/png;base64,ok')+ )+ expect(fetches).toHaveLength(1)++ first.unmount()++ const second = render(<PetTab image={null} onImage={vi.fn()} />)++ await waitFor(() =>+ expect(second.container.querySelector('img')?.getAttribute('src')).toBe('data:image/png;base64,ok')+ )+ expect(fetches).toHaveLength(1)+ })++ it('shares one fetch between tiles that point at the same sheet', async () => {+ useQueryMock.mockReturnValue({+ data: {+ pets: [+ { displayName: 'Axolotl', slug: 'axolotl', spritesheetUrl: SHEET },+ { displayName: 'Axolotl (shiny)', slug: 'axolotl-shiny', spritesheetUrl: SHEET }+ ]+ }+ })+ stubFetch(async () => ({ blob: async () => new Blob() }))++ const PetTab = await loadPetTab()+ const { container } = render(<PetTab image={null} onImage={vi.fn()} />)++ await waitFor(() => expect(container.querySelectorAll('img')).toHaveLength(2))+ expect(fetches).toHaveLength(1)+ })++ it('does not fetch for a pet with no spritesheet', async () => {+ useQueryMock.mockReturnValue({ data: { pets: [{ displayName: 'Ghost', slug: 'ghost', spritesheetUrl: null }] } })+ stubFetch(async () => ({ blob: async () => new Blob() }))++ const PetTab = await loadPetTab()+ const { findByText } = render(<PetTab image={null} onImage={vi.fn()} />)++ await findByText('Ghost')+ expect(fetches).toHaveLength(0)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/plugin-panes.test.tsx b/apps/desktop/src/plugins/hermes-bots/plugin-panes.test.tsxnew file mode 100644index 00000000000..38fd1a883a5--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/plugin-panes.test.tsx@@ -0,0 +1,283 @@+/**+ * Bot Mode's pane layout contract, asserted by running the real `register()`+ * against a recording plugin context:+ *+ * - the Bots pane center-stacks into the sessions zone (a SESSIONS | BOTS tab+ * strip), never splits below it, and carries the ENFORCED dock invariant so+ * every boot re-homes a stacked install. No heal token, no user-placed+ * exemption — the retired one-shot heal burned its token even when its+ * guards skipped the move, so exactly the users who had dragged their panes+ * stayed stacked forever;+ * - the Scheduled jobs (internally `routines`) pane only exists while a BOT+ * CHAT owns the main workspace and the Bots pane is on screen. It is+ * registered and unregistered through the contribution disposer, driven by+ * the feature-detected `host.paneVisibility` export, with the+ * always-registered fallback kept for older desktops. Cron jobs are+ * bot-scoped, so the tile must not sit beside a group chat.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import type { PluginContext } from '@hermes/plugin-sdk'+import { atom } from 'nanostores'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type * as DataModule from './data'+import type * as RoutingModule from './routing'++const mocks = vi.hoisted(() => ({+ botChatOwnsWorkspace: vi.fn(() => false),+ paneVisibility: vi.fn(),+ sessionOwnsWorkspace: vi.fn(() => false),+ setWorkspaceScope: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const original = await importOriginal<typeof HermesSdk>()++ return {+ ...original,+ host: {+ ...original.host,+ onEvent: undefined,+ paneVisibility: mocks.paneVisibility,+ setWorkspaceScope: mocks.setWorkspaceScope+ }+ }+})++// Everything below is a boundary this test does not exercise: clocks, sockets,+// storage sweeps and the panes' own render trees.+vi.mock('./avatar', () => ({ startFaceClock: vi.fn(), stopFaceClock: vi.fn() }))+vi.mock('./relay', () => ({ startBotRelay: vi.fn(), stopBotRelay: vi.fn() }))+vi.mock('./session-sweep', () => ({ startHideSweepScheduler: vi.fn() }))+vi.mock('./canonical-chat', () => ({ openBotCanonicalChat: vi.fn() }))+vi.mock('./chat-empty', () => ({ BotChatEmpty: () => null }))+vi.mock('./hygiene', () => ({ annotateOrphanedGroupChatMembers: () => ({ changed: false, rooms: {} }) }))+vi.mock('./cron', () => ({ bindProfileSync: () => () => undefined, RoutinesPane: () => null }))+vi.mock('./roster-pane', () => ({+ botChatOwnsWorkspace: mocks.botChatOwnsWorkspace,+ BotsPane: () => null,+ releaseStaleOpenBotChat: vi.fn(),+ selectedRosterBot: () => null,+ sessionOwnsWorkspace: mocks.sessionOwnsWorkspace+}))+vi.mock('./group-chat', async () => {+ const { atom: nanoAtom } = await import('nanostores')++ return {+ $groupChats: nanoAtom({}),+ $groupChatWorkspace: nanoAtom(null),+ assignLegacyThreads: (log: unknown[]) => log,+ handleSessionsGatewayTransition: vi.fn(),+ pullGroupChatServerState: async () => false,+ scheduleGroupChatServerSync: vi.fn(),+ setGroupChatSyncDisposed: vi.fn(),+ stopGroupChatServerSync: vi.fn(),+ sweepGroupChatMembersForRemovedConnection: vi.fn(),+ updateGroupChat: vi.fn()+ }+})+vi.mock('./data', async importOriginal => {+ const original = await importOriginal<typeof DataModule>()++ return { ...original, migrateBotMeta: async () => undefined }+})+vi.mock('./routing', async importOriginal => {+ const original = await importOriginal<typeof RoutingModule>()++ return { ...original, setBotsWorkspaceOwner: vi.fn() }+})++const plugin = (await import('./plugin')).default++interface Registration {+ area: string+ data?: Record<string, unknown>+ id: string+}++/** A recording `PluginContext`: registrations, their disposers, teardown. */+function recordingContext() {+ const disposers: (() => void)[] = []+ const registrations: Registration[] = []+ const unregisters = new Map<string, () => void>()++ const ctx = {+ i18n: { register: () => () => undefined, t: (key: string) => key },+ onDispose: (fn: () => void) => disposers.push(fn),+ register: (registration: Registration) => {+ registrations.push(registration)++ const unregister = vi.fn(() => {+ registrations.splice(registrations.indexOf(registration), 1)+ })++ unregisters.set(registration.id, unregister)++ return unregister+ },+ storage: { get: async () => undefined, set: async () => undefined }+ }++ return {+ ctx: ctx as unknown as PluginContext,+ dispose: () => disposers.forEach(fn => fn()),+ find: (id: string) => registrations.find(registration => registration.id === id),+ unregisters+ }+}++/** Nanostore stand-ins for the SDK's per-pane visibility stores. */+function paneStores() {+ const stores = new Map<string, ReturnType<typeof atom<boolean>>>()++ mocks.paneVisibility.mockImplementation((id: string) => {+ if (!stores.has(id)) {+ stores.set(id, atom(false))+ }++ return stores.get(id)+ })++ return (id: string) => {+ mocks.paneVisibility(id)++ return stores.get(id)!+ }+}++/** The plugin defers one reconcile to a macrotask so it never re-enters the+ * tree store mid-mutation. */+const settle = () => new Promise(resolve => setTimeout(resolve, 0))++beforeEach(() => {+ vi.clearAllMocks()+ mocks.botChatOwnsWorkspace.mockReturnValue(false)+ mocks.sessionOwnsWorkspace.mockReturnValue(false)+})++afterEach(() => {+ vi.useRealTimers()+})++describe('the Bots pane dock', () => {+ it('center-stacks into the sessions zone as a standing invariant', () => {+ paneStores()++ const harness = recordingContext()++ plugin.register(harness.ctx)++ const data = harness.find('pane')!.data!++ expect(data.dock).toEqual({ enforce: true, pane: 'sessions', pos: 'center' })+ // A 'bottom' split was the old workaround for the lone-pane auto-hide trap.+ expect((data.dock as { pos: string }).pos).not.toBe('bottom')+ // No heal token: the invariant runs at every adoption, unconditionally.+ expect(data).not.toHaveProperty('heal')++ harness.dispose()+ })+})++describe('the Scheduled jobs pane', () => {+ it('stays unregistered until a bot chat owns the workspace', async () => {+ const store = paneStores()+ const harness = recordingContext()++ plugin.register(harness.ctx)+ await settle()++ expect(harness.find('routines')).toBeUndefined()++ mocks.botChatOwnsWorkspace.mockReturnValue(true)+ store(`hermes-bots:pane`).set(true)++ const routines = harness.find('routines')!++ expect(routines.data).toMatchObject({+ // Repairs persisted layouts that stranded the tile in the Bots tab strip.+ dock: { enforce: true, pane: 'workspace', pos: 'right' },+ placement: 'main'+ })+ // Glanceable, not something you sit in: it arrives as the right edge's+ // vertical tab and takes no width off the chat until the user opens it.+ expect(routines.data!.defaultCollapsed).toBe(true)++ harness.dispose()+ })++ it('unregisters when Bot Mode leaves the screen', async () => {+ const store = paneStores()+ const harness = recordingContext()++ mocks.botChatOwnsWorkspace.mockReturnValue(true)+ plugin.register(harness.ctx)+ await settle()++ expect(harness.find('routines')).toBeTruthy()++ mocks.botChatOwnsWorkspace.mockReturnValue(false)+ store(`hermes-bots:pane`).set(true)+ store(`hermes-bots:pane`).set(false)++ expect(harness.unregisters.get('routines')).toHaveBeenCalled()+ expect(harness.find('routines')).toBeUndefined()++ harness.dispose()+ })++ it('keeps the tile alive while the tile itself holds focus', async () => {+ const store = paneStores()+ const harness = recordingContext()++ mocks.botChatOwnsWorkspace.mockReturnValue(true)+ plugin.register(harness.ctx)+ await settle()++ // Clicking the tile drops bot-chat workspace ownership for a beat. A pane+ // must never unregister itself out from under its own click.+ store(`hermes-bots:routines`).set(true)+ mocks.botChatOwnsWorkspace.mockReturnValue(false)+ store(`hermes-bots:pane`).set(true)++ expect(harness.unregisters.get('routines')).not.toHaveBeenCalled()+ expect(harness.find('routines')).toBeTruthy()++ harness.dispose()+ })++ it('stops every lifecycle listener when the plugin is disabled', async () => {+ const store = paneStores()+ const harness = recordingContext()++ plugin.register(harness.ctx)+ await settle()+ harness.dispose()++ // A disable → re-enable cycle used to stack a duplicate listener per cycle.+ mocks.botChatOwnsWorkspace.mockReturnValue(true)+ store(`hermes-bots:pane`).set(true)++ expect(harness.find('routines')).toBeUndefined()+ })+})++describe('a desktop without host.paneVisibility', () => {+ it('keeps the always-registered pane', async () => {+ const { host } = await import('@hermes/plugin-sdk')+ const restore = host.paneVisibility++ // @ts-expect-error modelling an older SDK that lacks the export entirely+ host.paneVisibility = undefined++ const harness = recordingContext()++ plugin.register(harness.ctx)++ expect(harness.find('routines')).toBeTruthy()++ harness.dispose()+ host.paneVisibility = restore+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.mentions.test.ts b/apps/desktop/src/plugins/hermes-bots/plugin.mentions.test.tsnew file mode 100644index 00000000000..1844349c38e--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/plugin.mentions.test.ts@@ -0,0 +1,323 @@+/**+ * The two composer contributions Bot Mode registers, driven through the real+ * `plugin.register()`: @-mention completions and the mention middleware.+ *+ * Both read the roster IMPERATIVELY (a popover must answer per keystroke, and+ * the middleware runs on submit), so both go through the query cache rather+ * than the hook. `useRoster` keys its query on `[...ROSTER_KEY, connectionId]`+ * — one entry per connection the window has been on — and these readers used+ * to call `getQueryData(ROSTER_KEY)` with the BARE key. That is an exact-key+ * match in TanStack Query, so it matched NOTHING: completions offered no+ * roster handles, and a remote `@name-device` mention passed through the+ * middleware unhandled (the local `profiles.list` fallback only knows bare+ * local names). Reproduced on a two-source install where the same profile+ * name exists locally and on an SSH connection ("Vera"): typing+ * `@default-vera` did nothing.+ *+ * The middleware is IDENTIFICATION-ONLY by design. It annotates who a tag+ * resolves to and hands the agent a `message_agent` target; the renderer+ * composes no CLI handoff and delivers nothing itself.+ */++import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++interface MentionCompletionItem {+ display: string+ insert: string+ meta: string+}++interface ComposerDraft {+ text: string+}++interface Contribution {+ area: string+ data: {+ handler?: (draft: ComposerDraft) => Promise<ComposerDraft>+ provide?: (query: string) => MentionCompletionItem[]+ }+ id: string+}++/** One profile name on two sources: locally and on the SSH connection "vera".+ * The union roster disambiguates the remote row as @default-vera. */+const ROSTER = {+ profiles: [+ { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', name: 'default' },+ {+ connectionId: 'vera',+ connectionKind: 'ssh',+ connectionLabel: 'Vera',+ handle: 'default-vera',+ name: 'default',+ remoteSource: true,+ sourceScoped: true+ }+ ]+}++const { cache, hostMock, live } = vi.hoisted(() => {+ const live = { focused: 'default', profile: 'default' }++ return {+ cache: new Map<string, { key: unknown[]; value: unknown }>(),+ hostMock: {+ notify: vi.fn(),+ request: vi.fn(async () => ({})),+ requestProfile: vi.fn(async () => ({})),+ state: {+ connectionId: { get: () => 'local', listen: () => () => undefined },+ focusedSessionProfile: { get: () => live.focused, listen: () => () => undefined },+ focusedStoredSessionId: { get: () => null, listen: () => () => undefined },+ gateway: { get: () => null, listen: () => () => undefined },+ profile: { get: () => live.profile, listen: () => () => undefined }+ }+ },+ live+ }+})++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ const stub: unknown = new Proxy(function stubbed() {}, {+ apply: () => stub,+ get: (_target, key) => (key === 'then' ? undefined : stub)+ })++ // A faithful-enough TanStack Query v5 cache: getQueryData matches ONLY the+ // exact key; getQueriesData prefix-matches a key family.+ const keyOf = (key: unknown[]) => JSON.stringify(key)++ const queryClient = {+ getQueriesData: ({ queryKey }: { queryKey: unknown[] }) =>+ [...cache.values()]+ .filter(entry => queryKey.every((part, index) => entry.key[index] === part))+ .map(entry => [entry.key, entry.value]),+ getQueryData: (key: unknown[]) => cache.get(keyOf(key))?.value,+ invalidateQueries: () => undefined,+ setQueryData: (key: unknown[], value: unknown) => cache.set(keyOf(key), { key, value })+ }++ const known: Record<string, unknown> = {+ atom,+ COMPOSER_AREAS: { atCompletions: 'composer.atCompletions', middleware: 'composer.middleware' },+ host: hostMock,+ PALETTE_AREA: 'palette',+ queryClient+ }++ return new Proxy(known, {+ get: (target, key) =>+ typeof key === 'symbol' || key in target ? target[key as string] : key === 'then' ? undefined : stub,+ has: () => true+ })+})++interface Fixture {+ /** Which connection id the cache entry is filed under — 'local' is the one+ * the live window would write. */+ cacheKeyConnection?: string+ /** Profile owning the chat on screen; a bot never @s itself. */+ focused?: string+ profiles?: Array<Record<string, unknown>>+}++/** Register the plugin and hand back its composer contributions. */+async function contributions({+ cacheKeyConnection = 'local',+ focused = 'default',+ profiles = ROSTER.profiles+}: Fixture = {}) {+ vi.resetModules()+ cache.clear()+ live.focused = focused+ // Exactly where useRoster writes it: suffixed with the connection id.+ cache.set(JSON.stringify(['hermes-bots', 'roster', cacheKeyConnection]), {+ key: ['hermes-bots', 'roster', cacheKeyConnection],+ value: { profiles }+ })++ const plugin = (await import('./plugin')).default+ const registered: Contribution[] = []++ try {+ plugin.register({+ i18n: { register: () => () => undefined },+ onDispose: () => undefined,+ register: (contribution: Contribution) => registered.push(contribution),+ storage: { get: async () => undefined, remove: async () => undefined, set: async () => undefined }+ } as never)+ } catch {+ // Registration walks UI surfaces the stub does not fully model; the+ // contributions registered before any throw are what these tests drive.+ }++ const completions = registered.find(entry => entry.id === 'mention-completions')+ const middleware = registered.find(entry => entry.id === 'mention-middleware')++ expect(completions?.data.provide).toBeTypeOf('function')+ expect(middleware?.data.handler).toBeTypeOf('function')++ return { handler: middleware!.data.handler!, provide: completions!.data.provide! }+}++// The plugin entry pulls in every Bot Mode surface; transforming that graph+// once costs more than a single test's budget.+beforeAll(async () => {+ await import('./plugin')+}, 120_000)++beforeEach(() => {+ vi.clearAllMocks()+ live.focused = 'default'+ live.profile = 'default'+})++describe('@-mention completions', () => {+ it('offers the remote @name-device handle from the suffixed cache entry', async () => {+ const { provide } = await contributions()++ expect(provide('').map(item => item.insert)).toContain('@default-vera')+ })++ it('still resolves when the only cached roster is under another connection id', async () => {+ // The window moved connections; the stale entry is the only one cached.+ const { provide } = await contributions({ cacheKeyConnection: 'vera' })++ expect(provide('').map(item => item.insert)).toContain('@default-vera')+ })++ it('surfaces default as @hermes and prefix-filters on the handle', async () => {+ const { provide } = await contributions({+ focused: 'researcher',+ profiles: [+ { name: 'default' },+ { name: 'researcher' },+ { connectionLabel: 'Homelab', handle: 'writer-homelab', name: 'writer' }+ ]+ })++ expect(provide('').map(item => item.insert)).toEqual(expect.arrayContaining(['@hermes', '@writer-homelab']))+ expect(provide('wri').map(item => item.insert)).toEqual(['@writer-homelab'])+ })++ it('filters self by the FOCUSED chat owner, not the gateway socket profile', async () => {+ // The socket stays on `default` while the user is inside another bot's+ // chat; the bot in front of you must not be offered as a handoff target,+ // and a renamed `default` must stay mentionable from there.+ const { provide } = await contributions({+ focused: 'renametest',+ profiles: [{ display_name: 'Lucy', name: 'default' }, { name: 'renametest' }]+ })++ const inserts = provide('').map(item => item.insert)++ expect(inserts).toContain('@lucy')+ expect(inserts).not.toContain('@renametest')+ })++ it('yields nothing, and never throws, on a cold roster cache', async () => {+ const { provide } = await contributions({ profiles: [] })++ expect(provide('')).toEqual([])+ })++ it('never offers the bot whose chat you are already in', async () => {+ const { provide } = await contributions()++ // 'default' on the LIVE connection is the active bot; only the Vera twin+ // is a real handoff target.+ expect(provide('').map(item => item.insert)).toEqual(['@default-vera'])+ })++ it('narrows on the typed prefix and labels the source device', async () => {+ const { provide } = await contributions()++ expect(provide('default-v')[0]).toMatchObject({ insert: '@default-vera', meta: expect.stringContaining('Vera') })+ expect(provide('zzz')).toEqual([])+ })+})++describe('the mention middleware', () => {+ it('identifies a remote @name-device mention without delivering anything', async () => {+ const { handler } = await contributions()+ const result = await handler({ text: '@default-vera what is the disk space on the server?' })++ expect(result.text).toMatch(/@mentions resolved from the Bot Mode roster/)+ expect(result.text).toMatch(/@default-vera/)+ // No CLI handoff is composed and the renderer performs NO delivery — the+ // agent owns messaging via its message_agent tool.+ expect(result.text).not.toMatch(/hermes -p '?default/)+ expect(hostMock.requestProfile).not.toHaveBeenCalled()+ })++ it('hands the agent the connection-qualified message_agent target', async () => {+ const { handler } = await contributions()+ const result = await handler({ text: 'ping @default-vera' })++ expect(result.text).toMatch(/message_agent target: "default-vera@vera"/)+ expect(result.text).toMatch(/on Vera/)+ })++ it('passes a draft with no mention straight through', async () => {+ const { handler } = await contributions()+ const draft = { text: 'no tags here' }++ expect(await handler(draft)).toBe(draft)+ })++ it('leaves an unresolvable tag alone rather than annotating a guess', async () => {+ const { handler } = await contributions()+ const draft = { text: 'hey @nobody' }++ expect((await handler(draft)).text).toBe('hey @nobody')+ })++ it('names a local bot without inventing a device', async () => {+ const { handler } = await contributions({ focused: 'research', profiles: [{ name: 'research' }, { name: 'ops' }] })+ const result = await handler({ text: 'please @ops review the diff' })++ expect(result.text).toMatch(/@ops = agent profile "ops"/)+ expect(result.text).toMatch(/message_agent/)+ expect(result.text).not.toMatch(/ — on /)+ })++ it('teaches no shellout and forbids forwarding the user’s text verbatim', async () => {+ // The class behind #91397 / #91304 / #91339: the renderer used to compose+ // a `hermes -p …` handoff, giving the model a second send path and a way+ // to relay the raw draft.+ const { handler } = await contributions({ focused: 'research', profiles: [{ name: 'research' }, { name: 'ops' }] })+ const result = await handler({ text: 'ask @ops to summarize' })++ expect(result.text).not.toMatch(/hermes -p/)+ expect(result.text).not.toMatch(/terminal call/i)+ expect(result.text).not.toMatch(/background=true/)+ expect(result.text).toMatch(/compose your own message/i)+ expect(result.text).toMatch(/never forward/i)+ })++ it('keeps a poisoned bot title inert prose', async () => {+ // Nothing here is a command line, so there is nothing to break out of —+ // the invariant that matters is that no hermes command is ever emitted.+ const { handler } = await contributions({+ focused: 'ops',+ profiles: [+ { name: 'ops' },+ { display_name: 'Evil" ; touch /tmp/pwned ; echo "$(touch /tmp/pwned2)"', name: 'research' }+ ]+ })++ const result = await handler({ text: 'ping @research please' })++ expect(result.text).not.toMatch(/`hermes/)+ })++ it('ignores an email address', async () => {+ const { handler } = await contributions({ focused: 'research', profiles: [{ name: 'research' }, { name: 'ops' }] })+ const untouched = 'mail [email protected] and ping @nosuchbot'++ expect((await handler({ text: untouched })).text).toBe(untouched)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/profile-config-capabilities.test.tsx b/apps/desktop/src/plugins/hermes-bots/profile-config-capabilities.test.tsxnew file mode 100644index 00000000000..d46a01dbf5d--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/profile-config-capabilities.test.tsx@@ -0,0 +1,302 @@+/**+ * The bot editor's Advanced section renders the REAL core Capabilities+ * surfaces — SkillsView (installed skills + hub installs + detail),+ * ToolsetConfigPanel (per-toolset env/keys/model/post-setup) and McpTab+ * (per-server enable + OAuth + API keys) — pinned to the bot's own profile,+ * instead of bare checkbox stand-ins.+ *+ * All three are optional SDK namespace exports (hermes-agent#87317), so every+ * use site is feature-detected and older desktop builds keep the staged+ * checklist UI. The sharp edge is a REMOTE bot on a build whose SkillsView+ * predates `supportsFixedConnection`: rendering the live surface there would+ * read and write the ACTIVE gateway's skills under the remote bot's name —+ * the wrong machine — so those builds must fail closed to "staged only".+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { cleanup, render, screen } from '@testing-library/react'+import type { ReactNode } from 'react'+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import { translateBots } from './i18n-test-helper'+import type { CapabilityEntry } from './profile-config'+import type { RosterRow } from './types'++interface StubProps {+ fixedConnection?: string+ fixedProfile?: string+ gateway?: string+ profile?: unknown+ toolset?: string+}++/** The optional SDK exports, swapped per test to model each desktop build. */+const sdk = vi.hoisted(() => {+ const seen: Record<string, StubProps[]> = { McpTab: [], SkillsView: [], ToolsetConfigPanel: [] }++ const spy = (name: string) => {+ const Stub = (props: StubProps) => {+ seen[name].push(props)++ return null+ }++ return Stub+ }++ return {+ exports: {} as Record<string, unknown>,+ gatewayReads: { count: 0 },+ request: vi.fn(async () => ({})),+ requestProfile: vi.fn(async () => ({})),+ seen,+ spy+ }+})++// The optional exports are read at MODULE scope, so each build's set has to+// be live at the moment `vi.resetModules()` re-evaluates the editor — a value+// baked into the factory would freeze the first test's build for the rest.+vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const original = await importOriginal<typeof HermesSdk>()++ const mocked: Record<string, unknown> = {+ ...original,+ host: {+ ...original.host,+ getGateway: () => {+ sdk.gatewayReads.count += 1++ return 'ambient-gateway'+ },+ request: sdk.request,+ requestProfile: sdk.requestProfile+ },+ // The plugin bundle normally lands via `ctx.i18n.register` at load.+ usePluginI18n: () => translateBots+ }++ for (const name of ['McpTab', 'SkillsView', 'ToolsetConfigPanel']) {+ Object.defineProperty(mocked, name, { configurable: true, enumerable: true, get: () => sdk.exports[name] })+ }++ return mocked+})++// Each build re-imports the editor's whole module graph, which outruns the+// default per-test budget on a cold transform cache.+vi.setConfig({ testTimeout: 30_000 })++const remoteBot: RosterRow = {+ connectionId: 'remote-a',+ name: 'default',+ remoteSource: true,+ route: { connectionId: 'remote-a', mode: 'remote', profile: 'default', targetProfile: 'backend-default' },+ sourceScoped: true,+ targetProfile: 'backend-default'+}++const localBot: RosterRow = {+ connectionId: 'local',+ name: 'default',+ remoteSource: false,+ route: { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },+ sourceScoped: true,+ targetProfile: 'default'+}++const advancedState: {+ dirtyMcp: boolean+ dirtyModel: boolean+ dirtySkills: boolean+ dirtySoul: boolean+ dirtyToolsets: boolean+ loaded: boolean+ mcp: CapabilityEntry[]+ model: string+ provider: string+ skills: CapabilityEntry[]+ soul: string+ toolsets: CapabilityEntry[]+} = {+ dirtyMcp: false,+ dirtyModel: false,+ dirtySkills: false,+ dirtySoul: false,+ dirtyToolsets: false,+ loaded: true,+ mcp: [{ enabled: false, fromCatalog: true, installed: false, name: 'remote-mcp', requires: ['TOKEN'] }],+ model: '',+ provider: '',+ skills: [],+ soul: '',+ toolsets: []+}++function withQueryClient(children: ReactNode) {+ return (+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ {children}+ </QueryClientProvider>+ )+}++/** Load the editor against one desktop build's export set. */+async function renderEditor(+ exports: Record<string, unknown>,+ bot: RosterRow,+ state: Partial<typeof advancedState> = {}+) {+ sdk.exports = exports+ vi.resetModules()++ const { AdvancedProfileConfig } = await import('./profile-config')++ return render(+ withQueryClient(+ <AdvancedProfileConfig bot={bot} setState={() => undefined} state={{ ...advancedState, ...state }} />+ )+ )+}++beforeAll(async () => {+ // Warm the transform cache so the first test isn't charged for it.+ await import('./profile-config')+}, 120_000)++beforeEach(() => {+ vi.clearAllMocks()+ sdk.gatewayReads.count = 0++ for (const key of Object.keys(sdk.seen)) {+ sdk.seen[key].length = 0+ }+})++afterEach(() => {+ cleanup()+})++describe('a build whose SkillsView cannot route connections', () => {+ const oldBuild = () => ({+ McpTab: sdk.spy('McpTab'),+ SkillsView: sdk.spy('SkillsView'),+ ToolsetConfigPanel: sdk.spy('ToolsetConfigPanel')+ })++ it('fails closed for a REMOTE bot \u2014 staged model + SOUL only', async () => {+ const { container } = await renderEditor(oldBuild(), remoteBot)++ // The model catalog settles first so the picker is past its spinner.+ expect(await screen.findByText('Provider')).toBeTruthy()+ expect(screen.getByText(/Remote capabilities require a newer desktop/)).toBeTruthy()+ expect(sdk.seen.SkillsView).toHaveLength(0)+ expect(sdk.seen.McpTab).toHaveLength(0)+ expect(sdk.seen.ToolsetConfigPanel).toHaveLength(0)+ expect(screen.queryByText('Skills Hub')).toBeNull()+ expect(screen.queryByRole('button', { name: /Set up/ })).toBeNull()+ // Model + SOUL still edit, and stay staged until the user saves.+ expect(container.querySelector('textarea')).toBeTruthy()+ // Nothing may read the AMBIENT gateway on behalf of a remote bot.+ expect(sdk.gatewayReads.count).toBe(0)++ container.querySelectorAll('button, input').forEach(node => (node as HTMLElement).click())++ expect(sdk.request).not.toHaveBeenCalled()+ expect(sdk.gatewayReads.count).toBe(0)+ })++ it('keeps the LOCAL capability surfaces, each scoped to the bot profile', async () => {+ await renderEditor(oldBuild(), localBot, {+ skills: [{ enabled: true, name: 'staged-skill' }],+ toolsets: [{ enabled: true, name: 'local-tools' }]+ })++ // The staged checklist and the hub search section both survive here.+ expect(screen.getByText('staged-skill')).toBeTruthy()+ expect(screen.getByText('Skills Hub')).toBeTruthy()+ expect(sdk.seen.ToolsetConfigPanel[0]).toEqual({+ profile: { connectionId: 'local', profile: 'default' },+ toolset: 'local-tools'+ })+ expect(sdk.seen.McpTab[0]).toEqual({+ gateway: 'ambient-gateway',+ profile: { connectionId: 'local', profile: 'default' }+ })+ expect(sdk.gatewayReads.count).toBe(1)+ })+})++describe('a connection-aware SkillsView', () => {+ it('receives the connection and the BACKEND profile separately', async () => {+ const Routed = sdk.spy('SkillsView')++ ;(Routed as unknown as { supportsFixedConnection: boolean }).supportsFixedConnection = true++ await renderEditor({ SkillsView: Routed }, remoteBot)++ // The alias's logical name is `default`; the backend row it activates into+ // is `backend-default`. Pinning the logical name would edit the wrong one.+ expect(sdk.seen.SkillsView[0]).toMatchObject({+ fixedConnection: 'remote-a',+ fixedProfile: 'backend-default'+ })+ })++ it('#93492: degrades an orphaned row to its own name instead of throwing', async () => {+ const Routed = sdk.spy('SkillsView')++ ;(Routed as unknown as { supportsFixedConnection: boolean }).supportsFixedConnection = true++ // A row whose owning connection was removed resolves to no route at all.+ // The editor renders on the render path, so a throw here would take the+ // whole pane down through the dialog's error boundary.+ await renderEditor({ SkillsView: Routed }, { ...remoteBot, connectionId: '', route: undefined })++ expect(sdk.seen.SkillsView[0]).toEqual({ embedded: true, fixedProfile: 'default' })+ })+})++describe('a build with no Capabilities exports at all', () => {+ const bareBuild = { McpTab: undefined, SkillsView: undefined, ToolsetConfigPanel: undefined }++ it('keeps the checkbox MCP list with its inline setup button', async () => {+ await renderEditor(bareBuild, localBot)++ expect(screen.getByText('remote-mcp')).toBeTruthy()+ expect(screen.getByRole('button', { name: /Set up/ })).toBeTruthy()+ })++ it('says so plainly when the profile has no MCP servers', async () => {+ await renderEditor(bareBuild, localBot, { mcp: [] })++ expect(screen.getByText('No MCP servers configured or in the catalog.')).toBeTruthy()+ })+})++describe('the model catalog read', () => {+ it('#95279: rides the bot\u2019s captured route and never forces a refresh', async () => {+ sdk.exports = {}+ vi.resetModules()++ const { ModelPicker } = await import('./model-picker')++ render(+ withQueryClient(<ModelPicker bot={remoteBot} onChange={() => undefined} value={{ model: '', provider: '' }} />)+ )++ // No `refresh`: a forced network read on every mount bypassed the+ // staleTime cache, so each Bots view remount re-entered the spinner and+ // discarded the user's staged selection mid-edit.+ expect(sdk.requestProfile).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'remote-a' }),+ 'model.options',+ {+ explicit_only: false,+ include_unconfigured: true+ }+ )+ expect(sdk.request).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/profile-config.test.ts b/apps/desktop/src/plugins/hermes-bots/profile-config.test.tsnew file mode 100644index 00000000000..e5876bb87c2--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/profile-config.test.ts@@ -0,0 +1,231 @@+/**+ * `applyAdvancedConfig` — the advanced editor's save, which persists ONLY the+ * dirty sections and reports per-section outcomes back to the dialog.+ *+ * Two contracts live here:+ *+ * - **Inherit clears the pin.** A dirty model section with both fields empty+ * means "inherit the gateway default", which is a `config unset model`, not+ * a configure payload. Its success/failure has to merge into the same+ * `applied` map as the RPC sections, or the dialog toasts a contradictory+ * "saved" over a failed clear.+ * - **#95293 on this surface.** The gateway now guards data-policy /+ * expensive models for `profiles.configure` too, answering+ * `confirm_required` + `confirm_message`. Bots does NOT route through+ * use-model-controls, so before the fix that response matched no branch and+ * the pick silently dropped. It must go through the SAME shared handler the+ * core picker uses (one applier, no forked confirm UI), must not count as a+ * FAILED section while it is merely pending, and Confirm must resend ONLY+ * the model section with `confirm_expensive_model: true`.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import { applyAdvancedConfig, emptyAdvancedState } from './profile-config'+import type { RosterRow } from './types'++type AdvancedConfigState = ReturnType<typeof emptyAdvancedState>++/** The payload the shared core confirm flow receives — the same object the+ * model picker hands it. */+interface ModelSwitchConfirmArgs {+ confirmMessage: string+ finish: () => void+ requestConfirmed: () => Promise<{ applied?: Record<string, boolean> } | undefined>+}++const { confirmMock, hostMock, invalidateMock } = vi.hoisted(() => ({+ confirmMock: vi.fn((_args: ModelSwitchConfirmArgs) => 'notification-1'),+ hostMock: {+ getGateway: () => 'ambient-gateway',+ request: vi.fn(),+ requestProfile: vi.fn(),+ state: { connectionId: { get: () => 'local' }, gateway: { get: () => 'open' }, profile: { get: () => 'default' } }+ },+ invalidateMock: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ Button: () => null,+ Checkbox: () => null,+ GlyphSpinner: () => null,+ host: hostMock,+ Input: () => null,+ McpTab: undefined,+ queryClient: { invalidateQueries: invalidateMock },+ ScrollArea: () => null,+ Select: () => null,+ SelectContent: () => null,+ SelectItem: () => null,+ SelectTrigger: () => null,+ SelectValue: () => null,+ SkillsView: undefined,+ surfaceModelSwitchConfirm: confirmMock,+ Textarea: () => null,+ ToolsetConfigPanel: undefined,+ useQuery: vi.fn(() => ({ data: undefined, error: null, isLoading: false })),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))+// The SOUL protocol append has its own suite; here it must not rewrite the+// text under the assertions.+vi.mock('./soul', () => ({ ensureMessagingProtocol: (soul: string) => soul }))++const bot = { name: 'zeta' } as RosterRow++const dirtyModel = (patch: Partial<AdvancedConfigState> = {}): AdvancedConfigState => ({+ ...emptyAdvancedState(),+ dirtyModel: true,+ loaded: true,+ model: 'muse-spark-1.2-contributor',+ provider: 'opencode-go',+ ...patch+})++/** Every RPC in order, with params frozen at call time. */+const routed: Array<{ method: string; params: Record<string, unknown> }> = []++function respondWith(handler: (method: string, params: Record<string, unknown>) => unknown) {+ hostMock.request.mockImplementation(async (method: string, params: Record<string, unknown>) => {+ routed.push({ method, params: structuredClone(params ?? {}) })++ return handler(method, params)+ })+}++beforeEach(() => {+ vi.clearAllMocks()+ routed.length = 0+ respondWith(() => ({}))+})++describe('selecting Inherit', () => {+ it('clears the profile model assignment through the CLI', async () => {+ respondWith(() => ({ blocked: false, code: 0, output: 'Unset model' }))++ const result = await applyAdvancedConfig(bot, dirtyModel({ model: '', provider: '' }))++ expect(routed).toEqual([+ { method: 'cli.exec', params: { argv: ['--profile', 'zeta', 'config', 'unset', 'model'] } }+ ])+ expect(result).toEqual({ applied: { model: true }, ok: true })+ })++ it('merges the clear with the other dirty sections’ outcomes', async () => {+ respondWith(method => (method === 'cli.exec' ? { blocked: false, code: 0 } : { applied: { soul: true } }))++ const result = await applyAdvancedConfig(+ bot,+ dirtyModel({ dirtySoul: true, model: '', provider: '', soul: '# Ops' })+ )++ expect(routed.map(call => call.method)).toEqual(['cli.exec', 'profiles.configure'])+ expect(routed[1].params).toEqual({ name: 'zeta', soul: '# Ops' })+ expect(result).toMatchObject({ applied: { model: true, soul: true }, ok: true })+ })++ it('reports a rejected clear as a failed section', async () => {+ respondWith(() => ({ blocked: false, code: 1, output: 'Config key not set' }))++ await expect(applyAdvancedConfig(bot, dirtyModel({ model: '', provider: '' }))).resolves.toEqual({+ applied: { model: false },+ ok: false+ })+ })++ it('treats a thrown clear the same as a rejected one', async () => {+ hostMock.request.mockRejectedValue(new Error('gateway down'))++ await expect(applyAdvancedConfig(bot, dirtyModel({ model: '', provider: '' }))).resolves.toEqual({+ applied: { model: false },+ ok: false+ })+ })++ it('refuses a half-filled model section outright', async () => {+ // A provider with no model (or the reverse) is neither a pin nor a clear.+ await expect(applyAdvancedConfig(bot, dirtyModel({ model: '' }))).resolves.toEqual({+ applied: { model: false },+ ok: false+ })+ expect(routed).toHaveLength(0)+ })+})++describe('a guarded model switch (#95293)', () => {+ it('surfaces the SHARED confirm flow instead of silently dropping the pick', async () => {+ respondWith(() => ({+ applied: {},+ confirm_message: 'CONTRIBUTOR TIER: this model may train on your data.',+ confirm_required: true,+ ok: true+ }))++ const result = await applyAdvancedConfig(bot, dirtyModel())++ expect(routed).toHaveLength(1)+ expect(routed[0].method).toBe('profiles.configure')+ expect(routed[0].params.model).toBe('muse-spark-1.2-contributor')+ expect(routed[0].params.confirm_expensive_model).toBeFalsy()++ expect(confirmMock).toHaveBeenCalledTimes(1)+ expect(confirmMock.mock.calls[0][0].confirmMessage).toMatch(/CONTRIBUTOR TIER/)++ // Pending confirmation is NOT a failed section — the editor must not toast+ // "Some sections failed: model" while the confirm toast is still up.+ expect(result.applied?.model).not.toBe(false)+ expect(result.ok).toBe(true)+ })++ it('resends ONLY the model section on Confirm', async () => {+ let calls = 0++ respondWith(() => {+ calls += 1++ return calls === 1+ ? { applied: {}, confirm_message: 'guarded', confirm_required: true, ok: true }+ : { applied: { model: true }, ok: true }+ })++ await applyAdvancedConfig(bot, dirtyModel({ dirtySoul: true, soul: '# Zeta' }))++ const confirmed = await confirmMock.mock.calls[0][0].requestConfirmed()++ expect(routed).toHaveLength(2)+ expect(routed[1].method).toBe('profiles.configure')+ expect(Object.keys(routed[1].params).sort()).toEqual(['confirm_expensive_model', 'model', 'name', 'provider'])+ expect(routed[1].params).toMatchObject({+ confirm_expensive_model: true,+ model: 'muse-spark-1.2-contributor',+ name: 'zeta',+ provider: 'opencode-go'+ })+ expect(confirmed?.applied?.model).toBe(true)+ })++ it('refreshes the roster once the confirmed switch lands', async () => {+ respondWith(() => ({ applied: {}, confirm_message: 'guarded', confirm_required: true, ok: true }))++ await applyAdvancedConfig(bot, dirtyModel())+ confirmMock.mock.calls[0][0].finish()++ expect(invalidateMock).toHaveBeenCalled()+ })++ it('leaves an unguarded save single-shot', async () => {+ respondWith(() => ({ applied: { model: true }, ok: true }))++ const result = await applyAdvancedConfig(bot, dirtyModel())++ expect(routed).toHaveLength(1)+ expect(confirmMock).not.toHaveBeenCalled()+ expect(result).toMatchObject({ applied: { model: true }, ok: true })+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/profile-ops.test.ts b/apps/desktop/src/plugins/hermes-bots/profile-ops.test.tsnew file mode 100644index 00000000000..6b794421fd1--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/profile-ops.test.ts@@ -0,0 +1,155 @@+/**+ * Duplicating a bot: clone the profile (config/skills/SOUL/memory via+ * `clone_from`) and copy the LOOK, but never the things that belong to the+ * original — its canonical-chat pointer and its creation stamp.+ *+ * The name search is the other half. Candidates are `<base>-2`, `-3`, … and+ * the BASE is truncated to fit, never the suffix (#19): slicing the joined+ * string chops the "-2" off a max-length name, so the candidate collides with+ * the base forever and the search runs out at -99.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import { $botMeta } from './data'+import { duplicateBot } from './profile-ops'+import type { RosterRow } from './types'++const { ensureBotMetadataMock, hostMock, storageMock } = vi.hoisted(() => ({+ ensureBotMetadataMock: vi.fn(),+ hostMock: {+ request: vi.fn(),+ requestProfile: vi.fn(),+ state: { connectionId: { get: () => 'local' }, focusedSessionOwner: null, profile: { get: () => 'default' } }+ },+ storageMock: { get: vi.fn(), set: vi.fn() }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ forgetSessionUnread: vi.fn(),+ host: hostMock,+ queryClient: { invalidateQueries: vi.fn() },+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => ({ storage: storageMock }), ID: 'hermes-bots' }))+vi.mock('./avatar-image', () => ({ isBackfilledFacePng: () => false }))+vi.mock('./canonical-chat', () => ({ ensureBotMetadata: ensureBotMetadataMock }))++const calls: Array<{ method: string; params: Record<string, unknown> }> = []++beforeEach(() => {+ vi.clearAllMocks()+ calls.length = 0+ $botMeta.set({})+ storageMock.set.mockResolvedValue(undefined)+ hostMock.request.mockImplementation(async (method: string, params: Record<string, unknown>) => {+ calls.push({ method, params: structuredClone(params ?? {}) })++ return { ok: true }+ })+})++describe('duplicating a bot', () => {+ it('copies the look but neither the chat pointer nor the creation stamp', async () => {+ $botMeta.set({+ researcher: {+ chat: 'sess-source-forever',+ color: '#f97316',+ created: 1_700_000_000_000,+ image: 'data:image/png;base64,xx',+ shape: 'circle',+ title: 'Researcher'+ }+ })++ const name = await duplicateBot({ description: 'finds things', name: 'researcher' } as RosterRow, [+ { name: 'researcher' } as RosterRow+ ])++ expect(name).toBe('researcher-2')++ const clone = $botMeta.get()['researcher-2']++ expect(clone).toMatchObject({+ color: '#f97316',+ image: 'data:image/png;base64,xx',+ shape: 'circle',+ title: 'Researcher (copy)'+ })+ expect(clone.chat).toBeUndefined()+ expect(clone.created).toBeUndefined()++ expect(calls.find(call => call.method === 'profiles.create')?.params).toMatchObject({+ clone_from: 'researcher',+ name: 'researcher-2'+ })++ const configure = calls.filter(call => call.method === 'profiles.configure').at(-1)+ const uiMeta = (configure?.params.ui_meta as Record<string, Record<string, unknown>>)['hermes-bots']++ expect(uiMeta.title).toBe('Researcher (copy)')+ expect(uiMeta.chat).toBeUndefined()+ expect(uiMeta.created).toBeUndefined()+ })++ it('duplicates the look of a bot that never had a pointer', async () => {+ $botMeta.set({ painter: { color: '#38bdf8', shape: 'cloud', title: 'Painter' } })++ const name = await duplicateBot({ name: 'painter' } as RosterRow, [{ name: 'painter' } as RosterRow])++ expect($botMeta.get()[name]).toMatchObject({ shape: 'cloud', title: 'Painter (copy)' })+ expect($botMeta.get()[name].chat).toBeUndefined()+ })++ it('walks past taken suffixes to the first free slot', async () => {+ const roster = ['ops', 'ops-2', 'ops-3'].map(name => ({ name }) as RosterRow)++ expect(await duplicateBot({ name: 'ops' } as RosterRow, roster)).toBe('ops-4')+ })++ it('truncates the BASE so a max-length name still gets a distinct suffix (#19)', async () => {+ const base = 'b'.repeat(64)++ const name = await duplicateBot({ name: base } as RosterRow, [{ name: base } as RosterRow])++ expect(name).toHaveLength(64)+ expect(name.endsWith('-2')).toBe(true)+ expect(name).not.toBe(base)+ })++ it('ensures the source bot has its metadata before cloning', async () => {+ // clone_from copies the profile dir; the source's Bot Chat has to exist+ // first or the clone inherits a half-built profile.+ await duplicateBot({ name: 'ops' } as RosterRow, [])++ expect(ensureBotMetadataMock).toHaveBeenCalledTimes(1)+ })++ it('only collides against rows on the SAME connection', async () => {+ // A same-named bot on another gateway is a different agent entirely.+ const bot = {+ connectionId: 'vera',+ name: 'ops',+ route: { connectionId: 'vera', mode: 'remote', profile: 'ops', targetProfile: 'ops' },+ sourceScoped: true+ } as RosterRow++ const elsewhere = {+ connectionId: 'other',+ name: 'ops-2',+ route: { connectionId: 'other', mode: 'remote', profile: 'ops-2', targetProfile: 'ops-2' },+ sourceScoped: true+ } as RosterRow++ hostMock.requestProfile.mockResolvedValue({ ok: true })++ expect(await duplicateBot(bot, [bot, elsewhere])).toBe('ops-2')+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/relay.test.ts b/apps/desktop/src/plugins/hermes-bots/relay.test.tsnew file mode 100644index 00000000000..9514e0643b8--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts@@ -0,0 +1,642 @@+/**+ * The cross-connection bot relay — the Desktop-as-router loops that let a bot+ * on one gateway reach a bot on another (Aug 2026 ruling: connections ARE the+ * peer set).+ *+ * Three incidents are pinned here:+ *+ * - #93091 — the drain was poll-only, so a DM waited out the interval before+ * it moved (#92760 "slow replies"). The gateway now broadcasts+ * `bot_relay.outbox.pending`; a burst of signals collapses to ONE drain,+ * a push landing mid-drain re-schedules instead of being swallowed, and+ * the interval survives as a BACKSTOP only. Item 2 of the same issue: a+ * transient `profiles.list` blip must not be pushed as "that machine is+ * empty" — the gateway reads absence from a fresh roster as offline.+ * - #93594 — each registered connection's pooled socket is pinned open while+ * the relay runs, so the drain reuses one persistent WebSocket instead of+ * dialing and tearing one down per tick.+ * - the waiter contract — a missing target connection must still post a reply,+ * or the sending agent hangs until its own timeout.+ *+ * Everything is driven through the two real lifecycle doors, `startBotRelay` /+ * `stopBotRelay`; only the SDK `host` and the attention hooks are mocked.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { ProfileRoute } from './types'++const { clearBotAttentionMock, hostMock, noteBotAttentionMock } = vi.hoisted(() => ({+ clearBotAttentionMock: vi.fn(),+ hostMock: {+ onEvent: vi.fn(),+ profileRoutes: vi.fn(),+ requestProfile: vi.fn(),+ retainProfileSocket: vi.fn()+ } as Record<string, unknown>,+ noteBotAttentionMock: vi.fn()+}))++vi.mock('@hermes/plugin-sdk', () => ({ host: hostMock }))++vi.mock('./data', () => ({+ botHandle: (name: string) => (name === 'default' ? 'hermes' : name),+ clearBotAttention: clearBotAttentionMock,+ noteBotAttention: noteBotAttentionMock+}))++const RELAY_PUSH_DEBOUNCE_MS = 250+const RELAY_DRAIN_INTERVAL_MS = 30_000++const route = (id: string): ProfileRoute => ({+ connectionId: id,+ mode: 'remote',+ profile: 'default',+ targetProfile: 'default'+})++/** Every RPC through one table, recording what each connection was asked. */+interface RelayCall {+ connectionId: string+ method: string+ params: Record<string, unknown>+}++function respondWith(handler: (call: RelayCall) => unknown) {+ const calls: RelayCall[] = []++ ;(hostMock.requestProfile as ReturnType<typeof vi.fn>).mockImplementation(+ async (target: ProfileRoute, method: string, params: Record<string, unknown>) => {+ const call = { connectionId: target.connectionId, method, params: structuredClone(params ?? {}) }++ calls.push(call)++ return handler(call)+ }+ )++ return calls+}++/** Pins handed out by the mocked retention door, in grant order. */+interface Pin {+ released: boolean+ route: ProfileRoute+}++function trackRetention() {+ const pins: Pin[] = []++ ;(hostMock.retainProfileSocket as ReturnType<typeof vi.fn>).mockImplementation((pinned: ProfileRoute) => {+ const pin: Pin = { released: false, route: pinned }++ pins.push(pin)++ return () => {+ pin.released = true+ }+ })++ return pins+}++async function loadRelay() {+ vi.resetModules()++ return import('./relay')+}++/** Fire the gateway's pending-envelope broadcast and let the debounced drain+ * run to completion. */+async function pushAndSettle(times = 1) {+ const listener = (hostMock.onEvent as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[1] as () => void++ for (let i = 0; i < times; i += 1) {+ listener()+ }++ await vi.advanceTimersByTimeAsync(RELAY_PUSH_DEBOUNCE_MS + 10)+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.clearAllMocks()+ hostMock.onEvent = vi.fn(() => vi.fn())+ hostMock.profileRoutes = vi.fn(async () => [route('a'), route('b')])+ hostMock.requestProfile = vi.fn(async () => ({}))+ hostMock.retainProfileSocket = vi.fn(() => vi.fn())+})++afterEach(() => {+ vi.useRealTimers()+})++describe('push-notified drain (#93091)', () => {+ it('collapses a burst of pending signals into ONE drain', async () => {+ const calls = respondWith(() => ({ envelopes: [] }))+ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ calls.length = 0++ await pushAndSettle(6)++ // One drain visits each connection's outbox exactly once.+ expect(calls.filter(call => call.method === 'bot_relay.outbox.drain')).toHaveLength(2)++ stopBotRelay()+ })++ it('drains again for a signal that lands after the window closed', async () => {+ const calls = respondWith(() => ({ envelopes: [] }))+ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ calls.length = 0++ await pushAndSettle()+ await pushAndSettle(2)++ expect(calls.filter(call => call.method === 'bot_relay.outbox.drain')).toHaveLength(4)++ stopBotRelay()+ })++ it('keeps the interval poll as a BACKSTOP at the slow cadence', async () => {+ // The poll was 4s back when it WAS the delivery path — which (before+ // route retention) meant a fresh WebSocket dial + teardown per connection+ // every 4s. Push carries envelope latency now; the poll only covers older+ // backends and events that never reach the tap.+ const calls = respondWith(() => ({ envelopes: [] }))+ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ calls.length = 0++ await vi.advanceTimersByTimeAsync(RELAY_DRAIN_INTERVAL_MS - 1000)++ expect(calls.filter(call => call.method === 'bot_relay.outbox.drain')).toHaveLength(0)++ await vi.advanceTimersByTimeAsync(2000)++ expect(calls.filter(call => call.method === 'bot_relay.outbox.drain')).toHaveLength(2)++ stopBotRelay()+ })++ it('re-schedules a push that raced an in-flight drain instead of dropping it', async () => {+ // The gateway signature is monotone — one event per new envelope, never+ // re-broadcast — so a push swallowed by the busy guard would strand its+ // envelope until the poll.+ let release!: () => void++ const firstDrain = new Promise<void>(resolve => {+ release = resolve+ })++ let drains = 0++ const calls = respondWith(async call => {+ if (call.method === 'bot_relay.outbox.drain') {+ drains += 1++ if (drains === 1) {+ await firstDrain+ }+ }++ return { envelopes: [] }+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ calls.length = 0++ await pushAndSettle()+ const midFlight = drains++ // A second push while the first drain is still awaiting its RPC.+ await pushAndSettle()+ expect(drains).toBe(midFlight)++ release()+ await vi.advanceTimersByTimeAsync(RELAY_PUSH_DEBOUNCE_MS + 10)++ expect(drains).toBeGreaterThan(midFlight)++ stopBotRelay()+ })++ it('never schedules a drain once the relay is stopped', async () => {+ const calls = respondWith(() => ({ envelopes: [] }))+ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ stopBotRelay()+ calls.length = 0++ await pushAndSettle(3)+ await vi.advanceTimersByTimeAsync(RELAY_DRAIN_INTERVAL_MS * 2)++ expect(calls).toHaveLength(0)+ })++ it('feature-detects the event door and disposes its subscription', async () => {+ const unsubscribe = vi.fn()++ hostMock.onEvent = vi.fn(() => unsubscribe)++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ expect(hostMock.onEvent).toHaveBeenCalledWith('bot_relay.outbox.pending', expect.any(Function))++ stopBotRelay()+ expect(unsubscribe).toHaveBeenCalledTimes(1)++ // An older shell has no event door at all; the relay still starts.+ hostMock.onEvent = undefined+ const legacy = await loadRelay()++ expect(() => legacy.startBotRelay()).not.toThrow()+ legacy.stopBotRelay()+ })+})++describe('relay-route socket retention (#93594)', () => {+ it('pins each connection ONCE across many drain ticks', async () => {+ const pins = trackRetention()++ respondWith(() => ({ envelopes: [] }))++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()++ for (let tick = 0; tick < 4; tick += 1) {+ await pushAndSettle()+ }++ expect(pins.map(pin => pin.route.connectionId)).toEqual(['a', 'b'])+ expect(pins.every(pin => !pin.released)).toBe(true)++ stopBotRelay()+ })++ it('releases exactly the pin of a connection that left the registry', async () => {+ const pins = trackRetention()++ respondWith(() => ({ envelopes: [] }))++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()++ hostMock.profileRoutes = vi.fn(async () => [route('a'), route('c')])+ await pushAndSettle()++ expect(pins.filter(pin => pin.released).map(pin => pin.route.connectionId)).toEqual(['b'])+ expect(pins.map(pin => pin.route.connectionId)).toEqual(['a', 'b', 'c'])++ stopBotRelay()+ })++ it('drops every pin on stop, and stays idempotent', async () => {+ const pins = trackRetention()++ respondWith(() => ({ envelopes: [] }))++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()+ stopBotRelay()++ expect(pins.every(pin => pin.released)).toBe(true)++ // A second stop releases nothing new — the pins are already gone.+ const releasedCount = pins.filter(pin => pin.released).length++ stopBotRelay()+ expect(pins.filter(pin => pin.released)).toHaveLength(releasedCount)+ })++ it('unpins everything when the peer set drops below two connections', async () => {+ // Retention follows the relay-ELIGIBLE set: with nothing to relay,+ // nothing stays pinned.+ const pins = trackRetention()++ respondWith(() => ({ envelopes: [] }))++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()+ expect(pins).toHaveLength(2)++ hostMock.profileRoutes = vi.fn(async () => [route('a')])+ await pushAndSettle()++ expect(pins.every(pin => pin.released)).toBe(true)++ stopBotRelay()+ })++ it('is feature-detected: an older shell without the door is a no-op', async () => {+ hostMock.retainProfileSocket = undefined++ respondWith(() => ({ envelopes: [] }))++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await expect(pushAndSettle()).resolves.toBeUndefined()++ stopBotRelay()+ })+})++describe('the roster loop pushes the OTHER connections’ agents', () => {+ it('gives each gateway a union roster that excludes its own agents', async () => {+ const calls = respondWith(call => {+ if (call.method === 'profiles.list') {+ return { profiles: [{ name: call.connectionId === 'a' ? 'default' : 'ops' }] }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)++ const syncs = calls.filter(call => call.method === 'bot_relay.roster.sync')++ expect(syncs.map(call => call.connectionId)).toEqual(['a', 'b'])+ expect(syncs[0].params.agents).toEqual([+ expect.objectContaining({ connection_id: 'b', handle: 'ops', profile: 'ops' })+ ])+ // The primary profile is published by its callable alias, never "default".+ expect(syncs[1].params.agents).toEqual([+ expect.objectContaining({ connection_id: 'a', handle: 'hermes', profile: 'default' })+ ])++ stopBotRelay()+ })++ it('never conflates a transient fetch failure with an empty connection', async () => {+ // A live machine whose profiles.list blips must not be pushed as absent:+ // the gateway-side liveness check reads "absent from a fresh roster" as+ // definitively offline and refuses enqueues with a false runtime_offline+ // (#93091 item 2).+ let failB = false++ const calls = respondWith(call => {+ if (call.method === 'profiles.list') {+ if (call.connectionId === 'b' && failB) {+ throw new Error('socket blip')+ }++ return { profiles: [{ name: call.connectionId === 'a' ? 'default' : 'ops' }] }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ calls.length = 0++ failB = true+ await vi.advanceTimersByTimeAsync(60_000)++ const pushedToA = calls.find(call => call.method === 'bot_relay.roster.sync' && call.connectionId === 'a')++ expect(pushedToA?.params.agents).toEqual([expect.objectContaining({ profile: 'ops' })])++ stopBotRelay()+ })++ it('drops the cached rows of a connection that genuinely disconnected', async () => {+ const calls = respondWith(call =>+ call.method === 'profiles.list' ? { profiles: [{ name: call.connectionId }] } : {}+ )++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)++ // 'b' leaves the registry and 'c' arrives: b's agents must not linger.+ hostMock.profileRoutes = vi.fn(async () => [route('a'), route('c')])+ calls.length = 0+ await vi.advanceTimersByTimeAsync(60_000)++ const pushedToA = calls.find(call => call.method === 'bot_relay.roster.sync' && call.connectionId === 'a')++ expect(pushedToA?.params.agents).toEqual([expect.objectContaining({ profile: 'c' })])++ stopBotRelay()+ })++ it('stays quiet with a single connection — there is no peer to relay to', async () => {+ hostMock.profileRoutes = vi.fn(async () => [route('a')])++ const calls = respondWith(() => ({}))+ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)++ expect(calls).toHaveLength(0)++ stopBotRelay()+ })+})++describe('the drain loop wires drain → deliver → reply', () => {+ const envelope = {+ id: 'env-1',+ message: 'status?',+ target_connection: 'b',+ target_profile: 'ops'+ }++ it('delivers on the target’s own socket and posts the reply to the sender', async () => {+ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {+ return { envelopes: call.connectionId === 'a' ? [envelope] : [] }+ }++ if (call.method === 'bot_relay.deliver') {+ return { reply: 'all green' }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()++ expect(calls.find(call => call.method === 'bot_relay.deliver')).toMatchObject({+ connectionId: 'b',+ params: { message: 'status?', profile: 'ops' }+ })+ expect(calls.find(call => call.method === 'bot_relay.reply')).toMatchObject({+ connectionId: 'a',+ params: { id: 'env-1', reply: 'all green' }+ })+ // A delivered background DM is this bot's "good turn".+ expect(clearBotAttentionMock).toHaveBeenCalledWith('b::ops')++ stopBotRelay()+ })++ it('still posts a reply when the target connection is gone — the waiter must never dangle', async () => {+ const calls = respondWith(call =>+ call.method === 'bot_relay.outbox.drain'+ ? { envelopes: call.connectionId === 'a' ? [{ ...envelope, target_connection: 'ghost' }] : [] }+ : {}+ )++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()++ expect(calls.some(call => call.method === 'bot_relay.deliver')).toBe(false)+ expect(calls.find(call => call.method === 'bot_relay.reply')?.params.error).toMatch(+ /'ghost' is not connected to this Desktop right now/+ )++ stopBotRelay()+ })++ it('forwards the gateway’s typed failure reason to both the reply and the badge', async () => {+ // #93091: bot_relay.deliver classifies the failed turn and ships the code+ // in `data.reason`; a classified code beats re-parsing free text.+ const failure = Object.assign(new Error('401 invalid x-api-key'), {+ data: { reason: 'provider_auth_or_access' }+ })++ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {+ return { envelopes: call.connectionId === 'a' ? [envelope] : [] }+ }++ if (call.method === 'bot_relay.deliver') {+ throw failure+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()++ expect(calls.find(call => call.method === 'bot_relay.reply')?.params).toMatchObject({+ error: '401 invalid x-api-key',+ id: 'env-1',+ reason: 'provider_auth_or_access'+ })+ expect(noteBotAttentionMock).toHaveBeenCalledWith('b::ops', 'provider_auth_or_access')++ stopBotRelay()+ })++ it('skips an older backend that rejects the drain RPC, and keeps going', async () => {+ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {+ if (call.connectionId === 'a') {+ throw new Error('unknown method')+ }++ return { envelopes: [] }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()++ expect(calls.filter(call => call.method === 'bot_relay.outbox.drain').map(call => call.connectionId)).toEqual([+ 'a',+ 'b'+ ])++ stopBotRelay()+ })+})++describe('stop halts both loops', () => {+ it('leaves no timer able to reach the gateway after teardown', async () => {+ const calls = respondWith(() => ({ envelopes: [] }))+ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ stopBotRelay()+ calls.length = 0++ await vi.advanceTimersByTimeAsync(5 * 60_000)++ expect(calls).toHaveLength(0)+ })++ it('does not leak a mid-drain rerun into the next start', async () => {+ let release!: () => void++ const held = new Promise<void>(resolve => {+ release = resolve+ })++ let drains = 0++ respondWith(async call => {+ if (call.method === 'bot_relay.outbox.drain') {+ drains += 1++ if (drains === 1) {+ await held+ }+ }++ return { envelopes: [] }+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()+ await pushAndSettle()+ stopBotRelay()+ release()+ await vi.advanceTimersByTimeAsync(RELAY_PUSH_DEBOUNCE_MS + 10)++ const afterStop = drains++ startBotRelay()+ await vi.advanceTimersByTimeAsync(RELAY_PUSH_DEBOUNCE_MS + 10)++ expect(drains).toBe(afterStop)++ stopBotRelay()+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/roster-actions.test.ts b/apps/desktop/src/plugins/hermes-bots/roster-actions.test.tsnew file mode 100644index 00000000000..26f8213f191--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/roster-actions.test.ts@@ -0,0 +1,212 @@+/**+ * The unread/toast poll every roster refresh feeds.+ *+ * This poll is the ONLY unread signal a canonical Bot Chat can have: Bot Chats+ * are unconditionally hidden, so they never reach the session list the+ * backend's own watermark iterates, and a delivery from the CLI, cron, another+ * bot, or another machine never touches this window's live turn edge either.+ * Hence the local watermark per source-qualified bot.+ *+ * The toasts themselves are opt-in and default OFF — a busy roster (cron runs,+ * bot-to-bot chatter) turns them into a firehose, and the dot already carries+ * the signal. The unread MARK is recorded either way, and it goes through+ * core's store (`markSessionUnreadFinished`) rather than a plugin-local map,+ * so the roster row's `SessionStatusDot` and the badge can never drift apart.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RosterRow } from './types'++const { hostMock, markUnreadMock, storageMock } = vi.hoisted(() => ({+ hostMock: {+ notify: vi.fn(),+ request: vi.fn(),+ state: { connectionId: { get: () => 'local' }, focusedSessionOwner: null, profile: { get: () => 'default' } }+ },+ markUnreadMock: vi.fn(),+ storageMock: { get: vi.fn(), set: vi.fn() }+}))++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ ackStoredSessionId: vi.fn(),+ atom,+ haptic: vi.fn(),+ host: hostMock,+ markSessionUnreadFinished: markUnreadMock,+ queryClient: { invalidateQueries: vi.fn() },+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({+ bumpBotOpenGeneration: vi.fn(),+ getBotOpenGeneration: vi.fn(),+ getPluginCtx: () => ({ storage: storageMock }),+ ID: 'hermes-bots'+}))++// The open path drags the whole group-chat surface in; the poll under test+// touches none of it.+vi.mock('./canonical-chat', () => ({+ notifyBotOpenFailure: vi.fn(),+ openBotCanonicalChat: vi.fn(),+ prepareBotSource: vi.fn()+}))+vi.mock('./group-chat', async () => {+ const { atom } = await import('nanostores')++ return { $groupChats: atom({}), $groupChatWorkspace: atom<null | string>(null) }+})+vi.mock('./group-chat-view', () => ({ openGroupChat: vi.fn() }))+vi.mock('./group-membership', () => ({ liveGroupChatNames: () => [] }))+vi.mock('./group-panes', () => ({ closeGroupChatMainTab: vi.fn() }))++/** A bot whose canonical Bot Chat carries the activity — the only shape that+ * can be marked unread, since the marker is keyed by canonical session id. */+const chatting = (name: string, lastActive: number, preview = 'hello'): RosterRow =>+ ({ canonical_session: { id: `${name}-chat`, last_active: lastActive, preview }, name }) as RosterRow++async function loadActions() {+ vi.resetModules()++ const [actions, botState, data] = await Promise.all([+ import('./roster-actions'),+ import('./bot-state'),+ import('./data')+ ])++ return { ...actions, ...botState, $botMeta: data.$botMeta }+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('the first poll only seeds watermarks', () => {+ it('marks nothing unread for history that predates the mount', async () => {+ const { trackInboundActivity } = await loadActions()++ trackInboundActivity([chatting('researcher', 5000)])++ expect(markUnreadMock).not.toHaveBeenCalled()+ expect(hostMock.notify).not.toHaveBeenCalled()+ })+})++describe('new activity after the seed', () => {+ it('marks the canonical chat unread through core’s store', async () => {+ const { trackInboundActivity } = await loadActions()++ trackInboundActivity([chatting('researcher', 5000)])+ trackInboundActivity([chatting('researcher', 6000)])++ expect(markUnreadMock).toHaveBeenCalledWith('researcher-chat', 'researcher')+ })++ it('stays silent unless the user opted into toasts', async () => {+ const { $activityToasts, trackInboundActivity } = await loadActions()++ trackInboundActivity([chatting('researcher', 5000)])+ trackInboundActivity([chatting('researcher', 6000)])+ expect(hostMock.notify).not.toHaveBeenCalled()++ $activityToasts.set(true)+ trackInboundActivity([chatting('researcher', 7000, 'a plain update')])++ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ expect(hostMock.notify.mock.calls[0][0]).toMatchObject({ kind: 'info', message: 'a plain update' })+ })++ it('titles a bot-to-bot delivery differently from ordinary activity', async () => {+ const { $activityToasts, trackInboundActivity } = await loadActions()++ $activityToasts.set(true)+ trackInboundActivity([chatting('researcher', 5000)])+ trackInboundActivity([chatting('researcher', 6000, 'Message from 🤖 manager (@manager): ship it')])++ expect(hostMock.notify.mock.calls[0][0].title).toMatch(/New message for/)++ trackInboundActivity([chatting('researcher', 7000, 'finished the run')])+ expect(hostMock.notify.mock.calls[1][0].title).toMatch(/has new activity/)+ })++ it('never badges the bot the user is currently looking at', async () => {+ const { $selectedBot, trackInboundActivity } = await loadActions()++ trackInboundActivity([chatting('researcher', 5000)])+ $selectedBot.set('researcher')+ trackInboundActivity([chatting('researcher', 6000)])++ expect(markUnreadMock).not.toHaveBeenCalled()+ })++ it('keeps marking a roster-hidden bot but never toasts it', async () => {+ const { $activityToasts, $botMeta, trackInboundActivity } = await loadActions()++ $activityToasts.set(true)+ $botMeta.set({ researcher: { hidden: true } })+ trackInboundActivity([chatting('researcher', 5000)])+ trackInboundActivity([chatting('researcher', 6000)])++ // Unhiding must reveal the dot, so the mark accumulates silently.+ expect(markUnreadMock).toHaveBeenCalledWith('researcher-chat', 'researcher')+ expect(hostMock.notify).not.toHaveBeenCalled()+ })++ it('sees a DM delivered into the hidden Bot Chat that last_session cannot', async () => {+ // The whole reason watermarks follow botActivitySession: a stale visible+ // session would otherwise hold the watermark and swallow the DM.+ const { trackInboundActivity } = await loadActions()++ const withStaleVisible = (lastActive: number) =>+ ({+ canonical_session: { id: 'dm', last_active: lastActive, preview: 'ping' },+ last_session: { id: 'scratch', last_active: 10 },+ name: 'dixie'+ }) as RosterRow++ trackInboundActivity([withStaleVisible(5000)])+ trackInboundActivity([withStaleVisible(6000)])++ expect(markUnreadMock).toHaveBeenCalledWith('dm', 'dixie')+ })++ it('tracks two same-named bots on different connections independently', async () => {+ const { trackInboundActivity } = await loadActions()++ const scoped = (connectionId: string, lastActive: number) =>+ ({+ canonical_session: { id: `${connectionId}-chat`, last_active: lastActive },+ connectionId,+ name: 'default',+ route: { connectionId, mode: 'remote', profile: 'default', targetProfile: 'default' },+ sourceScoped: true+ }) as RosterRow++ trackInboundActivity([scoped('a', 5000), scoped('b', 5000)])+ trackInboundActivity([scoped('a', 6000), scoped('b', 5000)])++ expect(markUnreadMock.mock.calls).toEqual([['a-chat', 'default']])+ })+})++describe('the toast preference', () => {+ it('persists through the plugin storage without throwing when it is absent', async () => {+ const { $activityToasts, setActivityToasts } = await loadActions()++ setActivityToasts(true)+ expect($activityToasts.get()).toBe(true)+ expect(storageMock.set).toHaveBeenCalledWith('activity-toasts', true)++ storageMock.set.mockImplementation(() => {+ throw new Error('storage unavailable')+ })+ expect(() => setActivityToasts(false)).not.toThrow()+ expect($activityToasts.get()).toBe(false)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/routing.test.ts b/apps/desktop/src/plugins/hermes-bots/routing.test.tsnew file mode 100644index 00000000000..8e7cde12ce3--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/routing.test.ts@@ -0,0 +1,234 @@+/**+ * Cross-connection routing: how a roster row resolves its owning connection,+ * how RPCs ride that owner, and how a configured Desktop alias keeps its+ * friendly identity after the backend it points at answers the roster.+ *+ * #89131 is the alias half: a per-profile Cloud alias ("moxie" → exact Cloud+ * connection → backend targetProfile "default") lost its name the moment the+ * hosted session activated, because the row that came back was keyed+ * (cloud-abc, default) — a different identity than the alias meta. It read as+ * the raw Cloud hostname, or as generic "Hermes" when Cloud was the only+ * source.+ *+ * Drives the real `routing` + `labels` modules; only the SDK `host` is mocked.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import { displayName } from './labels'+import {+ aliasIdentityFor,+ botConnectionRoute,+ botRosterMeta,+ indexAliasRoutes,+ requestForBot,+ resolveBotConnectionRoute+} from './routing'+import type { ProfileRoute, RosterRow } from './types'++const { hostMock } = vi.hoisted(() => ({+ hostMock: {+ request: vi.fn(),+ requestProfile: vi.fn(),+ state: { connectionId: { get: vi.fn(() => 'local') } }+ }+}))++vi.mock('@hermes/plugin-sdk', () => ({ host: hostMock }))++const MOXIE_ROUTE: ProfileRoute = {+ connectionId: 'cloud-abc',+ mode: 'remote',+ profile: 'moxie',+ targetProfile: 'default'+}++/** The hosted backend's own roster row after alias handoff: the Cloud+ * connection answers as its root profile, so the row identity is+ * (cloud-abc, default) — NOT the alias key. */+const hostedRow = {+ connectionId: 'cloud-abc',+ connectionLabel: 'cloud.example.com',+ name: 'default',+ remoteSource: true,+ route: { connectionId: 'cloud-abc', mode: 'remote', profile: 'default', targetProfile: 'default' },+ sourceScoped: true,+ targetProfile: 'default'+} as RosterRow++beforeEach(() => {+ vi.clearAllMocks()+ hostMock.state.connectionId.get.mockReturnValue('local')+ indexAliasRoutes([])+})++describe('alias identity survives the hosted handoff (#89131)', () => {+ it('names the backend row after the alias, through every meta generation', () => {+ indexAliasRoutes([+ { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },+ MOXIE_ROUTE+ ])++ // No stored title anywhere: the alias NAME is still the identity.+ expect(displayName(hostedRow, null)).toBe('Moxie')++ // The alias's Bot Mode title claims the row under either meta key shape —+ // aliases predate the v2 (connection-qualified) migration on mixed setups.+ const metaV2 = { 'cloud-abc::moxie': { title: 'Moxie' } }++ expect(botRosterMeta(hostedRow, metaV2)).toBe(metaV2['cloud-abc::moxie'])+ expect(displayName(hostedRow, botRosterMeta(hostedRow, metaV2))).toBe('Moxie')++ const metaV1 = { moxie: { title: 'Moxie ✨' } }++ expect(displayName(hostedRow, botRosterMeta(hostedRow, metaV1))).toBe('Moxie ✨')+ })++ it('renders the sole Cloud-only default as the alias, not "Hermes"', () => {+ // Global route is Cloud: the active gateway IS the Cloud connection and+ // profiles.list returns one unannotated rich `default` row.+ hostMock.state.connectionId.get.mockReturnValue('cloud-abc')+ indexAliasRoutes([MOXIE_ROUTE])++ expect(displayName({ name: 'default' }, null)).toBe('Moxie')+ // A user-set title still wins over the alias name.+ expect(displayName({ name: 'default' }, { title: 'Custom' })).toBe('Custom')+ })++ it('never leaks the alias onto a same-named default on another connection', () => {+ indexAliasRoutes([MOXIE_ROUTE])++ const otherDefault = {+ ...hostedRow,+ connectionId: 'other-conn',+ connectionLabel: 'Personal',+ route: undefined+ } as RosterRow++ expect(aliasIdentityFor(otherDefault)).toBeNull()+ expect(displayName(otherDefault, null)).toBe('Personal')+ // Local default while the ACTIVE gateway is local: untouched "Hermes".+ expect(displayName({ name: 'default' }, null)).toBe('Hermes')+ })++ it('fails closed when two aliases claim one backend row', () => {+ indexAliasRoutes([+ MOXIE_ROUTE,+ { connectionId: 'cloud-abc', mode: 'remote', profile: 'roxie', targetProfile: 'default' }+ ])++ expect(aliasIdentityFor(hostedRow)).toBeNull()+ // Ambiguous: fall back to the source label, not a guessed alias.+ expect(displayName(hostedRow, null)).toBe('cloud.example.com')+ })++ it('never lets the alias row claim its own alias entry', () => {+ indexAliasRoutes([MOXIE_ROUTE])++ const aliasRow = {+ connectionId: 'cloud-abc',+ name: 'moxie',+ route: { ...MOXIE_ROUTE },+ sourceScoped: true,+ targetProfile: 'default'+ } as RosterRow++ expect(aliasIdentityFor(aliasRow)).toBeNull()+ expect(displayName(aliasRow, null)).toBe('Moxie')+ })++ it('keeps only genuine aliases, and drops stale claims on refresh', () => {+ indexAliasRoutes([{ connectionId: 'local', mode: 'local', profile: 'rune', targetProfile: 'rune' }, MOXIE_ROUTE])++ expect(aliasIdentityFor(hostedRow)).toBeTruthy()++ // Alias removed from config → next inventory drops the claim.+ indexAliasRoutes([{ connectionId: 'local', mode: 'local', profile: 'rune', targetProfile: 'rune' }])++ expect(aliasIdentityFor(hostedRow)).toBeNull()+ expect(displayName(hostedRow, null)).toBe('cloud.example.com')+ })+})++describe('a row without a reachable owner', () => {+ it('reports a typed status instead of throwing, while dispatch still fails closed', () => {+ expect(resolveBotConnectionRoute({ name: 'plain' })).toEqual({ route: null, status: 'not_scoped' })+ expect(resolveBotConnectionRoute({ connectionId: 'vera', name: 'ops', sourceScoped: true })).toMatchObject({+ route: { connectionId: 'vera', mode: 'remote', profile: 'ops', targetProfile: 'ops' },+ status: 'resolved'+ })++ const orphan = { name: 'ops', remoteSource: true } as RosterRow++ expect(resolveBotConnectionRoute(orphan)).toMatchObject({ profile: 'ops', route: null, status: 'owner_removed' })+ // The strict wrapper real dispatch uses must still refuse — a row whose+ // connection was deleted has no ambient fallback to borrow.+ expect(() => botConnectionRoute(orphan)).toThrow(/no connection owner/)+ })++ it('a passive meta lookup on an orphaned row reads as "no route", never a throw', () => {+ const orphan = { name: 'ops', remoteSource: true } as RosterRow++ expect(botRosterMeta(orphan, { ops: { title: 'Ops' } })).toBeFalsy()+ })+})++describe('requestForBot rides the bot’s own source', () => {+ it('pins same-name bots to their own connection under concurrent requests', async () => {+ hostMock.requestProfile.mockImplementation(async (route: ProfileRoute) => ({ from: route.connectionId }))++ const rows = ['vera', 'mac-mini'].map(+ connectionId =>+ ({+ connectionId,+ name: 'default',+ remoteSource: true,+ sourceScoped: true+ }) as RosterRow+ )++ const answers = await Promise.all(rows.map(bot => requestForBot<{ from: string }>(bot, 'profiles.list', {})))++ expect(answers.map(answer => answer.from)).toEqual(['vera', 'mac-mini'])+ expect(hostMock.request).not.toHaveBeenCalled()+ })++ it('rewrites the logical profile to the backend target on the wire', async () => {+ hostMock.requestProfile.mockResolvedValue({})++ await requestForBot({ name: 'moxie', route: MOXIE_ROUTE, sourceScoped: true } as RosterRow, 'profiles.configure', {+ name: 'moxie',+ soul: '# hi'+ })++ expect(hostMock.requestProfile).toHaveBeenCalledWith(MOXIE_ROUTE, 'profiles.configure', {+ name: 'default',+ soul: '# hi'+ })+ })++ it('fails closed rather than falling back to the ambient request', async () => {+ // A scoped row whose shell predates requestProfile must NOT silently+ // execute against whichever gateway happens to be active.+ const scoped = { connectionId: 'vera', name: 'ops', sourceScoped: true } as RosterRow++ hostMock.requestProfile = undefined as never++ await expect(requestForBot(scoped, 'profiles.list', {})).rejects.toThrow(/Cannot route profiles\.list/)+ expect(hostMock.request).not.toHaveBeenCalled()++ hostMock.requestProfile = vi.fn()+ })++ it('coerces a JSON-RPC rejection into an Error with a string name (#94471)', async () => {+ // React 19 formats query errors with `(error.name || '').trim()`; a+ // numeric JSON-RPC `name` crashed the Routines pane and hid the cause.+ hostMock.request.mockRejectedValue({ code: -32000, message: 'profile busy', name: -32000 })++ const error = await requestForBot({ name: 'ops' }, 'cron.list', {}).catch((thrown: unknown) => thrown)++ expect(error).toBeInstanceOf(Error)+ expect(typeof (error as Error).name).toBe('string')+ expect((error as Error).message).toBe('profile busy')+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/row-helpers.test.ts b/apps/desktop/src/plugins/hermes-bots/row-helpers.test.tsnew file mode 100644index 00000000000..0e48e59e382--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/row-helpers.test.ts@@ -0,0 +1,239 @@+/**+ * The row-level reads a roster row is assembled from: who sent the last+ * message, what to call a generically-titled session, and whether a bot counts+ * as live right now.+ *+ * Two bug classes are pinned:+ * - #89484 — the bot-to-bot badge rendered the raw captured profile name, so+ * the primary profile surfaced as @default instead of @hermes;+ * - the "6d ago" class — canonical Bot Chats are hidden from session lists,+ * so a bot DM'd all day read as a week idle because its newest VISIBLE+ * session was a week old. Liveness keys off `botActivitySession`, and+ * kanban/tool workers count too (hermes-agent#90268): a profile grinding+ * through a 30-minute task must not read "3 hr ago" the whole time.+ */++import { describe, expect, it, vi } from 'vitest'++import {+ ACTIVE_WINDOW_S,+ activeBots,+ botCanonicalSessionId,+ botRowOwnsWorkspace,+ generatedSessionTitle,+ previewKind,+ rosterActivityMatches,+ workerActiveAt+} from './row-helpers'+import type { RosterRow } from './types'++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ return {+ atom,+ host: { state: { connectionId: { get: () => 'local' } } },+ queryClient: undefined,+ useQuery: vi.fn(),+ useValue: vi.fn()+ }+})++vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))++/** Gateway rows carry a session id on `last_session` / `worker_session` that+ * the plugin's `SessionPreview` type deliberately does not model. Fixtures+ * keep it so "the canonical id is never the last_session id" stays a real+ * assertion rather than one about a missing field. */+interface RowFixture extends Omit<Partial<RosterRow>, 'last_session' | 'worker_session'> {+ last_session?: { id?: string; last_active?: number; preview?: string }+ worker_session?: { id?: string; last_active?: number; source?: string }+}++const row = (bot: RowFixture) => bot as RosterRow++// Fixed clock so "inside the window" vs "stale" is deterministic.+const NOW = 1_000_000_000_000+const secondsAgo = (n: number) => NOW / 1000 - n++describe('previewKind classifies a roster preview', () => {+ const fromBot = (preview: null | string | undefined) => previewKind(preview).fromBot++ it('reads a plain chat preview as a human exchange, not a DM', () => {+ expect(fromBot('Can you check the vault sync?')).toBeNull()+ })++ it('parses the current 🤖 delivery prefix and the legacy agent shape', () => {+ expect(fromBot('Message from 🤖 manager (@manager): Learn-share: skill installed')).toBe('manager')+ expect(fromBot("Message from agent 'researcher': here is the paper")).toBe('researcher')+ })++ it('surfaces the primary profile as @hermes, never @default (#89484)', () => {+ expect(fromBot("Message from agent 'default': deploy is green")).toBe('hermes')+ expect(fromBot("Message from agent 'ops': deploy is green")).toBe('ops')+ })++ it('treats an empty or absent preview as not a DM', () => {+ expect(fromBot('')).toBeNull()+ expect(fromBot(undefined)).toBeNull()+ })+})++describe('generatedSessionTitle labels a generically-titled chat', () => {+ it('keeps a stored title that means something', () => {+ expect(generatedSessionTitle({ id: 's', last_active: 1, title: 'Weekly review' }, 'some preview')).toBe(+ 'Weekly review'+ )+ })++ it('invents a label from the preview for auto-assigned titles', () => {+ for (const title of ['Bot Chat', 'New chat', '']) {+ expect(generatedSessionTitle({ id: 's', last_active: 1, title }, 'The tailnet proxy binds 100.64.0.1')).toBe(+ 'The tailnet proxy binds 100.64.0.1'+ )+ }+ })++ it('strips the bot-to-bot delivery prefix before generating', () => {+ const label = generatedSessionTitle(+ { id: 's', last_active: 1, title: '' },+ 'Message from 🤖 manager (@manager): Learn-share: skill installed'+ )++ expect(label).toMatch(/Learn-share/)+ expect(label).not.toMatch(/Message from/)+ })++ it('caps the generated label so it fits the row', () => {+ const label = generatedSessionTitle(+ { id: 's', last_active: 1, title: '' },+ 'this is a very long preview that goes on and on and on about something or other entirely'+ )++ expect(label.length).toBeLessThanOrEqual(34)+ })+})++describe('the canonical session id everything core-keyed reads', () => {+ it('prefers the compression-lineage tip over the durable registry id', () => {+ expect(botCanonicalSessionId(row({ canonical_session: { id: 'root', last_active: 1, resolved_id: 'tip' } }))).toBe(+ 'tip'+ )+ expect(botCanonicalSessionId(row({ canonical_session: { id: 'root', last_active: 1 } }))).toBe('root')+ })++ it('is never last_session — that is a different conversation entirely', () => {+ expect(botCanonicalSessionId(row({ last_session: { id: 'scratch', last_active: 1 } }))).toBeNull()+ })+})++describe('which bots are working right now', () => {+ const roster = [+ row({ last_session: { id: 'a', last_active: secondsAgo(10) }, name: 'researcher' }),+ row({ last_session: { id: 'b', last_active: secondsAgo(400) }, name: 'scribe' }),+ row({ name: 'analyst' })+ ]++ it('includes the gateway-busy profile before its first response lands', () => {+ // analyst has no session at all — a busy turn must still show it.+ expect(activeBots(roster, 'analyst', 'busy', NOW).map(bot => bot.name)).toContain('analyst')+ })++ it('includes activity inside the liveness window and excludes activity outside it', () => {+ const names = activeBots(roster, 'default', 'open', NOW).map(bot => bot.name)++ expect(names).toContain('researcher')+ expect(names).not.toContain('scribe')+ // Output follows input order and never hides or reorders the full list.+ expect(names).toEqual(['researcher'])+ expect(roster).toHaveLength(3)+ })++ it('returns an empty list when nothing is active, and tolerates no roster', () => {+ expect(activeBots(roster.slice(1), 'default', 'open', NOW)).toEqual([])+ expect(activeBots(null, 'default', 'open', NOW)).toEqual([])+ expect(activeBots([], 'default', 'open', NOW)).toEqual([])+ })++ it('counts Bot Chat activity that last_session cannot see', () => {+ const bots = [+ row({+ canonical_session: { id: 'chat', last_active: secondsAgo(5) },+ last_session: { id: 'old', last_active: secondsAgo(6 * 86_400) },+ name: 'default'+ })+ ]++ expect(activeBots(bots, 'other', 'open', NOW).map(bot => bot.name)).toContain('default')+ })++ it('counts a live kanban/tool worker heartbeat (#90268)', () => {+ // The reported shape: last chat hours ago while the bot is mid-task.+ const working = row({+ last_session: { id: 'chat', last_active: secondsAgo(3 * 3600) },+ name: 'coding',+ worker_session: { id: 'w1', last_active: secondsAgo(30), source: 'kanban' }+ })++ expect(activeBots([working], 'other', 'open', NOW).map(bot => bot.name)).toContain('coding')+ expect(workerActiveAt(working, NOW)).toBe(true)+ })++ it('ignores a finished worker outside the liveness window', () => {+ const finished = row({+ last_session: { id: 'chat', last_active: secondsAgo(3 * 3600) },+ name: 'coding',+ worker_session: { id: 'w1', last_active: secondsAgo(3600), source: 'kanban' }+ })++ expect(activeBots([finished], 'other', 'open', NOW)).toEqual([])+ // Workers get a wider window than chat activity to bridge one missed+ // heartbeat — but not an hour's worth.+ expect(workerActiveAt(finished, NOW)).toBe(false)+ expect(ACTIVE_WINDOW_S).toBeGreaterThan(0)+ })+})++describe('the roster activity filter', () => {+ it('passes everything through with no filter', () => {+ expect(rosterActivityMatches({ activity: 0 }, null, NOW)).toBe(true)+ expect(rosterActivityMatches({ activity: 0 }, 'all', NOW)).toBe(true)+ })++ it('splits recent from older on the week boundary', () => {+ const week = 7 * 24 * 60 * 60 * 1000++ expect(rosterActivityMatches({ activity: NOW - week + 1000 }, 'recent', NOW)).toBe(true)+ expect(rosterActivityMatches({ activity: NOW - week - 1000 }, 'recent', NOW)).toBe(false)+ expect(rosterActivityMatches({ activity: NOW - week - 1000 }, 'older', NOW)).toBe(true)+ // A bot with no activity at all counts as older, never recent.+ expect(rosterActivityMatches({}, 'older', NOW)).toBe(true)+ })++ it('reads the live pulse for the active filter', () => {+ expect(rosterActivityMatches({ active: true }, 'active', NOW)).toBe(true)+ expect(rosterActivityMatches({ active: false }, 'active', NOW)).toBe(false)+ })+})++describe('which row owns the workspace highlight', () => {+ const bot = row({ connectionId: 'local', name: 'ops' })++ it('follows the explicit selection while no bot chat has focus', () => {+ expect(botRowOwnsWorkspace(bot, null, false, null, 'local::ops')).toBe(true)+ expect(botRowOwnsWorkspace(bot, null, false, null, 'local::other')).toBe(false)+ })++ it('follows the FOCUSED chat’s owner once a bot chat has focus', () => {+ // Tab/tile focus moves without swapping the socket, so keying this off+ // the gateway's home profile highlighted the wrong bot.+ const focused = { authoritative: true, connectionId: 'local', name: 'ops' }++ expect(botRowOwnsWorkspace(bot, null, true, focused, 'local::other')).toBe(true)+ expect(botRowOwnsWorkspace(bot, null, true, { ...focused, name: 'writer' }, 'local::ops')).toBe(false)+ })++ it('never highlights a bot row while a group room is active', () => {+ expect(botRowOwnsWorkspace(bot, 'team', false, null, 'local::ops')).toBe(false)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/skills-hub-picker.test.tsx b/apps/desktop/src/plugins/hermes-bots/skills-hub-picker.test.tsxnew file mode 100644index 00000000000..e8f5222106d--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/skills-hub-picker.test.tsx@@ -0,0 +1,152 @@+/**+ * The Skills Hub picker embeds the real hub page in an iframe; the page posts+ * `{type:'hermes-skill-pick'}` back and the plugin installs via skills.manage.+ *+ * The handler used to check only `event.origin`, so ANY window on the hub+ * origin — an OAuth popup that had navigated back there, for instance — could+ * drive an install while the picker was open, and whatever string it sent+ * reached skills.manage as the install identifier. Picks are now pinned to OUR+ * frame's contentWindow and the identifier is charset-checked.+ */++import type * as HermesSdk from '@hermes/plugin-sdk'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const HUB_ORIGIN = 'https://hermes-agent.nousresearch.com'++const mocks = vi.hoisted(() => ({+ notify: vi.fn(),+ notifyError: vi.fn(),+ request: vi.fn(async (_method: string, _params: Record<string, unknown>) => ({}))+}))++vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const original = await importOriginal<typeof HermesSdk>()++ return {+ ...original,+ host: { ...original.host, notify: mocks.notify, notifyError: mocks.notifyError, request: mocks.request }+ }+})++const { HubSkillsSection } = await import('./skills-hub')++interface PickMessage {+ identifier?: string+ name?: string+ type?: string+}++/** Mount the section with the hub browser open and hand back its frame. */+function openHubBrowser() {+ const { container } = render(<HubSkillsSection forProfile={null} />)++ fireEvent.click(screen.getByRole('button', { name: /browse the full hub/ }))++ const frame = container.querySelector('iframe')++ expect(frame).toBeTruthy()++ return frame as HTMLIFrameElement+}++function postPick(data: PickMessage, options: { origin?: string; source?: null | Window }) {+ window.dispatchEvent(+ new MessageEvent('message', {+ data,+ origin: options.origin ?? HUB_ORIGIN,+ source: options.source ?? null+ })+ )+}++function installCalls() {+ return mocks.request.mock.calls.filter(([, params]) => params.action === 'install')+}++beforeEach(() => {+ vi.clearAllMocks()+})++afterEach(() => {+ cleanup()+})++describe('hub pick messages', () => {+ it('installs the picked skill when it comes from our own frame', () => {+ const frame = openHubBrowser()++ postPick(+ { identifier: 'nous/web-research', name: 'Web Research', type: 'hermes-skill-pick' },+ {+ source: frame.contentWindow+ }+ )++ expect(installCalls()).toEqual([['skills.manage', { action: 'install', query: 'nous/web-research' }]])+ })++ it('regression: ignores a same-origin window that is NOT the picker frame', () => {+ openHubBrowser()++ // Same origin, different window — the OAuth-popup shape of the hole.+ postPick(+ { identifier: 'nous/web-research', name: 'Web Research', type: 'hermes-skill-pick' },+ {+ source: window+ }+ )++ expect(installCalls()).toEqual([])+ })++ it('ignores anything posted from another origin', () => {+ const frame = openHubBrowser()++ postPick(+ { identifier: 'nous/web-research', name: 'Web Research', type: 'hermes-skill-pick' },+ {+ origin: 'https://evil.example',+ source: frame.contentWindow+ }+ )++ expect(installCalls()).toEqual([])+ })++ it('regression: refuses identifiers outside the slug charset', () => {+ const frame = openHubBrowser()++ for (const identifier of ['../../etc/passwd', 'skill; rm -rf /', '-flag', 'name with spaces', '']) {+ postPick({ identifier, name: 'Web Research', type: 'hermes-skill-pick' }, { source: frame.contentWindow })+ }++ // The empty identifier falls back to `name`, which is also off-charset.+ expect(installCalls()).toEqual([])+ })++ it('ignores messages that are not a skill pick', () => {+ const frame = openHubBrowser()++ postPick({ identifier: 'nous/web-research', type: 'oauth-callback' }, { source: frame.contentWindow })+ postPick({ identifier: 'nous/web-research', type: 'hermes-skill-pick' }, { source: frame.contentWindow })++ // The second has no `name`, so it is not a complete pick either.+ expect(installCalls()).toEqual([])+ })++ it('stops listening once the hub browser is closed', () => {+ const frame = openHubBrowser()++ fireEvent.click(screen.getByRole('button', { name: /hide the hub browser/ }))+ postPick(+ { identifier: 'nous/web-research', name: 'Web Research', type: 'hermes-skill-pick' },+ {+ source: frame.contentWindow+ }+ )++ expect(installCalls()).toEqual([])+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/soul.test.ts b/apps/desktop/src/plugins/hermes-bots/soul.test.tsnew file mode 100644index 00000000000..813111ce3ab--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/soul.test.ts@@ -0,0 +1,192 @@+/**+ * The agent-to-agent messaging protocol section every SOUL has to keep.+ *+ * #16: a CUSTOM SOUL silently dropped the handoff protocol, which broke+ * @mentions for every customized bot. The protocol is therefore appended+ * idempotently — at create time, on save, and as a one-shot backfill for the+ * pre-Bot-Mode personas (`default` above all) that never went through+ * `composeSoul`.+ *+ * The escape hatch is the backend capability: once `profiles.list` reports+ * `bot_mode_protocol`, the gateway injects the protocol into every session's+ * system prompt and Bot Mode must stop writing to user SOUL files entirely —+ * a second copy in SOUL.md is duplicated prompt the user did not ask for.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RosterRow } from './types'++const { hostMock, serverInjects } = vi.hoisted(() => ({+ hostMock: { request: vi.fn() },+ serverInjects: { value: false }+}))++vi.mock('@hermes/plugin-sdk', () => ({ host: hostMock }))++vi.mock('./data', () => ({+ botHandle: (name: string) => (String(name).toLowerCase() === 'default' ? 'hermes' : name),+ // A live binding in the real module — useRoster flips it from the roster+ // response, so the mock has to be a getter too.+ get serverInjectsProtocol() {+ return serverInjects.value+ }+}))++const EXISTING_SOUL = `# Main agent++I am the default profile on this machine.++## Notes+- Execute directly.+`++const roster = [+ { description: 'main agent', name: 'default' },+ { description: 'research specialist', name: 'researcher' }+] as RosterRow[]++const sectionCount = (soul: string) => soul.split('## Messaging other agents').length - 1++async function loadSoul() {+ vi.resetModules()++ return import('./soul')+}++beforeEach(() => {+ vi.clearAllMocks()+ serverInjects.value = false+})++describe('appending the protocol to an existing SOUL', () => {+ it('appends once and never duplicates', async () => {+ const { ensureMessagingProtocol } = await loadSoul()+ const once = ensureMessagingProtocol(EXISTING_SOUL, 'default', roster)++ expect(sectionCount(once)).toBe(1)+ // Identity text is never overwritten.+ expect(once).toMatch(/I am the default profile on this machine/)+ expect(once).toMatch(/`researcher` — research specialist/)+ // The primary profile addresses itself by its callable alias.+ expect(once).toMatch(/@hermes/)+ expect(once).not.toMatch(/@default/)++ const twice = ensureMessagingProtocol(once, 'default', roster)++ expect(twice).toBe(once.trim())+ expect(sectionCount(twice)).toBe(1)+ })++ it('points at the real CLI verb, not the plural that does not exist', async () => {+ const { ensureMessagingProtocol } = await loadSoul()+ const soul = ensureMessagingProtocol('', 'default', roster)++ expect(soul).toMatch(/run `hermes profile list` for the LIVE/)+ expect(soul).not.toMatch(/hermes profiles list/)+ })++ it('seeds an empty SOUL with the section alone', async () => {+ const { ensureMessagingProtocol } = await loadSoul()++ expect(ensureMessagingProtocol('', 'ops', [])).toMatch(/^## Messaging other agents/)+ expect(ensureMessagingProtocol('', 'ops', [])).toMatch(/- \(none yet\)/)+ })+})++describe('composeSoul', () => {+ it('does not double-append when the custom SOUL already carries the protocol', async () => {+ const { composeSoul } = await loadSoul()++ const withProtocol = composeSoul({+ customSoul: '',+ description: 'literature review',+ name: 'researcher',+ roster,+ title: 'Researcher'+ })++ const cloned = composeSoul({ customSoul: withProtocol, name: 'researcher', roster })++ expect(sectionCount(cloned)).toBe(1)+ })+})++describe('one-shot backfill for profiles that predate the protocol', () => {+ it('describes every bot but only configures the ones missing the section', async () => {+ const calls: Array<{ method: string; payload: Record<string, string> }> = []++ hostMock.request.mockImplementation(async (method: string, payload: Record<string, string>) => {+ calls.push({ method, payload })++ if (method === 'profiles.describe') {+ return payload.name === 'researcher'+ ? { soul: '# Researcher\n\n## Messaging other agents\n' }+ : { soul: EXISTING_SOUL }+ }++ return { ok: true }+ })++ const { backfillMessagingProtocol } = await loadSoul()++ backfillMessagingProtocol(roster)+ await vi.waitFor(() => expect(calls.some(call => call.method === 'profiles.configure')).toBe(true))++ expect(+ calls+ .filter(call => call.method === 'profiles.describe')+ .map(call => call.payload.name)+ .sort()+ ).toEqual(['default', 'researcher'])++ const configures = calls.filter(call => call.method === 'profiles.configure')++ expect(configures).toHaveLength(1)+ expect(configures[0].payload.name).toBe('default')+ expect(configures[0].payload.soul).toMatch(/## Messaging other agents/)+ })++ it('does not hammer a gateway that fails the describe', async () => {+ hostMock.request.mockRejectedValue(new Error('older gateway'))++ const { backfillMessagingProtocol } = await loadSoul()++ backfillMessagingProtocol(roster)+ await vi.waitFor(() => expect(hostMock.request).toHaveBeenCalledTimes(2))++ backfillMessagingProtocol(roster)+ await vi.waitFor(() => expect(hostMock.request).toHaveBeenCalledTimes(2))+ })+})++describe('the bot_mode_protocol backend capability suppresses every SOUL write', () => {+ it('turns ensureMessagingProtocol into identity', async () => {+ serverInjects.value = true++ const { ensureMessagingProtocol } = await loadSoul()++ expect(ensureMessagingProtocol(EXISTING_SOUL, 'default', [])).toBe(EXISTING_SOUL.trim())+ })++ it('issues no RPC at all from the backfill', async () => {+ serverInjects.value = true++ const { backfillMessagingProtocol } = await loadSoul()++ backfillMessagingProtocol(roster)+ await Promise.resolve()++ expect(hostMock.request).not.toHaveBeenCalled()+ })++ it('leaves the section out of a generated identity SOUL', async () => {+ serverInjects.value = true++ const { composeSoul } = await loadSoul()++ expect(composeSoul({ customSoul: '', description: 'D', name: 'newbot', roster: [], title: 'T' })).not.toMatch(+ /## Messaging other agents/+ )+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/94478-mention-settle.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/94478-mention-settle.test.mjsdeleted file mode 100644index 827a2d6c04e..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/94478-mention-settle.test.mjs+++ /dev/null@@ -1,126 +0,0 @@-/**- * Regression tests for #94478 — a bot's @mention of a teammate inside its own- * reply never drives the cited bot; the room records "settled" instead.- *- * Mechanism (traced on 6ce7ab8-era main, apps/desktop/src/plugins/hermes-bots/plugin.js):- *- * `resolveGroupResponders` (L6441) scopes responder selection to entries- * SINCE THE LAST USER ENTRY. A member reply that @mentions a teammate lands- * AFTER that user entry, so the mention IS visible to the next round's- * selection — but only if the loop runs another round at all.- *- * The hole is the early exit at L7821: `if (spokeThisRound === 0) return`.- * That guard exists for the everyone-passed case, but it also fires when the- * round's responders had no NEW delta to read — e.g. every member already- * spoke and the only new log entry is the citing member's reply. The cited- * bot is in `mentioned`, but the loop exits before any further round can- * select it: the room settles with an unresolved handoff. The same happens- * when a cap (`GROUP_CHAT_MAX_ROUNDS` / `GROUP_CHAT_MAX_MESSAGES`) lands- * between the mention and the next round.- *- * Fix contract:- * 1. When a round produces zero spoken turns but the thread's tail contains- * an @mention of a member who has NOT yet answered it, drive one- * continuation round for exactly those cited members (still bounded by- * the GROUP_CHAT_MAX_* caps) instead of settling silently.- * 2. If settling must happen anyway (cap exhausted), record an activity- * entry naming the unaddressed handoff so the room does not LOOK- * finished while a called bot never answered.- */-import assert from 'node:assert/strict'-import test from 'node:test'--// Mirror of resolveGroupResponders' scoping rule (plugin.js L6441): mentions-// are collected from entries after the last user entry.-function mentionedSinceLastUser(log, parseMentions) {- let sinceLastUser = []-- for (let i = log.length - 1; i >= 0; i--) {- if (log[i].from.kind === 'user') {- sinceLastUser = log.slice(i)- break- }- }-- const mentioned = new Set()-- for (const entry of sinceLastUser) {- for (const name of parseMentions(entry.text)) {- mentioned.add(name)- }- }-- return mentioned-}--test('#94478: detects an unanswered member mention in the post-user tail', () => {- // Room state from the issue: user asks, member radar replies citing @hermes.- const log = [- { id: 1, from: { kind: 'user' }, text: 'kick this off' },- { id: 2, from: { kind: 'member', name: 'radar' }, text: 'done — @hermes please review' }- ]-- const mentioned = mentionedSinceLastUser(log, text => (text.includes('@hermes') ? ['hermes'] : []))-- // Pre-fix, the loop exits via `spokeThisRound === 0` / cap exhaustion before- // any round can act on this mention. The fix's detector must find it so a- // continuation round can be driven for exactly [hermes].- assert.ok(mentioned.has('hermes'), 'cited member must be detected as pending')-})--test('#94478: does not flag a handoff the cited member already answered', () => {- const log = [- { id: 1, from: { kind: 'user' }, text: 'kick this off' },- { id: 2, from: { kind: 'member', name: 'radar' }, text: 'done — @hermes please review' },- { id: 3, from: { kind: 'member', name: 'hermes' }, text: 'reviewed, all good' }- ]-- // hermes has a member entry AFTER the mentioning one — handoff resolved.- // The fix's detector must not re-drive an answered mention (that would loop).- const mentionIdx = log.findIndex(e => e.id === 2)- const answer = [...log].reverse().find(e => e.from.kind === 'member' && e.from.name === 'hermes')- const answerIdx = log.findIndex(e => answer && e.id === answer.id)-- assert.ok(answerIdx > mentionIdx, 'answer must postdate the mention')-})--// --- exit-path wiring contracts (salvage follow-up) --------------------------// The two tests above pin the detector's semantics in isolation; these pin the-// WIRING — the quiet-round exit must consult the detector before settling, and-// a cap-forced exit must be labelled distinctly from consensus settle.-import { readFileSync } from 'node:fs'--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--test('#94478: the quiet-round exit consults unaddressedGroupMentions before settling', () => {- const loopStart = pluginSource.indexOf('async function runGroupChatRounds')- assert.ok(loopStart >= 0, 'runGroupChatRounds must exist')-- const loop = pluginSource.slice(loopStart, pluginSource.indexOf('\n}', loopStart) + 2)-- // The spokeThisRound === 0 path may no longer settle unconditionally: it- // must call the detector and drive a bounded continuation round first.- assert.ok(- loop.includes('unaddressedGroupMentions(group, members, thread)'),- 'quiet-round exit must check for unanswered @mention handoffs before settling'- )- assert.ok(- loop.includes('GROUP_CHAT_MAX_CONTINUATIONS'),- 'continuation rounds must be bounded by GROUP_CHAT_MAX_CONTINUATIONS'- )-})--test('#94478: a cap-forced exit is labelled distinctly from consensus settle', () => {- const loopStart = pluginSource.indexOf('async function runGroupChatRounds')- const loop = pluginSource.slice(loopStart, pluginSource.indexOf('\n}', loopStart) + 2)-- // The finally must record the tracked exit kind, not a hardcoded 'settled'.- assert.ok(- /recordGroupActivity\(group, \{ kind: exitKind, member: null, thread \}\)/.test(loop),- 'the drive-end activity entry must use the tracked exit kind'- )- assert.ok(/exitKind = 'capped'/.test(loop), 'cap exits must set the capped exit kind')-- // And the activity vocabulary must know the new kind.- assert.ok(/\bcapped:\s*'/.test(pluginSource), "GROUP_ACTIVITY_LABELS must define 'capped'")-})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.mjsdeleted file mode 100644index 9660d13332a..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs+++ /dev/null@@ -1,162 +0,0 @@-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 loadActiveBotsSlice() {- 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;\nglobalThis.__botActivitySession = botActivitySession;`,- context- )-- return context-}--function loadActiveBots() {- return loadActiveBotsSlice().__activeBots-}--function loadBotActivitySession() {- return loadActiveBotsSlice().__botActivitySession-}--// 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)-})--// ── botActivitySession: canonical Bot Chat activity counts (hermes-agent "6d ago" bug) ──--test('botActivitySession picks the fresher canonical_session over a stale last_session', () => {- const botActivitySession = loadBotActivitySession()- const bot = {- // Canonical Bot Chat (hidden from session lists): messaged seconds ago.- canonical_session: { id: 'bot-chat', last_active: NOW / 1000 - 5, preview: 'fresh DM' },- // Newest VISIBLE session: 6 days old — what last_session alone reports.- last_session: { id: 'old-scratch', last_active: NOW / 1000 - 6 * 86400, preview: 'ancient' }- }- assert.equal(botActivitySession(bot).id, 'bot-chat')-})--test('botActivitySession keeps last_session when it is the fresher one', () => {- const botActivitySession = loadBotActivitySession()- const bot = {- canonical_session: { id: 'bot-chat', last_active: NOW / 1000 - 3600 },- last_session: { id: 'scratch', last_active: NOW / 1000 - 10 }- }- assert.equal(botActivitySession(bot).id, 'scratch')-})--test('botActivitySession degrades to whichever session summary exists on an older gateway', () => {- const botActivitySession = loadBotActivitySession()- assert.equal(botActivitySession({ last_session: { id: 'only', last_active: 1 } }).id, 'only')- assert.equal(botActivitySession({ canonical_session: { id: 'canonical', last_active: 1 } }).id, 'canonical')- assert.equal(botActivitySession({}), null)- assert.equal(botActivitySession(null), null)-})--test('activeBots counts Bot Chat activity that last_session cannot see', () => {- const activeBots = loadActiveBots()- const bots = [- {- name: 'default',- canonical_session: { last_active: NOW / 1000 - 5 },- last_session: { last_active: NOW / 1000 - 6 * 86400 }- }- ]- const names = activeBots(bots, 'other', 'open', NOW).map(bot => bot.name)- assert.ok(names.includes('default'), 'fresh canonical-chat activity must light the pulse dot')-})--test('row age label and recency sort key off botActivitySession, not last_session', () => {- // The "6d ago" regression: the timestamp/sort sites must not read- // bot.last_session directly anymore.- assert.match(source, /relativeTime\(rowAgeTs \* 1000\)/)- assert.match(source, /const lastMsg = \(botActivitySession\(bot\)\?\.last_active \|\| 0\) \* 1000/)- assert.doesNotMatch(source, /relativeTime\(last\.last_active \* 1000\)/)-})--// ── worker liveness: kanban/tool workers count as activity (#90268) ─────────--test('activeBots includes a bot whose kanban worker heartbeat is fresh', () => {- const activeBots = loadActiveBots()- const bots = [- {- name: 'coding',- // Last chat hours ago — the reported "3 hr ago while working" shape.- last_session: { last_active: NOW / 1000 - 3 * 3600 },- worker_session: { id: 'w1', source: 'kanban', last_active: NOW / 1000 - 30 }- }- ]- const names = activeBots(bots, 'other', 'open', NOW).map(bot => bot.name)- assert.ok(names.includes('coding'), 'live worker heartbeat must light ACTIVE NOW')-})--test('activeBots ignores a finished worker outside the liveness window', () => {- const activeBots = loadActiveBots()- const bots = [- {- name: 'coding',- last_session: { last_active: NOW / 1000 - 3 * 3600 },- worker_session: { id: 'w1', source: 'kanban', last_active: NOW / 1000 - 3600 }- }- ]- assert.deepEqual(activeBots(bots, 'other', 'open', NOW), [])-})\ No newline at end of filediff --git a/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjsdeleted file mode 100644index f085cba9393..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/activity-toasts.test.mjs+++ /dev/null@@ -1,99 +0,0 @@-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)- // The tracker keys watermarks off the REAL botActivitySession helper- // (defined later in plugin.js) — extract it so the harness can't drift.- const helperStart = source.indexOf('function botActivitySession(')- const helperEnd = source.indexOf('/** Bots that are working', helperStart)- assert.ok(helperStart >= 0 && helperEnd > helperStart, 'botActivitySession must remain extractable')- 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 } }- })(),- botRosterMeta: (bot, meta) => meta?.[bot.name] || null,- botSelectionKey: bot => bot.name,- displayName: bot => bot.name- }- const section = source- .slice(helperStart, helperEnd)- .concat('\n', 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'\)/)-})--test('Bot Chat opens pass the exported 60-second hydration budget', () => {- assert.match(source, /sdk\.BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS/)- assert.match(source, /hydrationTimeoutMs,/)-})--test('activity in the hidden canonical Bot Chat still badges (the "6d ago" class)', () => {- // The canonical Bot Chat is hidden from session lists, so last_session- // never advances when a DM lands there — only canonical_session does.- const t = loadTracker(false)- const at = ts => [- {- name: 'researcher',- last_session: { last_active: 100, preview: 'ancient scratch chat' },- canonical_session: { last_active: ts, preview: 'Message from writer: hi' }- }- ]- t.trackInboundActivity(at(150)) // seeding poll- t.trackInboundActivity(at(250)) // Bot Chat got a DM; last_session unchanged- assert.equal(t.$botUnread.get().researcher, true, 'hidden Bot Chat activity must set unread')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/blobatar-shapes.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/blobatar-shapes.test.mjsdeleted file mode 100644index cf15fcc4b48..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/blobatar-shapes.test.mjs+++ /dev/null@@ -1,110 +0,0 @@-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({ blobatarSvg } = {}) {- 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 sdkStub = new Proxy(- { blobatarSvg },- { get: (target, key) => (key in target ? target[key] : undefined) }- )- 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 } } },- sdk: sdkStub- }- 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(`-globalThis.__blob = { isBlobShape, parseBlobShape, blobShapeString, blobMarkup, BLOB_KINDS, BLOB_KIND_TRAIT };-`)- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return context.__blob-}--test('blob shape strings round-trip through parse/build', () => {- const b = load()-- assert.equal(b.isBlobShape('blobatar'), true)- assert.equal(b.isBlobShape('blobatar:seed123'), true)- assert.equal(b.isBlobShape('blobatar::sun'), true)- assert.equal(b.isBlobShape('circle'), false)- assert.equal(b.isBlobShape(undefined), false)-- // Unlocked: seed follows the name.- assert.equal(JSON.stringify(b.parseBlobShape('blobatar', 'inbox-triage')), JSON.stringify({ seed: 'inbox-triage', seedPart: '', kind: '' }))- // Locked seed.- assert.equal(JSON.stringify(b.parseBlobShape('blobatar:abc123', 'inbox-triage')), JSON.stringify({ seed: 'abc123', seedPart: 'abc123', kind: '' }))- // Pinned silhouette, unlocked seed.- assert.equal(JSON.stringify(b.parseBlobShape('blobatar::cloud', 'inbox-triage')), JSON.stringify({ seed: 'inbox-triage', seedPart: '', kind: 'cloud' }))- // Unknown silhouette is ignored, never trusted.- assert.equal(b.parseBlobShape('blobatar:abc:mystery', 'x').kind, '')-- assert.equal(b.blobShapeString('', ''), 'blobatar')- assert.equal(b.blobShapeString('abc', ''), 'blobatar:abc')- assert.equal(b.blobShapeString('abc', 'sun'), 'blobatar:abc:sun')- assert.equal(b.blobShapeString('', 'sun'), 'blobatar::sun')-})--test('every silhouette has a trait position inside its frozen band', () => {- const b = load()- const bands = {- round: [0, 0.22], organic: [0.22, 0.48], boxy: [0.48, 0.60], capsule: [0.60, 0.70],- nub: [0.70, 0.79], cloud: [0.79, 0.86], droplet: [0.86, 0.915], hexagon: [0.915, 0.95],- sun: [0.95, 0.98], triangle: [0.98, 1]- }-- for (const kind of b.BLOB_KINDS) {- const v = b.BLOB_KIND_TRAIT[kind]- assert.equal(typeof v, 'number', kind)- assert.ok(v >= bands[kind][0] && v < bands[kind][1], `${kind} trait ${v} outside band`)- }-})--test('blobMarkup renders via the SDK export, tags data-bot-face, pins traits', () => {- const calls = []- const b = load({- blobatarSvg: (seed, opts) => {- calls.push({ seed, opts })- return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>'- }- })-- const markup = b.blobMarkup('blobatar', 'inbox-triage', 56)- assert.ok(markup.startsWith('<svg data-bot-face="inbox-triage" '), 'roster PNG backfill needs the data-bot-face tag')- assert.equal(calls[0].seed, 'inbox-triage')- assert.equal(calls[0].opts.size, 56)- assert.equal('traits' in calls[0].opts, false)-- b.blobMarkup('blobatar:abc:sun', 'inbox-triage', 32)- assert.equal(calls[1].seed, 'abc')- assert.equal(calls[1].opts.traits.shape, b.BLOB_KIND_TRAIT.sun)-})--test('blobMarkup degrades to null when the SDK lacks the export or the renderer throws', () => {- const withoutSdk = load()- assert.equal(withoutSdk.blobMarkup('blobatar', 'x', 32), null)-- const throwing = load({- blobatarSvg: () => {- throw new Error('boom')- }- })- assert.equal(throwing.blobMarkup('blobatar', 'x', 32), null)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-attention-badge.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-attention-badge.test.mjsdeleted file mode 100644index 71ec3e1be70..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-attention-badge.test.mjs+++ /dev/null@@ -1,157 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Needs-attention badge (#93091 item 3): background bot failures whose class-// is attention-worthy (auth, quota, missing config, blocked) badge the roster-// tile; transient failures (rate limit, server error, timeout) never do; the-// bot's next good turn clears the badge. Display-only state — hooks live at-// the relay deliver reply and the group member turn boundary, and hidden bots-// keep their entry (hiding is roster-display-only).--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--/** Evaluate just the delimited needs-attention helper section in a bare vm- * context (same slice-and-eval approach as the other pure-helper tests). */-function loadHelpers() {- const start = pluginSource.indexOf('const BOT_ATTENTION_CLASSES')- const end = pluginSource.indexOf('/** Last good cron list')- assert.ok(start > -1 && end > start, 'needs-attention helper section exists')-- 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 }- vm.createContext(context)-- return vm.runInContext(- `${pluginSource.slice(start, end)}-;({ BOT_ATTENTION_CLASSES, BOT_ATTENTION_HINTS, attentionReasonFromError, $botAttention, noteBotAttention, clearBotAttention })`,- context- )-}--test('classifier: reason codes pass through; matches the #93091 item-1 enum', () => {- const { BOT_ATTENTION_CLASSES, attentionReasonFromError } = loadHelpers()-- assert.deepEqual(- [...BOT_ATTENTION_CLASSES].sort(),- ['agent_blocked', 'missing_config', 'provider_auth_or_access', 'provider_quota_limit']- )-- for (const code of BOT_ATTENTION_CLASSES) {- assert.equal(attentionReasonFromError(code), code)- }-})--test('classifier: raw-text fallback maps current gateway error strings', () => {- const { attentionReasonFromError } = loadHelpers()-- // The anthropic 401 shape observed on current main.- assert.equal(- attentionReasonFromError(- 'Error code: 401 - {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}'- ),- 'provider_auth_or_access'- )- assert.equal(- attentionReasonFromError('No LLM provider configured. Run hermes model to pick one.'),- 'missing_config'- )- assert.equal(attentionReasonFromError('No access token found for profile'), 'missing_config')- assert.equal(attentionReasonFromError('Your account is out of funds'), 'provider_quota_limit')- assert.equal(attentionReasonFromError('quota exceeded for this billing period'), 'provider_quota_limit')- assert.equal(attentionReasonFromError('agent is blocked awaiting approval'), 'agent_blocked')-})--test('classifier: transient classes never badge', () => {- const { attentionReasonFromError } = loadHelpers()-- for (const text of [- 'Rate limit exceeded, retry shortly',- 'Error code: 429 - too many requests',- '500 Internal Server Error',- 'upstream 503 service unavailable',- 'the model is overloaded, try again',- 'request timed out after 180s',- 'temporarily unavailable',- '',- null,- undefined- ]) {- assert.equal(attentionReasonFromError(text), null, `expected null for ${JSON.stringify(text)}`)- }-})--test('lifecycle: set on classified failure, latest wins, cleared on success', () => {- const { $botAttention, noteBotAttention, clearBotAttention } = loadHelpers()-- // Transient failure sets nothing.- noteBotAttention('radar', 'Rate limit exceeded')- assert.deepEqual(Object.keys($botAttention.get()), [])-- // Classified failure badges the bot with reason + timestamp + snippet.- noteBotAttention('radar', 'Error code: 401 authentication_error')- const first = $botAttention.get().radar- assert.equal(first.reason, 'provider_auth_or_access')- assert.ok(first.at > 0)- assert.match(first.message, /401/)-- // A later failure for the same bot merges — latest wins.- noteBotAttention('radar', 'No LLM provider configured')- assert.equal($botAttention.get().radar.reason, 'missing_config')-- // Other bots are independent.- noteBotAttention('dixie', 'quota exceeded')- assert.equal($botAttention.get().dixie.reason, 'provider_quota_limit')-- // The next good turn clears exactly that bot.- clearBotAttention('radar')- assert.equal($botAttention.get().radar, undefined)- assert.equal($botAttention.get().dixie.reason, 'provider_quota_limit')-- // Clearing an unbadged bot is a no-op.- clearBotAttention('radar')- clearBotAttention('')- assert.equal($botAttention.get().dixie.reason, 'provider_quota_limit')-})--test('hooks: relay delivery and group member turns note/clear attention', () => {- // Relay drain: deliver success clears, deliver failure notes.- const drain = pluginSource.slice(- pluginSource.indexOf('async function drainRelayOutboxes'),- pluginSource.indexOf('function startBotRelay')- )- assert.match(drain, /clearBotAttention\(attentionKey\)/)- // #93091: the drain prefers the typed reason from bot_relay.deliver's- // error.data over free-text re-parsing, and forwards it to the reply.- assert.match(drain, /noteBotAttention\(attentionKey, reason \|\| error\?\.message \|\| error\)/)- assert.match(drain, /\.\.\.\(reason \? \{ reason \} : \{\}\)/)-- // Group member turn boundary: failure notes under the member key; a real- // reply clears it. Typed gateway reasons take precedence over text parsing.- assert.match(- pluginSource,- /noteBotAttention\(groupMemberKey\(member\), reason \|\| error\?\.message \|\| error\)/- )- assert.match(pluginSource, /clearBotAttention\(groupMemberKey\(member\)\)/)-})--test('render: roster row shows an amber warning glyph with a per-class hint', () => {- assert.match(pluginSource, /BOT_ATTENTION_HINTS\[attention\.reason\]/)- assert.match(pluginSource, /name: 'warning'/)- // Lookup covers all three key shapes so relay- and group-recorded state- // renders, including local/unannotated rows keyed by the ACTIVE connection.- assert.match(pluginSource, /attentionByKey\[botSelectionKey\(bot\)\] \|\|/)- assert.match(pluginSource, /attentionByKey\[botRosterKey\(bot\)\] \|\|/)- assert.match(pluginSource, /attentionByKey\[`\$\{bot\?\.connectionId \|\| activeConnectionId\}::\$\{bot\?\.name \|\| 'default'\}`\]/)- // Hint copy for every class.- assert.match(pluginSource, /Sign in again for this profile/)- assert.match(pluginSource, /Quota or balance exhausted/)- assert.match(pluginSource, /Provider not configured — run hermes model/)- assert.match(pluginSource, /Bot is blocked — see its last message/)-})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.mjsdeleted file mode 100644index 63c58f0d14a..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-delete.test.mjs+++ /dev/null@@ -1,226 +0,0 @@-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({ activeConnectionId = 'local', activeProfile = 'default', sdkDeleteProfile = false } = {}) {- const requests = []- const sdkDeletes = []- const invalidations = []- const newChats = []- const stored = []- const storageOps = []- 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: { get: () => activeProfile, listen: () => undefined },- connectionId: { get: () => activeConnectionId, listen: () => undefined },- gateway: { listen: () => undefined }- },- newChat: profile => newChats.push(profile),- ...(sdkDeleteProfile- ? {- deleteProfile: async profile => {- sdkDeletes.push(profile)- }- }- : {}),- 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,- remove: key => storageOps.push({ op: 'remove', key }),- set: (key, value) => {- stored.push({ key, value })- storageOps.push({ op: 'set', key, value })- }- },- register: () => undefined- })- return { context, requests, sdkDeletes, invalidations, newChats, stored, storageOps }-}--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: source-scoped deletion preserves the route targetProfile', async () => {- const { context, sdkDeletes } = load({ sdkDeleteProfile: true })- const route = {- connectionId: 'source-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'backend-worker'- }-- await context.__delete.deleteBot({ name: 'worker', sourceScoped: true, route })-- assert.deepEqual(JSON.parse(JSON.stringify(sdkDeletes)), [route])-})--test('unit: deleting same-name bot on another connection keeps the active chat', async () => {- const { context, newChats } = load({- activeConnectionId: 'source-b',- activeProfile: 'worker',- sdkDeleteProfile: true- })-- await context.__delete.deleteBot({- name: 'worker',- sourceScoped: true,- route: {- connectionId: 'source-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'worker'- }- })-- assert.deepEqual(newChats, [])-})--test('unit: source-scoped deletion commits bot-meta-v2 atomically', async () => {- const { context, storageOps } = load({ sdkDeleteProfile: true })- const route = {- connectionId: 'source-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'backend-worker'- }- const key = 'source-a::worker'- context.__delete.$botMeta.set({- [key]: { title: 'Worker' },- 'source-a::writer': { title: 'Writer' }- })-- await context.__delete.deleteBot({- name: 'worker',- sourceScoped: true,- route- })-- assert.deepEqual(- JSON.parse(JSON.stringify(storageOps.slice(-3))),- [- { op: 'remove', key: 'bot-meta-v2-migrated' },- {- op: 'set',- key: 'bot-meta-v2',- value: { 'source-a::writer': { title: 'Writer' } }- },- { op: 'set', key: 'bot-meta-v2-migrated', value: true }- ]- )-})--test('unit: an alias targeting backend default is rejected before deletion', async () => {- const { context, sdkDeletes, requests } = load({ sdkDeleteProfile: true })-- await assert.rejects(- context.__delete.deleteBot({- name: 'worker',- sourceScoped: true,- route: {- connectionId: 'source-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'default'- }- }),- /default profile cannot be deleted/i- )-- assert.deepEqual(sdkDeletes, [])- assert.equal(requests.some(request => request.method === 'cli.exec'), false)-})--test('unit: source-scoped deletion without host.deleteProfile fails closed without CLI execution', async () => {- const { context, requests } = load()-- await assert.rejects(- context.__delete.deleteBot({- name: 'worker',- sourceScoped: true,- route: {- connectionId: 'source-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'worker'- }- }),- /source-scoped profile deletion requires host\.deleteProfile/i- )-- assert.equal(requests.some(request => request.method === 'cli.exec'), false)-})--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' })-- // The load-time hide sweep (hideOwnedBotSessions/sweepBotProfileSessions)- // may interleave its own profiles.list / session.* traffic — filter to the- // delete path's request.- const exec = requests.filter(r => r.method === 'cli.exec')- assert.deepEqual(JSON.parse(JSON.stringify(exec[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, /isDefaultBot\(bot\) \? 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.mjsdeleted file mode 100644index be07ef5d435..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-asset-sync.test.mjs+++ /dev/null@@ -1,91 +0,0 @@-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.mjsdeleted file mode 100644index 4da93318b08..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-hydrate.test.mjs+++ /dev/null@@ -1,91 +0,0 @@-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 new Promise(resolve => setTimeout(resolve, 0))-- 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.mjsdeleted file mode 100644index 9451b72a57a..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-persistence.test.mjs+++ /dev/null@@ -1,99 +0,0 @@-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,/)- 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.mjsdeleted file mode 100644index e33a5be108f..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-meta-sync.test.mjs+++ /dev/null@@ -1,139 +0,0 @@-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,- noteBotMetaWrite,- saveBotMeta,- 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('regression: authoritative groups remove a stale local legacy group projection', () => {- const writes = []- const sync = load()- sync.set({ researcher: { groups: ['Old'], group: 'Old', title: 'Researcher' } })- sync.setPluginCtx({ storage: { set: (key, value) => writes.push({ key, value }) } })-- sync.mergeServerMeta([- {- name: 'researcher',- ui_meta: { 'hermes-bots': { groups: [], title: 'Researcher' } }- }- ])-- const current = sync.get().researcher- assert.deepEqual(current.groups, [])- assert.equal(Object.hasOwn(current, 'group'), false)- assert.equal(Object.hasOwn(writes.at(-1).value.researcher, 'group'), 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)-})--test('regression (#disband-resurrection): a roster snapshot fetched BEFORE a local write cannot overlay it back', async () => {- const writes = []- const sync = load()- sync.set({ builder: { groups: ['Team'], group: 'Team', title: 'Builder' } })- sync.setPluginCtx({ storage: { set: (key, value) => writes.push({ key, value }) } })-- // Snapshot fetched now — its ui_meta still names the group.- const staleFetchedAt = Date.now()- const staleRow = { name: 'builder', ui_meta: { 'hermes-bots': { groups: ['Team'], group: 'Team', title: 'Builder' } } }-- // Disband path: saveBotMeta removes the membership AFTER the fetch.- await new Promise(resolve => setTimeout(resolve, 5))- await sync.saveBotMeta('builder', { groups: [], group: null })- assert.deepEqual(sync.get().builder.groups, [])-- // The stale snapshot must NOT resurrect the membership...- sync.mergeServerMeta([staleRow], staleFetchedAt)- assert.deepEqual(sync.get().builder.groups, [])- assert.deepEqual(writes.at(-1).value.builder.groups, [])-- // ...but a FRESH snapshot (fetched after the write) still gets the last- // word — server truth wins once it actually post-dates the local change.- sync.mergeServerMeta([staleRow], Date.now() + 5)- assert.deepEqual(sync.get().builder.groups, ['Team'])-})--test('compatibility: mergeServerMeta without fetchedAt overlays as before (no fence)', async () => {- const sync = load()- sync.set({})- sync.setPluginCtx({ storage: { set: () => undefined } })-- await sync.saveBotMeta('builder', { groups: [], group: null })- sync.mergeServerMeta([{ name: 'builder', ui_meta: { 'hermes-bots': { groups: ['Team'] } } }])-- assert.deepEqual(sync.get().builder.groups, ['Team'])-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-open-focus-identity.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-open-focus-identity.test.mjsdeleted file mode 100644index 65b0c42aca8..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-open-focus-identity.test.mjs+++ /dev/null@@ -1,68 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--// First-click home bounce (community report, Aug 2026): clicking a bot whose-// canonical Bot Chat had been COMPRESSED landed on the Bots home instead of-// the chat; only a second click got through. Root cause: openRosterBot-// claimed the center with the durable registry id, but the session-focus-// edge that the open itself fired reports the compression-lineage TIP —-// releaseStaleOpenBotChat compared tip !== registry id, called the claim-// stale, released it, and the home reasserted over the freshly opened chat.-// The second click "worked" only because the tip was already focused, so no-// new focus edge fired to sabotage it.-//-// Contract pinned here (source-shape):-// - openBotCanonicalChat returns BOTH identities (registryId + openedId);-// - the $openBotChat claim stores openedSessionId alongside openedRegistryId;-// - releaseStaleOpenBotChat keeps the claim when the focused id matches-// EITHER identity, and still releases on a genuinely foreign session.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--test('canonical open returns both the registry row and the opened tip', () => {- const fn = pluginSource.slice(- pluginSource.indexOf('async function openBotCanonicalChat'),- pluginSource.indexOf('async function prepareBotSource')- )- assert.match(fn, /registryId: String\(existing\.id\)/)- assert.match(fn, /openedId: String\(openedId\)/)-})--test('the open claim carries the opened session id', () => {- const fn = pluginSource.slice(- pluginSource.indexOf('async function openRosterBot'),- pluginSource.indexOf('function displayName')- )- assert.match(fn, /openedSessionId: opened\.openedId/)-})--test('focus on either owned identity keeps the claim; foreign focus releases', () => {- const start = pluginSource.indexOf('function releaseStaleOpenBotChat')- const body = pluginSource.slice(start, pluginSource.indexOf('\n}', start) + 2)- // executable check: evaluate the function against a stub store- let stored = null- const $openBotChat = {- get: () => stored,- set: value => {- stored = value- }- }- const release = new Function('$openBotChat', `${body}; return releaseStaleOpenBotChat`)($openBotChat)-- // compressed chat: claim carries registry 'reg-1' and tip 'tip-9'- stored = { key: 'k', openedRegistryId: 'reg-1', openedSessionId: 'tip-9' }- release('tip-9') // the focus edge the open itself fires- assert.ok(stored, 'tip focus must NOT release the claim (first-click bounce)')-- release('reg-1')- assert.ok(stored, 'registry-id focus must not release either')-- release('other-session')- assert.equal(stored, null, 'a genuinely foreign session releases the claim')-- // legacy draft claim (no ids): any focused session releases- stored = { key: 'k', openedRegistryId: '' }- release('any')- assert.equal(stored, null)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bot-relay.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bot-relay.test.mjsdeleted file mode 100644index d7b8cfae621..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bot-relay.test.mjs+++ /dev/null@@ -1,80 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--// The cross-connection bot relay (Aug 2026 ruling: connections ARE the peer-// set). Source-shape contracts:-// - both relay loops exist, start in register(), and stop via ctx.onDispose;-// - the roster loop pushes bot_relay.roster.sync with agents from OTHER-// connections only;-// - the drain loop wires drain → deliver → reply, and posts an error reply-// when the target connection is gone (waiter must never dangle);-// - the remote-row toast no longer tells users messaging is device-local;-// - the middleware note carries the message_agent target for cross--// connection rows instead of implying they're unreachable.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--test('relay loops start in register() and stop on dispose', () => {- assert.match(pluginSource, /startBotRelay\(\)/)- assert.match(pluginSource, /ctx\.onDispose\(stopBotRelay\)/)- // teardown really clears both timers- const stop = pluginSource.slice(pluginSource.indexOf('function stopBotRelay'))- // 800-char window: stopBotRelay grew a retention release (#93594) ahead of- // the timer teardown it also must keep doing.- assert.match(stop.slice(0, 800), /clearInterval\(relayRosterTimer\)/)- assert.match(stop.slice(0, 800), /clearInterval\(relayDrainTimer\)/)-})--test('roster loop syncs OTHER connections agents to each gateway', () => {- const sync = pluginSource.slice(- pluginSource.indexOf('async function syncRelayRosters'),- pluginSource.indexOf('async function drainRelayOutboxes')- )- assert.match(sync, /bot_relay\.roster\.sync/)- assert.match(sync, /id !== connection\.id/)-})--test('roster loop never conflates a transient fetch failure with an empty connection', () => {- // relayAgentsOn signals failure as null (not []) so a live machine whose- // profiles.list blips is not pushed as absent — the gateway-side liveness- // check reads "absent from a fresh roster" as offline and would refuse- // enqueues with a false runtime_offline (#93091 item 2).- const fetch = pluginSource.slice(- pluginSource.indexOf('async function relayAgentsOn'),- pluginSource.indexOf('async function syncRelayRosters')- )- assert.match(fetch, /return null/)- assert.doesNotMatch(fetch.slice(fetch.indexOf('catch')), /return \[\]/)-- // syncRelayRosters falls back to the last good rows on failure and prunes- // the cache for connections genuinely gone from profileRoutes.- const sync = pluginSource.slice(- pluginSource.indexOf('async function syncRelayRosters'),- pluginSource.indexOf('async function drainRelayOutboxes')- )- assert.match(sync, /agents === null/)- assert.match(sync, /relayAgentsCache\.get\(connection\.id\)/)- assert.match(sync, /relayAgentsCache\.delete\(id\)/)-})--test('drain loop wires drain → deliver → reply with error fallback', () => {- const drain = pluginSource.slice(- pluginSource.indexOf('async function drainRelayOutboxes'),- pluginSource.indexOf('function startBotRelay')- )- assert.match(drain, /bot_relay\.outbox\.drain/)- assert.match(drain, /bot_relay\.deliver/)- assert.match(drain, /bot_relay\.reply/)- // a missing target connection still posts a reply (error) for the waiter- assert.match(drain, /is not connected to this Desktop right now/)-})--test('remote-row dead-end toast is gone (rows open; relay carries DMs)', () => {- assert.doesNotMatch(pluginSource, /Gateway stays on this device/)-})--test('middleware note names the cross-connection message_agent target', () => {- assert.match(pluginSource, /message_agent target: "\$\{target\}"/)- assert.match(pluginSource, /agents on other connected machines are reachable too/)-})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.mjsdeleted file mode 100644index b7269961f0f..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/bots-search.test.mjs+++ /dev/null@@ -1,95 +0,0 @@-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 = { botActivitySession: bot => bot?.canonical_session || bot?.last_session || null }- 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('bot search also matches roles, message previews, and gateway labels', () => {- const filterBots = loadFilter()- const richerRoster = [- {- name: 'reviewer',- connectionLabel: 'Work Studio',- description: 'Release quality and compliance',- last_session: { preview: 'Checked the deployment checklist' }- },- { name: 'writer', description: 'Editorial support' }- ]-- assert.equal(filterBots(richerRoster, {}, 'compliance')[0].name, 'reviewer')- assert.equal(filterBots(richerRoster, {}, 'deployment checklist')[0].name, 'reviewer')- assert.equal(filterBots(richerRoster, {}, 'work studio')[0].name, 'reviewer')-})--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,- /const showRosterSearch =\s*gatewayOptions\.length > 1 \|\| rosterItemCount >= BOT_ROSTER_SEARCH_THRESHOLD/- )- assert.match(source, /jsx\(SearchField,\s*\{[\s\S]*?placeholder: 'Search bots and group chats…'/)- assert.match(source, /query \? 'opacity-100!' : 'opacity-50 focus-within:opacity-100'/)- assert.match(source, /placeholder:text-\(--ui-text-tertiary\)/)- assert.match(source, /children: jsx\(Codicon, \{ name: 'list-filter' \}\)/)- assert.match(source, /'aria-live': 'polite'/)- assert.match(source, /No bots or group chats match “\$\{query\.trim\(\)\}”/)- assert.match(source, /const initialRosterLoading = !data && !error && roster\.length === 0/)- assert.match(source, /\(isLoading \|\| initialRosterLoading\) && !roster\.length/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-on-conflict.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-on-conflict.test.mjsdeleted file mode 100644index 94fa018afa9..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-adopt-on-conflict.test.mjs+++ /dev/null@@ -1,87 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// ADOPT-BEFORE-MINT (#92473 part 2): between the registry miss and our eager-// session.title write, another writer can take the canonical title (peer dm-// minting server-side, a second machine, cross-connection sync). UNIQUE(title)-// rejects our write with "already in use". Before this fix that rejection was-// read as "old gateway" and the compat path prompted into OUR stray lazy-// session — forking the forever chat. Now the mint re-consults the registry-// and adopts the winner; the stray zero-message session is abandoned to the-// gateway's pruner.--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 context = {- host: { openSession, request },- backendTargetProfile: (route, name) => route?.targetProfile || name,- botOwner: name => (typeof name === 'string'- ? { bot: { name }, key: name, name, route: null }- : { bot: name, key: name?.name, name: name?.name, route: name?.route || null }),- requestForBot: (_bot, method, params) => context.host.request(method, params),- botWorkspaceOwnerKey: bot => String(bot?.name || bot || ''),- 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-adopt.js' })- return { ...context.__canonical }-}--test('title-uniqueness rejection adopts the racing winner instead of forking', async () => {- const events = []- let lists = 0- const runtime = loadCanonicalCreation({- openSession: async id => events.push(`open:${id}`),- request: async method => {- events.push(method)- if (method === 'session.list') {- lists += 1- // First consult: registry miss (this is why we mint at all). Second- // consult (after the conflict): the racing winner exists.- if (lists === 1) return { sessions: [] }- return { sessions: [{ id: 'winner-1', resolved_id: 'winner-1', title: 'Bot Chat', message_count: 3 }] }- }- if (method === 'session.create') return { stored_session_id: 'stray-1', session_id: 'rt-stray' }- if (method === 'session.title') {- throw new Error("Title 'Bot Chat' is already in use by session winner-1")- }- return {}- }- })-- assert.equal(await runtime.createCanonicalChat('ops'), 'winner-1')- // The winner is opened; the stray is never prompted into or opened.- assert.ok(events.includes('open:winner-1'), `winner opened (events: ${events})`)- assert.ok(!events.includes('prompt.submit'), 'no prompt into the stray session')- assert.ok(!events.includes('open:stray-1'), 'stray session never mounted')-})--test('a NON-conflict title failure still takes the compat path (old gateways)', async () => {- const events = []- const runtime = loadCanonicalCreation({- openSession: async id => events.push(`open:${id}`),- request: async (method) => {- events.push(method)- if (method === 'session.list') return { sessions: [] }- if (method === 'session.create') return { stored_session_id: 'stored-1', session_id: 'rt-1' }- if (method === 'session.title') throw new Error('unknown method')- return {}- }- })-- assert.equal(await runtime.createCanonicalChat('ops'), 'stored-1')- // Old gateway: eager title unsupported → the kickoff persists the lazy row.- assert.ok(events.includes('prompt.submit'), 'compat kickoff persists the session')- // Only the initial registry consult — a plain failure must not re-list.- assert.equal(events.filter(e => e === 'session.list').length, 1)-})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.mjsdeleted file mode 100644index bf3d251cb47..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs+++ /dev/null@@ -1,168 +0,0 @@-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 context = {- host: { openSession, request },- backendTargetProfile: (route, name) => route?.targetProfile || name,- botOwner: name => (typeof name === 'string'- ? { bot: { name }, key: name, name, route: null }- : { bot: name, key: name?.name, name: name?.name, route: name?.route || null }),- botWorkspaceOwnerKey: bot => `bot:local::${bot.name}`,- requestForBot: (_bot, method, params) => context.host.request(method, params),- 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 }-}--test('regression: creation materializes and titles the lazy row before opening it', async () => {- const events = []- const runtime = loadCanonicalCreation({- openSession: async id => events.push(`open:${id}`),- request: async (method, params) => {- events.push(method)- if (method === 'session.create') return { stored_session_id: 'stored-1', session_id: 'runtime-1' }- if (method === 'session.title') {- // vm-realm objects fail assert.deepEqual on prototype identity —- // compare via JSON.stringify (harness contract). A throw here is- // NOT inert: createCanonicalChat reads it as "eager title- // unsupported" and falls back to the compat kickoff.- assert.equal(JSON.stringify(params), JSON.stringify({ session_id: 'runtime-1', title: 'Bot Chat' }))- }- return {}- }- })-- // No kickoff option: the click-path mint. The eager title write persists- // the row, so NO intro turn fires — the user speaks first (ScottFive).- assert.equal(await runtime.createCanonicalChat('ops'), 'stored-1')- assert.deepEqual(events, [- 'session.list',- 'session.create',- 'session.title',- 'open:stored-1'- ])-})--test('New Agent creation (kickoff: true) still sends the one intro turn', async () => {- const events = []- const runtime = loadCanonicalCreation({- openSession: async id => events.push(`open:${id}`),- request: async (method, params) => {- events.push(method)- if (method === 'session.create') return { stored_session_id: 'stored-1', session_id: 'runtime-1' }- if (method === 'prompt.submit') {- assert.equal(params.session_id, 'runtime-1')- }- return {}- }- })-- assert.equal(await runtime.createCanonicalChat('ops', { kickoff: true }), 'stored-1')- assert.deepEqual(events, [- 'session.list',- 'session.create',- 'session.title',- 'open:stored-1',- 'prompt.submit'- ])-})--test('compatibility: navigation retries after kickoff when eager title persistence is unavailable', 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 === 'session.title') throw new Error('unknown method')- 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'])-})--test('regression: a failed intro still returns the created registry row', async () => {- const runtime = loadCanonicalCreation({- openSession: async () => undefined,- request: async method => {- if (method === 'session.create') return { stored_session_id: 'new-bot-chat', session_id: 'rt-1' }- if (method === 'prompt.submit') throw new Error('gateway timeout')- return {}- }- })-- // The chat exists under the canonical title — the next click finds it by- // NAME (the registry), so a failed kickoff can never orphan or fork it.- assert.equal(await runtime.createCanonicalChat('newbie', { kickoff: true }), 'new-bot-chat')-})--test('a superseded roster open may create the canonical row but never navigate it', async () => {- const opens = []- let current = true- const runtime = loadCanonicalCreation({- openSession: async (id, options) => opens.push({ id, options }),- request: async method => {- if (method === 'session.create') {- current = false- return { stored_session_id: 'new-stored', session_id: 'new-runtime' }- }- return {}- }- })-- assert.equal(await runtime.createCanonicalChat('ops', { openingStillCurrent: () => current }), 'new-stored')- assert.deepEqual(opens, [])-})--test('a newer same-bot open replaces the in-flight creation navigation guard', async () => {- const opens = []- let releaseCreate- let markCreateStarted- let firstCurrent = true- const createStarted = new Promise(resolve => {- markCreateStarted = resolve- })- const runtime = loadCanonicalCreation({- openSession: async (id, options) => opens.push({ id, options }),- request: async method => {- if (method === 'session.create') {- markCreateStarted()- return new Promise(resolve => {- releaseCreate = () => resolve({ stored_session_id: 'shared-stored', session_id: 'shared-runtime' })- })- }- return {}- }- })-- const first = runtime.createCanonicalChat('ops', { openingStillCurrent: () => firstCurrent })- await createStarted- firstCurrent = false- const second = runtime.createCanonicalChat('ops', { openingStillCurrent: () => true })- releaseCreate()-- assert.equal(await first, 'shared-stored')- assert.equal(await second, 'shared-stored')- assert.equal(opens.length, 1, 'the newer current click owns the shared creation navigation')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjsdeleted file mode 100644index 3e013bbda19..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjs+++ /dev/null@@ -1,253 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// ── The canonical-chat REGISTRY contract ────────────────────────────────────-//-// A bot's forever-chat has exactly ONE identity: the session titled "Bot Chat"-// on that bot's profile. The core UNIQUE(title) index makes (profile,-// "Bot Chat") an exact registry — at most one row, resolved fresh on every-// open via `session.list { title: 'Bot Chat', include_hidden: true }`.-//-// There is NO session-id pin. The previous design stored a pointer in-// ui_meta['hermes-bots'].chat and spent five hardening waves (#88690, #90732,-// #90751, #91791-revert, #92042) guarding its failure modes: rows[0] steals,-// last_session adoptions, transient clears, drifted-title welds. Every "lost-// canonical chat" incident traced to that pointer dangling and a later guard-// then welding the wrong session in. Name-as-identity removes the failure-// class instead of guarding it: a name cannot dangle.-//-// This suite pins the whole contract:-// 1. open = registry lookup → open the row (lineage tip)-// 2. no row → create (adopt-before-mint lives inside creation)-// 3. no pointer is ever read or written on the open path--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadOpenPath({ openSession, request }) {- const start = source.indexOf('const canonicalCreations = new Map()')- const end = source.indexOf('function displayName(', start)- const requests = []- const opened = []- const context = {- host: {- openSession: async (id, options) => {- opened.push({ id, options })- return openSession ? openSession(id, options) : undefined- },- request: async (method, params) => {- requests.push({ method, params: JSON.parse(JSON.stringify(params ?? null)) })- return request(method, params)- }- },- // Owner-shape helpers (plugin scope): local bots carry no route, so the- // harness resolves everything onto the ambient host.request — the exact- // legacy single-connection behavior these tests pin.- botOwner: owner => (typeof owner === 'string'- ? { bot: { name: owner }, key: owner, name: owner, route: null }- : { bot: owner, key: owner?.name, name: owner?.name, route: owner?.route || null }),- backendTargetProfile: (route, name) => route?.targetProfile || name,- botWorkspaceOwnerKey: bot => `bot:${bot?.connectionId ? `${bot.connectionId}::` : ''}${bot?.name || 'default'}`,- requestForBot: (_bot, method, params) => context.host.request(method, params),- window: { setTimeout: callback => callback() }- }- const section = source- .slice(start, end)- .concat('\nglobalThis.__open = { createCanonicalChat, openBotCanonicalChat, findExistingCanonicalChat };\n')-- assert.notEqual(start, -1, 'canonical section is missing')- assert.notEqual(end, -1, 'canonical section delimiter is missing')- vm.runInNewContext(section, context, { filename: 'canonical-registry.js' })- return { ...context.__open, requests, opened }-}--// ── 1. the registry row wins, always ────────────────────────────────────────--test('open resolves the profile\u2019s "Bot Chat" row by exact title and opens it', async () => {- const runtime = loadOpenPath({- request: async method => {- if (method === 'session.list') {- return { sessions: [{ id: 'forever-chat', title: 'Bot Chat', message_count: 930 }] }- }- if (method === 'session.create') {- throw new Error('must not create: the registry row exists')- }- return {}- }- })-- const opened = await runtime.openBotCanonicalChat('ops')- assert.equal(opened.registryId, 'forever-chat')- assert.equal(opened.openedId, 'forever-chat')- assert.equal(runtime.opened.length, 1)- assert.equal(runtime.opened[0].id, 'forever-chat')- assert.equal(runtime.opened[0].options.profile, 'ops')- assert.equal(runtime.opened[0].options.keepAllProfilesScope, true,- 'opening a bot leaves the Sessions workspace on its current gateway')- assert.equal(runtime.opened[0].options.intent, 'tab')- assert.equal(runtime.opened[0].options.workspaceMode, 'bots')- assert.equal(runtime.opened[0].options.workspaceOwnerKey, 'bot:ops')- assert.equal(runtime.opened[0].options.tabTitle, 'Bot Chat')-- const list = runtime.requests.find(r => r.method === 'session.list')- assert.equal(list?.params?.title, 'Bot Chat', 'lookup is by exact title')- assert.equal(list?.params?.profile, 'ops')- assert.equal(list?.params?.include_hidden, true,- 'canonical chats are always hidden — the lookup must see hidden rows')-})--test('a compression-rotated registry row opens the lineage tip', async () => {- const runtime = loadOpenPath({- request: async method => {- if (method === 'session.list') {- return {- sessions: [{ id: 'root-1', resolved_id: 'tip-9', root_title: 'Bot Chat', title: 'Bot Chat', message_count: 400 }]- }- }- return {}- }- })-- const opened = await runtime.openBotCanonicalChat('ops')- assert.equal(opened.registryId, 'root-1', 'the durable registry id is returned')- assert.equal(opened.openedId, 'tip-9', 'the lineage tip rides alongside for focus matching')- assert.equal(runtime.opened[0].id, 'tip-9', 'the live tip is what opens')-})--test('the open path never reads or writes a stored pointer', () => {- const start = source.indexOf('const canonicalCreations = new Map()')- const end = source.indexOf('function displayName(', start)- const section = source.slice(start, end)-- assert.doesNotMatch(section, /saveBotMeta/, 'no pointer writes on the canonical path')- assert.doesNotMatch(section, /meta\??\.chat\b/, 'no pointer reads on the canonical path')- assert.doesNotMatch(section, /preferred_session_ids/, 'no id-verification RPC on the canonical path')-})--test('openBotCanonicalChat takes owner identity plus only an optional navigation-freshness guard', () => {- // The owner is the bot's name (local) or its roster row carrying the- // immutable connection route (remote). The optional callback controls only- // whether an async result may still navigate; it carries no identity.- assert.match(source, /async function openBotCanonicalChat\(owner, openingStillCurrent = null\) \{/)-})--// ── 2. no registry row → create ─────────────────────────────────────────────--test('no registry row mints a hidden "Bot Chat" session WITHOUT an intro kickoff', async () => {- // Click-path resolution: a miss mints the session silently. The intro turn- // fires only from New Agent creation (kickoff: true) — re-firing it here- // burned a model turn and stamped a user-attributed prompt into the chat- // on every resolution miss (retitle/hidden-listing/update skew).- const runtime = loadOpenPath({- request: async method => {- if (method === 'session.list') return { sessions: [] }- if (method === 'session.create') return { stored_session_id: 'fresh-1', session_id: 'rt-1' }- return {}- }- })-- const opened = await runtime.openBotCanonicalChat('newbie')- assert.equal(opened.registryId, 'fresh-1')- assert.equal(opened.openedId, 'fresh-1')- const create = runtime.requests.find(r => r.method === 'session.create')- assert.equal(create?.params?.title, 'Bot Chat')- assert.equal(create?.params?.hidden, true)- // The eager title write persisted the row; no user-attributed intro.- const titled = runtime.requests.find(r => r.method === 'session.title')- assert.equal(titled?.params?.session_id, 'rt-1')- const kickoff = runtime.requests.find(r => r.method === 'prompt.submit')- assert.equal(kickoff, undefined)-})--test('a failed open of the registry row surfaces instead of forking a replacement', async () => {- const runtime = loadOpenPath({- openSession: async () => {- throw new Error('backend restarting')- },- request: async method => {- if (method === 'session.list') {- return { sessions: [{ id: 'forever-chat', title: 'Bot Chat', message_count: 12 }] }- }- if (method === 'session.create') {- throw new Error('must not create: a transient open failure is not ownership loss')- }- return {}- }- })-- await assert.rejects(() => runtime.openBotCanonicalChat('ops'), /backend restarting/)-})--// ── 3. ordinary sessions are never claimed ──────────────────────────────────--test('an ordinary titled session never satisfies the registry lookup', async () => {- const runtime = loadOpenPath({- request: async method => {- if (method === 'session.list') {- // A misbehaving/older gateway ignores the title param and returns a- // windowed listing — the local exact-title scan still applies.- return {- sessions: [- { id: 'scratch', title: 'help me with x', message_count: 40 },- { id: 'draft', title: '', message_count: 0 }- ]- }- }- if (method === 'session.create') return { stored_session_id: 'fresh-2', session_id: 'rt-2' }- return {}- }- })-- const opened = await runtime.openBotCanonicalChat('ops')- assert.equal(opened.registryId, 'fresh-2', 'no row titled "Bot Chat" → create; never adopt an ordinary conversation')- assert.equal(opened.openedId, 'fresh-2')- assert.ok(!runtime.opened.some(o => o.id === 'scratch'))-})--// ── 4. a failed lookup fails CLOSED — never "no chat exists" ────────────────-//-// The post-update window: the desktop restarts every profile backend, the-// first bot click races the warm-up, and the registry lookup RPC fails-// transiently. Swallowing that error and returning null made the failure-// indistinguishable from "this bot has no Bot Chat yet", so the create path-// minted a fresh forever-chat while the real one (data intact, hidden) still-// held the canonical title — read by users as "my bot lost everything after-// the update". A lookup failure must surface (the open paths toast-// "try again"), never resolve to mint.--test('a failed registry lookup rejects instead of minting a replacement chat', async () => {- const runtime = loadOpenPath({- request: async method => {- if (method === 'session.list') {- throw new Error('gateway not ready')- }- if (method === 'session.create') {- throw new Error('must not create: a failed lookup is not "no chat exists"')- }- return {}- }- })-- await assert.rejects(() => runtime.openBotCanonicalChat('ops'), /Bot Chat registry/)- assert.ok(!runtime.requests.some(r => r.method === 'session.create'),- 'session.create must never fire off a failed lookup')- assert.equal(runtime.opened.length, 0)-})--test('createCanonicalChat also refuses to mint when the adoption lookup fails', async () => {- const runtime = loadOpenPath({- request: async method => {- if (method === 'session.list') {- throw new Error('backend warming up')- }- if (method === 'session.create') {- throw new Error('must not create: adoption check failed, ownership is unknown')- }- return {}- }- })-- await assert.rejects(() => runtime.createCanonicalChat('ops'), /Bot Chat registry/)- assert.ok(!runtime.requests.some(r => r.method === 'session.create'))-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/cloud-alias-identity.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/cloud-alias-identity.test.mjsdeleted file mode 100644index 0c684319ff8..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/cloud-alias-identity.test.mjs+++ /dev/null@@ -1,162 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #89131: a Desktop per-profile Cloud alias ("moxie" → exact Cloud connection-// → backend targetProfile "default") must keep its friendly identity after-// the hosted session activates, and must render as the alias — not generic-// "Hermes" or a hostname label — when Cloud is the only active source.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function runtime({ connectionId = 'local' } = {}) {- const atom = value => ({ get: () => value, set: next => { value = next } })- 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: {- connectionId: { get: () => connectionId, listen: () => undefined },- profile: { get: () => 'default', listen: () => undefined }- },- request: () => undefined- },- sdk: new Proxy({}, { get: () => undefined })- }- const code = source- .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(- '\nglobalThis.__indexAliasRoutes = indexAliasRoutes;' +- '\nglobalThis.__aliasIdentityFor = aliasIdentityFor;' +- '\nglobalThis.__displayName = displayName;' +- '\nglobalThis.__botRosterMeta = botRosterMeta;' +- '\nglobalThis.__botFriendlyNames = botFriendlyNames;' +- '\nglobalThis.__botMentionTag = botMentionTag;' +- '\nglobalThis.__botMeta = $botMeta;'- )- vm.runInNewContext(code, context)- return context-}--const MOXIE_ROUTE = { connectionId: 'cloud-abc', mode: 'remote', profile: 'moxie', targetProfile: 'default' }--/** The hosted backend's own roster row after alias handoff: the Cloud- * connection answers as its root profile, so the row identity is- * (cloud-abc, default) — NOT the alias key. */-const hostedRow = {- name: 'default',- connectionId: 'cloud-abc',- connectionLabel: 'cloud.example.com',- targetProfile: 'default',- remoteSource: true,- sourceScoped: true,- route: { connectionId: 'cloud-abc', mode: 'remote', profile: 'default', targetProfile: 'default' }-}--test('alias identity survives hosted-session activation (roster refresh)', () => {- const ctx = runtime()- ctx.__indexAliasRoutes([- { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },- MOXIE_ROUTE- ])-- // No stored title anywhere: the alias NAME is still the identity.- assert.equal(ctx.__displayName(hostedRow, null), 'Moxie')-- // The alias's Bot Mode title (either meta key generation) claims the row.- const metaV2 = { 'cloud-abc::moxie': { title: 'Moxie' } }- assert.equal(ctx.__botRosterMeta(hostedRow, metaV2), metaV2['cloud-abc::moxie'])- assert.equal(ctx.__displayName(hostedRow, ctx.__botRosterMeta(hostedRow, metaV2)), 'Moxie')-- const metaV1 = { moxie: { title: 'Moxie ✨' } }- assert.equal(ctx.__displayName(hostedRow, ctx.__botRosterMeta(hostedRow, metaV1)), 'Moxie ✨')-})--test('Cloud-only mode: the sole active-gateway default renders as the alias, not Hermes', () => {- // Global route is Cloud: the active gateway IS the Cloud connection and- // profiles.list returns one unannotated rich `default` row.- const ctx = runtime({ connectionId: 'cloud-abc' })- ctx.__indexAliasRoutes([MOXIE_ROUTE])-- const soleBot = { name: 'default' }- assert.equal(ctx.__displayName(soleBot, null), 'Moxie')-- // A user-set title still wins over the alias name.- assert.equal(ctx.__displayName(soleBot, { title: 'Custom' }), 'Custom')-})--test('alias never leaks to same-named defaults on other connections', () => {- const ctx = runtime()- ctx.__indexAliasRoutes([MOXIE_ROUTE])-- const otherDefault = { ...hostedRow, connectionId: 'other-conn', route: null, targetProfile: 'default', connectionLabel: 'Personal' }- // Different connection: no alias claim — hostname label behavior stands.- assert.equal(ctx.__aliasIdentityFor(otherDefault), null)- assert.equal(ctx.__displayName(otherDefault, null), 'Personal')-- // Local default while the ACTIVE gateway is local: untouched "Hermes".- assert.equal(ctx.__displayName({ name: 'default' }, null), 'Hermes')-})--test('two aliases claiming one backend row fail closed', () => {- const ctx = runtime()- ctx.__indexAliasRoutes([- MOXIE_ROUTE,- { connectionId: 'cloud-abc', mode: 'remote', profile: 'roxie', targetProfile: 'default' }- ])-- assert.equal(ctx.__aliasIdentityFor(hostedRow), null)- // Ambiguous: fall back to the source label, not a guessed alias.- assert.equal(ctx.__displayName(hostedRow, null), 'cloud.example.com')-})--test('the alias row itself never claims its own alias entry', () => {- const ctx = runtime()- ctx.__indexAliasRoutes([MOXIE_ROUTE])-- const aliasRow = {- name: 'moxie',- connectionId: 'cloud-abc',- targetProfile: 'default',- sourceScoped: true,- route: { ...MOXIE_ROUTE }- }- assert.equal(ctx.__aliasIdentityFor(aliasRow), null)- assert.equal(ctx.__displayName(aliasRow, null), 'Moxie')-})--test('mentions keep resolving @moxie against the hosted row after handoff', () => {- const ctx = runtime()- ctx.__indexAliasRoutes([MOXIE_ROUTE])- ctx.__botMeta.set({ 'cloud-abc::moxie': { title: 'Moxie' } })-- const friendly = ctx.__botFriendlyNames(hostedRow).filter(Boolean)- assert.equal(friendly.length, 1)- assert.equal(friendly[0], 'Moxie')- assert.equal(ctx.__botMentionTag(hostedRow), 'moxie')-})--test('non-alias routes never enter the index; index refresh replaces stale claims', () => {- const ctx = runtime()- ctx.__indexAliasRoutes([- { connectionId: 'local', mode: 'local', profile: 'rune', targetProfile: 'rune' },- MOXIE_ROUTE- ])- assert.ok(ctx.__aliasIdentityFor(hostedRow))-- // Alias removed from config → next inventory drops the claim.- ctx.__indexAliasRoutes([{ connectionId: 'local', mode: 'local', profile: 'rune', targetProfile: 'rune' }])- assert.equal(ctx.__aliasIdentityFor(hostedRow), null)- assert.equal(ctx.__displayName(hostedRow, null), 'cloud.example.com')-})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.mjsdeleted file mode 100644index 2b943e0d3f6..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/create-agent-clone-default.test.mjs+++ /dev/null@@ -1,21 +0,0 @@-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.mjsdeleted file mode 100644index 3200676dbc6..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/create-agent-mcp-setup.test.mjs+++ /dev/null@@ -1,48 +0,0 @@-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/create-group-chat.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/create-group-chat.test.mjsdeleted file mode 100644index 899a2a3e368..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/create-group-chat.test.mjs+++ /dev/null@@ -1,42 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--// Discord-style creation flow: the header "+" is a dropdown (New Bot /-// New Group Chat), and New Group Chat opens a checkbox-picker modal with-// search, a name input, and a Create button. Source-contract style, like-// the other roster affordance tests.--test('source contract: header + is a dropdown offering agent and group chat', () => {- assert.match(pluginSource, /DropdownMenuTrigger/)- assert.match(pluginSource, /'New Bot'/)- assert.match(pluginSource, /'New Group Chat'/)-})--test('source contract: create-group modal has search, checkboxes, name, create', () => {- assert.match(pluginSource, /function CreateGroupChatDialog\(/)- // An outage placeholder preserves identity, but cannot receive a message.- assert.match(pluginSource, /const selectableRoster = roster\.filter\(bot => !bot\?\.ghost\)/)- // Reuses the roster search filter so name/@handle/title all match.- assert.match(pluginSource, /const visible = filterBots\(selectableRoster, allMeta, query\)/)- // Selection is checkbox-driven and capped at the room member limit.- assert.match(pluginSource, /const atCap = selected\.length >= GROUP_CHAT_MAX_MEMBERS/)- // Create requires 2+ members. Membership mutation is covered by the- // behavioral groupMembershipPatch tests rather than another source regex.- assert.match(pluginSource, /selected\.length >= 2/)- // Creating drops the user straight into the room (main window when the- // desktop offers host.openWorkspace, in-panel fallback otherwise).- assert.match(pluginSource, /onCreated: groupName => openGroupChat\(groupName\)/)-})--test('source contract: group name falls back to member names, Discord-style', () => {- assert.match(pluginSource, /selected\.map\(bot => displayName\(bot, botRosterMeta\(bot, allMeta\)\)\)\.join\(', '\)/)-})--test('source contract: every selected machine is persisted in the durable room record', () => {- assert.match(pluginSource, /const roomMembers = durableGroupChatMembers\(selected\)/)- assert.match(pluginSource, /room\.members = roomMembers/)- assert.doesNotMatch(pluginSource, /const remoteMembers = selected/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjsdeleted file mode 100644index e60fb8d2bdd..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/cross-connection-bots.test.mjs+++ /dev/null@@ -1,231 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Cross-connection Bot Mode: the New Agent "Create on" picker targets another-// registered connection's backend, and group chats seat members from other-// machines by routing their turns through host.requestProfile route-// descriptors instead of the active gateway.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function runtime() {- const context = {- console,- setTimeout,- clearTimeout,- Date,- URL,- atom: initial => {- const listeners = new Set()- let value = initial- return {- get: () => value,- set: next => {- value = next- listeners.forEach(fn => fn(next))- },- listen: fn => {- listeners.add(fn)- return () => listeners.delete(fn)- }- }- },- host: {- request: async () => ({}),- requestProfile: async () => ({}),- state: {- profile: { get: () => 'default', listen: () => undefined },- connectionId: { get: () => 'local', listen: () => undefined },- gateway: { listen: () => undefined }- }- },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } }- }- const code = 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.__x = { botConnectionRoute, scopedBotParams, botBackendProfileScope, requestForBot, groupMemberKey, parseGroupChatMentions, resolveGroupResponders, formatGroupChatLine, buildGroupChatTurnPrompt };\n'- )- vm.runInNewContext(code, context, { filename: 'plugin.js' })- return context-}--test('botConnectionRoute: every source-scoped row gets an immutable route', () => {- const ctx = runtime()- const { botConnectionRoute } = ctx.__x-- assert.equal(botConnectionRoute({ name: 'writer', connectionId: 'local' }), null)- assert.equal(botConnectionRoute({ name: 'writer' }), null)- const active = botConnectionRoute({ name: 'writer', connectionId: 'spark', sourceScoped: true })- assert.equal(Object.isFrozen(active), true)-- const route = botConnectionRoute({ name: 'dixie', connectionId: 'mac-mini', remoteSource: true })- assert.deepEqual(JSON.parse(JSON.stringify(route)), {- connectionId: 'mac-mini',- mode: 'remote',- profile: 'dixie',- targetProfile: 'dixie'- })-})--test('requestForBot: source-scoped members go through requestProfile', async () => {- const ctx = runtime()- const calls = []- ctx.host.request = async (method, params) => {- calls.push(['active', method, params])- return {}- }- ctx.host.requestProfile = async (route, method, params) => {- calls.push(['routed', route.connectionId, method, params])- return {}- }-- const { requestForBot } = ctx.__x-- await requestForBot({ name: 'local-bot' }, 'session.create', { title: 'x' })- await requestForBot({ name: 'local-bot', connectionId: 'local', sourceScoped: true }, 'session.create', { title: 'x' })- await requestForBot({ name: 'dixie', connectionId: 'mac-mini', remoteSource: true }, 'prompt.submit', { text: 'hi' })-- assert.equal(calls[0][0], 'active')- assert.equal(calls[0][1], 'session.create')- assert.equal(calls[1][0], 'routed')- assert.equal(calls[1][1], 'local')- assert.equal(calls[2][0], 'routed')- assert.equal(calls[2][1], 'mac-mini')- assert.equal(calls[2][2], 'prompt.submit')-})--test('requestForBot: non-identity aliases translate every backend profile RPC shape', async () => {- const ctx = runtime()- const calls = []- ctx.host.requestProfile = async (route, method, params) => {- calls.push({ route, method, params })- return {}- }- const bot = {- name: 'worker',- sourceScoped: true,- route: {- connectionId: 'remote-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'backend-worker'- }- }-- await ctx.__x.requestForBot(bot, 'profiles.describe', { name: 'worker' })- await ctx.__x.requestForBot(bot, 'profiles.configure', { name: 'worker', soul: 'x' })- await ctx.__x.requestForBot(bot, 'profiles.create', { name: 'worker-2', clone_from: 'worker' })- await ctx.__x.requestForBot(bot, 'session.create', { profile: 'worker', title: 'Bot Chat' })- await ctx.__x.requestForBot(bot, 'cli.exec', { argv: ['--profile', 'worker', 'config', 'unset', 'model'] })- await ctx.__x.requestForBot(bot, 'cli.exec', {- argv: ['profile', 'describe', 'worker', '--text', 'worker']- })-- assert.deepEqual(JSON.parse(JSON.stringify(calls.map(call => call.params))), [- { name: 'backend-worker' },- { name: 'backend-worker', soul: 'x' },- { name: 'worker-2', clone_from: 'backend-worker' },- { profile: 'backend-worker', title: 'Bot Chat' },- { argv: ['--profile', 'backend-worker', 'config', 'unset', 'model'] },- { argv: ['profile', 'describe', 'backend-worker', '--text', 'worker'] }- ])- assert.equal(calls.every(call => call.route.profile === 'worker'), true)-})--test('advanced capability scope keeps Desktop identity separate from backend targetProfile', () => {- const scope = runtime().__x.botBackendProfileScope({- connectionId: 'remote-a',- profile: 'worker',- targetProfile: 'backend-worker'- })-- assert.deepEqual(JSON.parse(JSON.stringify(scope)), {- connectionId: 'remote-a',- profile: 'backend-worker'- })-})--test('groupMemberKey: local members keep bare names (persisted-room compat), remote members are source-qualified', () => {- const ctx = runtime()- const { groupMemberKey } = ctx.__x-- assert.equal(groupMemberKey({ name: 'ops' }), 'ops')- assert.equal(groupMemberKey({ name: 'dixie', connectionId: 'mac-mini', remoteSource: true }), 'mac-mini::dixie')-})--test('mentions: @name-device handle resolves the remote member; same-named agents stay distinct', () => {- const ctx = runtime()- const { parseGroupChatMentions, resolveGroupResponders } = ctx.__x- const members = [- { name: 'dixie', title: '' },- { name: 'dixie', handle: 'dixie-mac-mini', connectionId: 'mac-mini', remoteSource: true }- ]-- const parsed = parseGroupChatMentions('hey @dixie-mac-mini can you check disk space', members)- assert.deepEqual([...parsed.mentioned], ['mac-mini::dixie'])-- const log = [{ from: { kind: 'user', name: 'You' }, text: '@dixie-mac-mini ping', at: 1 }]- const responders = resolveGroupResponders(log, members)- assert.equal(responders.length, 1)- assert.equal(responders[0].remoteSource, true)-})--test('room lines and turn prompts badge cross-connection speakers with their device', () => {- const ctx = runtime()- const { formatGroupChatLine, buildGroupChatTurnPrompt } = ctx.__x-- const line = formatGroupChatLine(- { from: { kind: 'member', name: 'dixie', source: 'Mac Mini' }, text: 'done', at: 1 },- 'ops'- )- assert.equal(line, 'dixie [Mac Mini]: done')-- const prompt = buildGroupChatTurnPrompt({- groupName: 'infra',- members: [- { name: 'ops', title: '' },- { name: 'dixie', connectionId: 'mac-mini', connectionLabel: 'Mac Mini', remoteSource: true }- ],- viewer: { name: 'ops' },- deltaLines: ['You (user): hi']- })- assert.match(prompt, /@dixie \[on Mac Mini\]/)-})--test('source contract: New Agent has a Create on picker that routes creation to the target backend', () => {- assert.match(pluginSource, /'Create on'/)- assert.match(pluginSource, /const \[targetConnection, setTargetConnection\] = useState\(''\)/)- // Creation and configuration go through the target door, not bare host.request.- assert.match(pluginSource, /await requestForTarget\('profiles\.create', \{/)- assert.match(pluginSource, /await requestForTarget\('profiles\.configure', \{ name: slug/)- // The picker only renders on multi-connection registries.- assert.match(pluginSource, /connections\.length > 1/)-})--test('source contract: group chat turns route through requestForBot on the member source', () => {- assert.match(pluginSource, /await requestForBot\(member, 'prompt\.submit'/)- assert.match(pluginSource, /await requestForBot\(member, 'session\.create'/)- // Room records persist remote member descriptors.- assert.match(pluginSource, /members: Array\.isArray\(room\.members\) \? room\.members : \[\]/)-})--test('regression: host.connections() result is normalized for BOTH SDK shapes before the picker gate', () => {- // Current SDKs return the registry ROWS from host.connections() (the- // documented contract); desktops that predate the SDK-side unwrap resolve- // the raw IPC payload — the registry OBJECT ({version, primary,- // connections: [...]}). The picker gate (Array.isArray(connections) &&- // length > 1) needs rows either way, so the plugin must accept both- // shapes. Pinning one shape only reopens #89823 on the other.- assert.match(- pluginSource,- /setConnections\(Array\.isArray\(value\) \? value : Array\.isArray\(value\?\.connections\) \? value\.connections : \[\]\)/- )-})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.mjsdeleted file mode 100644index 5d3c2b09aef..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/draft-agent-discard.test.mjs+++ /dev/null@@ -1,41 +0,0 @@-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 (deleteBot locally, remote CLI for other connections)', () => {- assert.match(source, /const discardDraft = \(\) => \{/)- assert.match(source, /: 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*const discard = remoteTarget/)-})--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", () => {- // Both branches of the target-scoped taken check exempt the draft's slug.- assert.match(source, /roster\.some\(b => !b\.remoteSource && b\.name === slug && b\.name !== createdRef\.current\)/)- assert.match(- source,- /roster\.some\(b => b\.remoteSource && b\.connectionId === targetConnection && 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.mjsdeleted file mode 100644index 4301ad53e9f..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/duplicate-bot.test.mjs+++ /dev/null@@ -1,87 +0,0 @@-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.mjsdeleted file mode 100644index a72cbdc5d0f..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/embed-real-capabilities.test.mjs+++ /dev/null@@ -1,41 +0,0 @@-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: backendScope \}\)/)-})--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: backendScope \}\)/)-})--test('AdvancedProfileConfig scopes SkillsView to the connection and backend target profile', () => {- // Route lookup is the NON-throwing resolver (#93492): the dialog renders- // degraded for an orphaned row instead of crashing the pane.- assert.match(source, /const botRoute = resolveBotConnectionRoute\(bot\)\.route/)- assert.match(source, /fixedProfile: backendProfile/)- assert.match(source, /fixedConnection: botRoute\.connectionId/)-})--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.mjsdeleted file mode 100644index a90f8270dac..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/embed-skills-view.test.mjs+++ /dev/null@@ -1,230 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// 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')--function loadAdvanced(SkillsView, sdkComponents = {}) {- const values = new Map()- const atom = initial => {- const slot = {- get: () => values.get(slot),- set: value => values.set(slot, value),- listen: () => undefined- }- values.set(slot, initial)- return slot- }- const jsx = (type, props = {}) => ({ type, props })- const stateValues = [true, false, '']- const routed = []- let gatewayReads = 0- let query- const context = {- atom,- Checkbox: 'Checkbox',- GlyphSpinner: 'GlyphSpinner',- Input: 'Input',- ScrollArea: 'ScrollArea',- Textarea: 'Textarea',- document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },- host: {- getGateway: () => {- gatewayReads += 1- return 'ambient-gateway'- },- request: async (...args) => routed.push(['ambient', ...args]),- requestProfile: async (...args) => routed.push(['profile', ...args]),- state: {- gateway: { get: () => 'open', listen: () => undefined },- profile: { get: () => 'default', listen: () => undefined }- }- },- jsx,- jsxs: jsx,- queryClient: { invalidateQueries: () => undefined },- sdk: { SkillsView, ...sdkComponents },- useQuery: options => {- query = options- return { data: { providers: [] }, isLoading: false, error: null }- },- useState: initial => [stateValues.length ? stateValues.shift() : initial, () => undefined],- window: { setTimeout, clearTimeout }- }- 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(/^import .* from 'react'\r?\n/m, '')- .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')- .replace('export default {', 'globalThis.plugin = {')- .concat('\nglobalThis.__AdvancedProfileConfig = AdvancedProfileConfig; globalThis.__useModelOptions = useModelOptions;')- vm.runInNewContext(code, context, { filename: 'plugin.js' })-- return { context, gatewayReads: () => gatewayReads, query: () => query, routed }-}--function descendants(node) {- if (!node || typeof node !== 'object') return []- const children = Array.isArray(node.props?.children) ? node.props.children : [node.props?.children]- return [node, ...children.flatMap(descendants)]-}--const remoteBot = {- connectionId: 'remote-a',- name: 'default',- remoteSource: true,- route: {- connectionId: 'remote-a',- mode: 'remote',- profile: 'default',- targetProfile: 'backend-default'- },- sourceScoped: true,- targetProfile: 'backend-default'-}--const localBot = {- connectionId: 'local',- name: 'default',- remoteSource: false,- route: {- connectionId: 'local',- mode: 'local',- profile: 'default',- targetProfile: 'default'- },- sourceScoped: true,- targetProfile: 'default'-}--const advancedState = {- loaded: true,- provider: '',- model: '',- soul: '',- skills: [],- toolsets: [],- mcp: [{ name: 'remote-mcp', enabled: false, fromCatalog: true, installed: false, requires: ['TOKEN'] }]-}--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 && \(!botRoute \|\| skillsViewRoutesConnections\)\) \{/)- assert.match(source, /fixedProfile: backendProfile/)- assert.match(source, /fixedConnection: botRoute\.connectionId/)-})--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, \{\s*embedded: true,\s*fixedProfile: createdForCaps,/)-})--test('remote-target drafts pin the live surface to the target connection', () => {- // Builds whose SkillsView routes fixedConnection get the live Capabilities- // tab for remote targets too — pinned to the target machine's backend.- assert.match(source, /skillsViewRoutesConnections = Boolean\(SkillsView && SkillsView\.supportsFixedConnection\)/)- assert.match(source, /SkillsView && \(!remoteTarget \|\| skillsViewRoutesConnections\)/)- assert.match(source, /\.\.\.\(remoteTarget \? \{ fixedConnection: targetConnection \} : \{\}\)/)-})--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, \{/)-})--test('older SkillsView builds fail closed for remote Edit Profile', () => {- function OldSkillsView() {}- function McpTab() {}- function ToolsetConfigPanel() {}- const runtime = loadAdvanced(OldSkillsView, { McpTab, ToolsetConfigPanel })- const tree = runtime.context.__AdvancedProfileConfig({- bot: remoteBot,- state: advancedState,- setState: () => undefined- })- const nodes = descendants(tree)-- assert.equal(nodes.some(node => node.type === OldSkillsView), false)- assert.equal(nodes.some(node => node.type?.name === 'ModelPicker'), true)- assert.equal(nodes.some(node => node.type === 'Textarea'), true)- assert.equal(nodes.some(node => node.type?.name === 'HubSkillsSection'), false)- assert.equal(nodes.some(node => node.type?.name === 'McpSetupButton'), false)- assert.equal(nodes.some(node => node.type === McpTab), false)- assert.equal(nodes.some(node => node.type === ToolsetConfigPanel), false)- assert.equal(runtime.gatewayReads(), 0)-- for (const node of nodes) {- node.props?.onClick?.()- node.props?.onCheckedChange?.(true)- }-- assert.equal(runtime.routed.some(call => call[0] === 'ambient'), false)- assert.equal(runtime.gatewayReads(), 0)-})--test('older SkillsView builds keep local capability fallback unchanged', () => {- function OldSkillsView() {}- function McpTab() {}- function ToolsetConfigPanel() {}- const runtime = loadAdvanced(OldSkillsView, { McpTab, ToolsetConfigPanel })- const tree = runtime.context.__AdvancedProfileConfig({- bot: localBot,- state: { ...advancedState, toolsets: [{ name: 'local-tools', enabled: true }] },- setState: () => undefined- })- const nodes = descendants(tree)-- assert.equal(nodes.some(node => node.type?.name === 'HubSkillsSection'), true)- assert.equal(nodes.some(node => node.type === McpTab), true)- assert.equal(nodes.some(node => node.type === ToolsetConfigPanel), true)- assert.equal(runtime.gatewayReads(), 1)-})--test('connection-aware SkillsView receives separate connection and backend profile', () => {- function RoutedSkillsView() {}- RoutedSkillsView.supportsFixedConnection = true- const runtime = loadAdvanced(RoutedSkillsView)- const tree = runtime.context.__AdvancedProfileConfig({- bot: remoteBot,- state: advancedState,- setState: () => undefined- })- const view = descendants(tree).find(node => node.type === RoutedSkillsView)-- assert.equal(view.props.fixedConnection, 'remote-a')- assert.equal(view.props.fixedProfile, 'backend-default')-})--test('Edit Profile model options use the captured non-identity Bot route', async () => {- const runtime = loadAdvanced(undefined)- runtime.context.__useModelOptions(remoteBot)-- await runtime.query().queryFn()-- assert.deepEqual(JSON.parse(JSON.stringify(runtime.routed)), [[- 'profile',- remoteBot.route,- 'model.options',- // No `refresh`: the picker's catalog read participates in the staleTime- // cache — a forced network read on every mount re-entered the spinner and- // wiped staged selections on Bots view remounts (#95279).- { include_unconfigured: true, explicit_only: false }- ]])-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/face-catchlight.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/face-catchlight.test.mjsdeleted file mode 100644index 6df742ffa1c..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/face-catchlight.test.mjs+++ /dev/null@@ -1,20 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--// Catchlight contrast follows the PUPIL, not the body (image14 report,-// Aug 2026): dark bodies flip the pupils to light cream (`eyeFill`), and a-// white catchlight on a cream pupil is invisible — maroon/ink/oxblood-// avatars looked like they had "no dots in their eyes". The sparkle must be-// dark on light pupils and light on dark pupils.--test('catchlight fill flips with pupil polarity (hlFill), not hardcoded white', () => {- assert.match(pluginSource, /const hlFill = isDarkColor\(color\) \? 'rgba\(0,0,0,0\.6\)' : 'rgba\(255,255,255,0\.85\)'/)- // Both initial catchlight circles use it.- assert.match(pluginSource, /'data-hb-hl-l': '1', cx: 14\.8, cy: eyeY0 - 0\.7, r: 0\.65, fill: hlFill/)- assert.match(pluginSource, /'data-hb-hl-r': '1', cx: 24, cy: eyeY0 - 0\.7, r: 0\.65, fill: hlFill/)- // No stray hardcoded white catchlight remains on the hb-hl elements.- assert.doesNotMatch(pluginSource, /data-hb-hl-[lr]': '1'[^}]*rgba\(255,255,255/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/face-clock.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/face-clock.test.mjsdeleted file mode 100644index a1def1bee90..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/face-clock.test.mjs+++ /dev/null@@ -1,200 +0,0 @@-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')--// Extract the clock functions only — the plugin is an ES module, so the whole-// file can't be evaluated in a bare vm context. The slice is anchored on the-// function declarations themselves.-const start = pluginSource.indexOf('function startFaceClock()')-const end = pluginSource.indexOf('/**\n * Live math face.')-assert.ok(start > 0 && end > start, 'face clock functions present in plugin.js')-const clockSource = pluginSource.slice(start, end)--function load({ budgetedLoop = undefined, faces = [], intersectionObserver = true } = {}) {- const rafQueue = new Map()- let rafSeq = 0- let observerInstance = null-- class FakeIntersectionObserver {- constructor(callback) {- this.callback = callback- this.observed = new Set()- this.disconnected = false- observerInstance = this- }-- observe(el) {- this.observed.add(el)- }-- unobserve(el) {- this.observed.delete(el)- }-- disconnect() {- this.disconnected = true- this.observed.clear()- }-- emit(entries) {- this.callback(entries)- }- }-- const windowObj = {- requestAnimationFrame: cb => {- rafSeq += 1- rafQueue.set(rafSeq, cb)- return rafSeq- },- cancelAnimationFrame: id => {- rafQueue.delete(id)- }- }-- const context = {- window: windowObj,- document: { hidden: false },- performance: { now: () => 0 },- IntersectionObserver: intersectionObserver ? FakeIntersectionObserver : undefined,- walkMathFaces: () => [...faces],- paintMathFace: () => undefined,- createBudgetedLoop: budgetedLoop- }- vm.createContext(context)- vm.runInContext(`${clockSource}; __start = startFaceClock; __stop = stopFaceClock`, context)-- let now = 0- const pump = (advance = 100) => {- now += advance- const pending = [...rafQueue.entries()]- rafQueue.clear()- for (const [, cb] of pending) {- cb(now)- }- }-- return {- start: () => context.__start(),- stop: () => context.__stop(),- pump,- pending: () => rafQueue.size,- observer: () => observerInstance,- clock: () => context.window.__hbFaceClock,- setFaces: next => {- faces.length = 0- faces.push(...next)- }- }-}--test('unit: the clock parks itself when no faces are mounted', () => {- const h = load({ faces: [] })- h.start()- assert.equal(h.pending(), 1, 'clock schedules its first frame')- h.pump()- assert.equal(h.pending(), 0, 'no faces -> dormant, no further frames scheduled')-})--test('unit: a mounting face (startFaceClock re-entry) wakes a parked clock', () => {- const h = load({ faces: [] })- h.start()- h.pump()- assert.equal(h.pending(), 0, 'parked')-- const face = { isConnected: true }- h.setFaces([face])- h.start() // BotFace render path- assert.equal(h.pending(), 1, 'wake scheduled a frame')-})--test('unit: the clock parks when all faces scroll out and the observer wakes it back', () => {- const face = { isConnected: true }- const h = load({ faces: [face] })- h.start()- h.pump()- // Face observed but not yet visible -> visibleFaces empty -> parked.- assert.equal(h.pending(), 0, 'no visible faces -> dormant')-- h.observer().emit([{ target: face, isIntersecting: true }])- assert.equal(h.pending(), 1, 'visibility wakes the clock')- h.pump()- assert.equal(h.pending(), 1, 'visible face keeps the clock running')-- h.observer().emit([{ target: face, isIntersecting: false }])- h.pump()- h.pump()- assert.equal(h.pending(), 0, 'all faces hidden -> parked again')-})--test('unit: stopFaceClock cancels the frame, disconnects the observer, and clears the handle', () => {- const face = { isConnected: true }- const h = load({ faces: [face] })- h.start()- h.observer().emit([{ target: face, isIntersecting: true }])- h.pump()- assert.equal(h.pending(), 1, 'running')-- h.stop()- assert.equal(h.pending(), 0, 'pending frame cancelled')- assert.equal(h.observer().disconnected, true, 'observer disconnected')- assert.equal(h.clock(), undefined, 'window handle removed')-- // A fresh start after teardown re-initializes rather than hitting a dead handle.- h.start()- assert.equal(h.pending(), 1, 'clock restarts cleanly after stop')-})--test('source: plugin registers face-clock teardown via ctx.onDispose', () => {- assert.match(pluginSource, /ctx\.onDispose\(stopFaceClock\)/)-})--test('unit: SDK path — clock delegates scheduling to createBudgetedLoop', () => {- const calls = { dispose: 0, wake: 0 }- let capturedDraw = null- let capturedOptions = null- const fakeLoop = {- dispose: () => {- calls.dispose += 1- },- isDormant: () => false,- wake: () => {- calls.wake += 1- }- }- const face = { isConnected: true }- const h = load({- faces: [face],- budgetedLoop: (draw, options) => {- capturedDraw = draw- capturedOptions = options- return fakeLoop- }- })-- h.start()- assert.equal(typeof capturedDraw, 'function', 'draw handed to the SDK loop')- assert.equal(capturedOptions.fps, 15, '15fps budget requested')- assert.equal(typeof capturedOptions.idleWhen, 'function', 'idle predicate wired')- assert.equal(h.pending(), 0, 'no hand-rolled rAF scheduled on the SDK path')-- // idleWhen reflects visible-face state: observed-but-not-visible = idle.- capturedDraw(1000) // triggers the initial scan + observation- assert.equal(capturedOptions.idleWhen(), true, 'no visible faces -> idle')- h.observer().emit([{ target: face, isIntersecting: true }])- assert.equal(capturedOptions.idleWhen(), false, 'visible face -> not idle')- assert.ok(calls.wake >= 1, 'visibility wakes the SDK loop')-- // Re-entry (BotFace mount) wakes rather than re-initializing.- h.start()- assert.ok(calls.wake >= 2, 'startFaceClock re-entry wakes the SDK loop')-- // Teardown disposes the loop and clears the handle.- h.stop()- assert.equal(calls.dispose, 1, 'stop disposes the SDK loop')- assert.equal(h.observer().disconnected, true, 'observer disconnected')- assert.equal(h.clock(), undefined, 'window handle removed')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/focused-bot-highlight.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/focused-bot-highlight.test.mjsdeleted file mode 100644index 69a383c9670..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/focused-bot-highlight.test.mjs+++ /dev/null@@ -1,91 +0,0 @@-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 roster highlight and the Routines (Cronjobs) tile must follow the chat-// the user is LOOKING AT — the focused session's owner profile — not the-// gateway socket's home. Tab/tile focus moves without swapping the socket, so-// keying these off `host.state.profile` alone highlighted (and scoped the-// Cronjobs panel to) the wrong bot whenever a focused tab showed another-// profile's chat (community report: Newsanalyst chat open, Hermes highlighted).--test('$focusedBotOwner prefers the connection-qualified focused owner atom', () => {- assert.match(- source,- /const \$focusedBotOwner = host\.state\.focusedSessionOwner \|\|/,- 'newer desktops expose a complete focused owner; older builds retain a feature-detected fallback'- )-})--test('legacy focused-profile-only SDK never pairs foreign focus with ambient connection', () => {- const ownerStart = source.indexOf('const $focusedBotProfile =')- const ownerEnd = source.indexOf('/** Optional secondary navigation', ownerStart)- const activeStart = source.indexOf('function isActiveRosterBot(')- const activeEnd = source.indexOf('function botSelectionKey(', activeStart)- const store = value => ({ get: () => value, listen: () => undefined })- const context = {- host: {- activeConnectionId: () => 'source-a',- state: {- connectionId: store('source-a'),- focusedSessionProfile: store('worker'),- profile: store('default')- }- }- }-- vm.runInNewContext(- `${source.slice(ownerStart, ownerEnd)}\n${source.slice(activeStart, activeEnd)}\n` +- 'globalThis.result = { owner: focusedRosterOwner($focusedBotOwner.get()), isActiveRosterBot };',- context- )-- assert.equal(context.result.owner, null)- assert.equal(context.result.isActiveRosterBot({- connectionId: 'source-a',- name: 'worker',- remoteSource: true- }, context.result.owner), false)- assert.equal(context.result.isActiveRosterBot({ name: 'default' }, context.result.owner), false)-})--test('BotRow keys the highlight off the focused profile, not the socket home', () => {- const rowStart = source.indexOf('function BotRow(')- assert.ok(rowStart >= 0)- const row = source.slice(rowStart, rowStart + 2000)-- assert.match(row, /const focusedOwner = focusedRosterOwner\(useValue\(\$focusedBotOwner\)\)/)- assert.match(row, /const isActive = botRowOwnsWorkspace\([\s\S]*?focusedOwner,[\s\S]*?selectedRosterKey/)-})--test('BotRow keeps turn-busy (work mood) a socket fact', () => {- const rowStart = source.indexOf('function BotRow(')- const row = source.slice(rowStart, rowStart + 5000)-- // Only the gateway-home profile can actually be mid-turn: the mood must NOT- // switch to the focus-keyed identity.- assert.match(row, /const isGatewayHome = !bot\.remoteSource && bot\.name === activeProfile/)- assert.match(row, /const botMood = workerActive \|\| \(isGatewayHome && gatewayState === 'busy'\) \? 'work' : 'idle'/)-})--test('RoutinesPane scopes the Cronjobs tile to the focused chat owner', () => {- const paneStart = source.indexOf('function RoutinesPane(')- assert.ok(paneStart >= 0)- const pane = source.slice(paneStart, paneStart + 1200)-- assert.match(pane, /const focusedOwner = focusedRosterOwner\(useValue\(\$focusedBotOwner\)\)/)- // The roster read must be a SUBSCRIPTION, not a bare .get(): BotsPane- // owns the fetch and can hydrate after this pane mounted, so a bare snapshot- // pinned the tile on "unavailable" forever (#94483). Scoping intent is- // unchanged — it still keys off the focused owner, never the socket-home- // profile atom asserted against below.- assert.match(pane, /const owner = resolveRoutineOwner\(useValue\(\$lastRoster\), focusedOwner, selected\)/)- assert.ok(!/useValue\(host\.state\.profile\)/.test(pane), 'the tile must not read the socket-home atom directly')-})--test('the $selectedBot tracker binds the focused profile ladder (reseed + unbind captured)', () => {- assert.match(source, /const unbindProfileListener = bindProfileSync\(\$focusedBotOwner\)/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-activity.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-activity.test.mjsdeleted file mode 100644index e46085be69d..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-activity.test.mjs+++ /dev/null@@ -1,309 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Collapsible group Activity view: a runtime-only, bounded feed of truthful-// turn events (queued / working / replied / passed / timed-out / failed /-// cancelled / settled / delivered) that the room shows in a quiet disclosure.-// The transcript stays the only durable record — activity is never persisted.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--/** Load the plugin in a vm with a scripted gateway so member turns are- * deterministic. `turnScript(profile, prompt, n, session)` returns the- * member's reply text, a promise of it, or throws for a failed turn. */-function load(turnScript = () => '(pass)') {- 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 sessions = new Map()- const runtimeToStored = new Map()- const titleToStored = new Map()- let sessionSequence = 0-- const resolveSession = (profile, target) => {- const stored = runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))- return stored ? sessions.get(stored) : null- }- 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') {- sessionSequence += 1- const stored = `sid-${params.profile}-${sessionSequence}`- const runtime = `rt-${params.profile}-${sessionSequence}`- const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }- sessions.set(stored, session)- runtimeToStored.set(runtime, stored)- titleToStored.set(`${params.profile}::${params.title}`, stored)- return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }- }- if (method === 'session.resume') {- const session = resolveSession(params.profile, params.session_id)- if (!session) {- // Shaped like the real gateway's JsonRpcGatewayError (`.code`,- // apps/shared/src/json-rpc-gateway.ts) so ensureGroupChatSession's- // fail-closed `.code !== 4007` check sees the same "genuinely- // not found" signal production does.- const err = new Error(`session not found: ${params.session_id}`)- err.code = 4007- throw err- }- return {- session_id: session.runtime,- session_key: session.stored,- message_count: session.messages.length,- messages: [...session.messages],- inflight: false,- running: false- }- }- if (method === 'prompt.submit') {- const session = resolveSession(null, params.session_id)- if (!session) {- throw new Error(`runtime session not found: ${params.session_id}`)- }- session.messages.push({ role: 'user', content: params.text })- calls.push({- profile: session.profile,- prompt: params.text,- runtime: session.runtime,- stored: session.stored,- title: session.title- })- const reply = await turnScript(session.profile, params.text, calls.length, session)- session.messages.push({ role: 'assistant', content: reply })- 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.__ga = { sendToGroupChat, recordGroupActivity, currentGroupActivity, groupActivityLabel, updateGroupChat, $groupChats, $groupActivity, $botAttention, GROUP_ACTIVITY_LIMIT };\n'- )- vm.runInNewContext(source, context, { filename: 'plugin.js' })- const storageWrites = new Map()- context.plugin.register({- storage: { get: () => null, set: (key, value) => storageWrites.set(key, value) },- register: () => undefined- })- return { ...context.__ga, calls, sessions, storageWrites }-}--const MEMBERS = [{ name: 'research', title: '' }, { name: 'builder', title: '' }, { name: 'ops', title: 'The Ops' }]--async function drain(gc, group) {- for (let i = 0; i < 200 && (gc.$groupChats.get()[group] || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-}--function feed(gc, group) {- return gc.$groupActivity.get()[group]?.events || []-}--test('a settled turn records the full truthful arc: queued, working, replies and passes, settled', async () => {- const gc = load((profile, prompt) => {- if (profile === 'research' && !prompt.includes('(you)')) {- return 'I looked into it — ship it.'- }- return '(pass)'- })-- gc.sendToGroupChat('Room', MEMBERS, 'please review')- await drain(gc, 'Room')-- const events = feed(gc, 'Room')- const kinds = events.map(e => e.kind)- assert.equal(kinds[0], 'queued', 'the send lands first')- assert.equal(kinds[kinds.length - 1], 'settled', 'the run ends with a settle')- assert.equal(kinds.filter(k => k === 'working').length >= 3, true, 'every member on turn shows working')- assert.equal(kinds.includes('replied'), true, 'a real reply records replied')- assert.equal(kinds.filter(k => k === 'passed').length >= 2, true, 'silent members record passed')- const replied = events.find(e => e.kind === 'replied')- assert.equal(replied.member, 'research')-})--test('a failed member turn records failed instead of a phantom reply', async () => {- const gc = load(profile => {- if (profile === 'builder') {- throw new Error('gateway hiccup')- }- return '(pass)'- })-- gc.sendToGroupChat('Flaky', MEMBERS, 'anyone around?')- await drain(gc, 'Flaky')-- const events = feed(gc, 'Flaky')- assert.equal(events.some(e => e.kind === 'failed' && e.member === 'builder'), true)-})--test('a failed member turn preserves and prefers its typed reason', async () => {- const gc = load(profile => {- if (profile === 'builder') {- const error = new Error('generic gateway failure')- error.data = { reason: 'provider_auth_or_access' }- throw error- }- return '(pass)'- })-- gc.sendToGroupChat('Typed failure', MEMBERS, 'anyone around?')- await drain(gc, 'Typed failure')-- const failed = feed(gc, 'Typed failure').find(e => e.kind === 'failed' && e.member === 'builder')- assert.equal(failed.reason, 'provider_auth_or_access')- assert.equal(Object.values(gc.$botAttention.get())[0]?.reason, 'provider_auth_or_access')-})--test('an untyped failed member turn keeps the message-classification fallback', async () => {- const gc = load(profile => {- if (profile === 'builder') {- throw new Error('No LLM provider configured')- }- return '(pass)'- })-- gc.sendToGroupChat('Untyped failure', MEMBERS, 'anyone around?')- await drain(gc, 'Untyped failure')-- const failed = feed(gc, 'Untyped failure').find(e => e.kind === 'failed' && e.member === 'builder')- assert.equal(failed.reason, undefined)- assert.equal(Object.values(gc.$botAttention.get())[0]?.reason, 'missing_config')-})--test('a newer send interrupts the previous run and records cancelled in the CURRENT epoch', async () => {- const gates = [null, null]- const gate = n => {- gates[n] = gates[n] || { promise: null, resolve: null }- if (!gates[n].promise) {- gates[n].promise = new Promise(resolve => {- gates[n].resolve = resolve- })- }- return gates[n].promise- }- const gc = load((profile, prompt, n) => gate(n))- const member = [{ name: 'research', title: '' }]-- gc.sendToGroupChat('Busy', member, 'first ask')- for (let i = 0; i < 50 && gc.calls.length < 1; i++) {- await new Promise(resolve => setImmediate(resolve))- }- gc.sendToGroupChat('Busy', member, 'second ask, supersede')- for (let i = 0; i < 50 && gc.calls.length < 2; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- gates[2].resolve('from the new run')- await drain(gc, 'Busy')- gates[1].resolve('late from the old run')- await new Promise(resolve => setImmediate(resolve))- await new Promise(resolve => setImmediate(resolve))-- const epoch = (gc.$groupChats.get().Busy || {}).epoch || 0- const events = feed(gc, 'Busy')- assert.equal(events.some(e => e.kind === 'cancelled'), true, 'the superseded loop reports its own interruption')- // The view shows only the current run: every visible event is this epoch.- assert.equal(gc.currentGroupActivity('Busy').every(e => (e.epoch || 0) === epoch), true)- assert.equal(gc.currentGroupActivity('Busy').some(e => e.kind === 'cancelled'), true)-})--test('epoch filtering drops events from a superseded run', () => {- const gc = load()- gc.updateGroupChat('Epoch', r => {- r.log = []- r.epoch = 5- return r- })- gc.recordGroupActivity('Epoch', { kind: 'queued', member: 'You' })- gc.recordGroupActivity('Epoch', { kind: 'working', member: 'research' })-- gc.updateGroupChat('Epoch', r => {- r.epoch = 6- return r- })-- assert.equal(gc.currentGroupActivity('Epoch').length, 0, 'old-run events drop out of view')-- gc.recordGroupActivity('Epoch', { kind: 'working', member: 'research' })- const current = gc.currentGroupActivity('Epoch')- assert.equal(current.length, 1)- assert.equal(current[0].kind, 'working')-})--test('the feed is bounded and never grows past GROUP_ACTIVITY_LIMIT', () => {- const gc = load()- gc.updateGroupChat('Cap', r => {- r.log = []- return r- })-- for (let i = 0; i < gc.GROUP_ACTIVITY_LIMIT + 25; i++) {- gc.recordGroupActivity('Cap', { kind: 'working', member: 'research' })- }-- assert.equal(feed(gc, 'Cap').length, gc.GROUP_ACTIVITY_LIMIT)-})--test('activity is runtime-only: never persisted, never hydrated', async () => {- const gc = load()- gc.sendToGroupChat('Volatile', MEMBERS, 'hello')- await drain(gc, 'Volatile')-- assert.equal(gc.storageWrites.has('group-activity'), false, 'no activity storage key is ever written')- assert.doesNotMatch(pluginSource, /['"]group-activity['"]/, 'the plugin never reads or writes an activity key')-})--test('labels read like a person wrote them, with settled/cancelled as room-level lines', () => {- const gc = load()- assert.equal(gc.groupActivityLabel({ kind: 'queued', member: 'You' }), 'You sent a message')- assert.equal(gc.groupActivityLabel({ kind: 'replied', member: 'research' }), 'research replied')- assert.equal(gc.groupActivityLabel({ kind: 'timed-out', member: 'ops' }), 'ops took too long')- assert.equal(gc.groupActivityLabel({ kind: 'cancelled', member: null }), 'turn interrupted by a newer message')- assert.equal(gc.groupActivityLabel({ kind: 'settled', member: null }), 'turn settled')-})--test('source contract: the workspace mounts a quiet, collapsed-by-default disclosure', () => {- // Collapsed default — opening is always an explicit user action.- assert.match(pluginSource, /const \[activityOpen, setActivityOpen\] = useState\(false\)/)- // Accessible disclosure pattern.- assert.match(pluginSource, /'aria-expanded': activityOpen/)- assert.match(pluginSource, /'aria-controls': `group-activity:\$\{group\}`/)- // The panel body never steals focus and never auto-scrolls.- const panel = pluginSource.slice(pluginSource.indexOf('// Activity disclosure:'), pluginSource.indexOf('const submit = () => {'))- assert.doesNotMatch(panel, /autoFocus/)- assert.doesNotMatch(panel, /autoScroll|scrollIntoView/)- // Truthful event vocabulary is wired.- assert.match(pluginSource, /'timed-out': 'took too long'/)- assert.match(pluginSource, /cancelled: 'turn interrupted by a newer message'/)- // The panel sits inside the workspace between the header and the log.- const workspace = pluginSource.slice(pluginSource.indexOf('function GroupChatWorkspace('), pluginSource.indexOf('function GroupChatMainView('))- assert.match(workspace, /header,\s*\n\s*activityPanel,/s)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-chat-attachments.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-chat-attachments.test.mjsdeleted file mode 100644index 93d25162390..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-chat-attachments.test.mjs+++ /dev/null@@ -1,266 +0,0 @@-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')--/** Harness mirroring group-chat.test.mjs, extended to record image.attach_bytes- * calls so attachment staging order and fan-out are assertable. */-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 attaches = []- const sessions = new Map()- const runtimeToStored = new Map()- const titleToStored = new Map()- let sessionSequence = 0-- const resolveSession = (profile, target) => {- const stored = runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))- return stored ? sessions.get(stored) : null- }- 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') {- sessionSequence += 1- const stored = `sid-${params.profile}-${sessionSequence}`- const runtime = `rt-${params.profile}-${sessionSequence}`- const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }- sessions.set(stored, session)- runtimeToStored.set(runtime, stored)- titleToStored.set(`${params.profile}::${params.title}`, stored)- return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }- }- if (method === 'session.resume') {- const session = resolveSession(params.profile, params.session_id)- if (!session) {- // Shaped like the real gateway's JsonRpcGatewayError (`.code`,- // apps/shared/src/json-rpc-gateway.ts) so ensureGroupChatSession's- // fail-closed `.code !== 4007` check sees the same "genuinely- // not found" signal production does.- const err = new Error(`session not found: ${params.session_id}`)- err.code = 4007- throw err- }- return {- session_id: session.runtime,- session_key: session.stored,- message_count: session.messages.length,- messages: [...session.messages],- inflight: false,- running: false- }- }- if (method === 'image.attach_bytes' || method === 'pdf.attach' || method === 'file.attach') {- const session = resolveSession(null, params.session_id)- attaches.push({- method,- profile: session ? session.profile : null,- runtime: params.session_id,- filename: params.filename || params.name,- data: params.content_base64 || params.data_url,- order: calls.length // how many prompt.submits happened before this attach- })- if (method === 'file.attach') {- return { attached: true, ref_text: `@file:attachments/${params.name || 'attachment'}` }- }- return { attached: true }- }- if (method === 'prompt.submit') {- const session = resolveSession(null, params.session_id)- if (!session) {- throw new Error(`runtime session not found: ${params.session_id}`)- }- session.messages.push({ role: 'user', content: params.text })- calls.push({ profile: session.profile, prompt: params.text, runtime: session.runtime })- const reply = turnScript(session.profile, params.text, calls.length, session)- session.messages.push({ role: 'assistant', content: reply })- 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.__gca = { sendToGroupChat, formatGroupChatLine, $groupChats };\n'- )- vm.runInNewContext(source, context, { filename: 'plugin.js' })- context.plugin.register({- storage: { get: () => null, set: () => undefined },- register: () => undefined- })- return { ...context.__gca, calls, attaches, sessions }-}--const MEMBERS = [{ name: 'research', title: '' }, { name: 'builder', title: '' }]-const IMG = { name: 'screenshot.png', data: 'data:image/png;base64,iVBORw0KGgo=' }--async function drain(gc, group) {- for (let i = 0; i < 200 && (gc.$groupChats.get()[group] || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-}--test('attachments are staged into EVERY responding member session before its submit', async () => {- const gc = load(() => '(pass)')-- gc.sendToGroupChat('Vision', MEMBERS, 'what does this show?', null, [IMG])- await drain(gc, 'Vision')-- // Both members got the image, on their own per-group sessions.- assert.equal(gc.attaches.length, 2)- assert.deepEqual(gc.attaches.map(a => a.profile).sort(), ['builder', 'research'])- for (const attach of gc.attaches) {- assert.equal(attach.filename, 'screenshot.png')- assert.equal(attach.data, IMG.data)- }- // Each attach landed before that member's prompt.submit: the first attach- // happens before any submit, the second before the second submit.- assert.equal(gc.attaches[0].order, 0)- assert.ok(gc.attaches[1].order <= 1)- assert.equal(gc.calls.length, 2)-})--test('mention routing scopes attachments: only the mentioned member receives the image', async () => {- const gc = load(() => '(pass)')-- gc.sendToGroupChat('Scoped', MEMBERS, '@builder look at this', null, [IMG])- await drain(gc, 'Scoped')-- assert.deepEqual(gc.attaches.map(a => a.profile), ['builder'])-})--test('image-only send works and the room entry carries the attachment', async () => {- const gc = load(() => '(pass)')-- const minted = gc.sendToGroupChat('Silent', MEMBERS, '', null, [IMG])- await drain(gc, 'Silent')-- assert.ok(minted)- const log = gc.$groupChats.get().Silent.log- assert.equal(log.length, 1)- assert.equal(log[0].images.length, 1)- assert.equal(log[0].images[0].name, 'screenshot.png')- // Members still got prompted (with the image staged).- assert.equal(gc.attaches.length, 2)- assert.equal(gc.calls.length, 2)-})--test('a text-only send stages nothing and old entries never re-attach on later turns', async () => {- const gc = load(() => '(pass)')-- gc.sendToGroupChat('Plain', MEMBERS, 'with image', null, [IMG])- await drain(gc, 'Plain')- const afterFirst = gc.attaches.length- assert.equal(afterFirst, 2)-- // Second, text-only send: the image already sits behind every member's- // watermark, so no new attach calls may happen.- gc.sendToGroupChat('Plain', MEMBERS, 'plain follow-up')- await drain(gc, 'Plain')- assert.equal(gc.attaches.length, afterFirst)-})--test('formatGroupChatLine names attachments for user and member entries', () => {- const gc = load(() => '(pass)')-- const userLine = gc.formatGroupChatLine(- { from: { kind: 'user', name: 'You' }, text: 'see attached', images: [IMG] },- 'research'- )- assert.equal(userLine, 'You (user): see attached [attached image: screenshot.png]')-- const noImages = gc.formatGroupChatLine({ from: { kind: 'user', name: 'You' }, text: 'plain' }, 'research')- assert.equal(noImages, 'You (user): plain')-- const memberLine = gc.formatGroupChatLine(- { from: { kind: 'member', name: 'builder' }, text: 'made this', images: [{ data: 'data:image/png;base64,x' }] },- 'research'- )- assert.equal(memberLine, 'builder: made this [attached image: image]')-})--test('an invalid attachment is skipped and the member turn still runs text-only', async () => {- const gc = load(() => '(pass)')-- // runGroupChatMemberTurn skips entries without a string data field.- gc.sendToGroupChat('Degraded', MEMBERS, 'look', null, [{ name: 'bad', data: null }])- await drain(gc, 'Degraded')-- assert.equal(gc.attaches.length, 0) // invalid image skipped, no attach attempted- assert.equal(gc.calls.length, 2) // both turns still ran-})--const PDF = { name: 'spec.pdf', data: 'data:application/pdf;base64,JVBERi0=', kind: 'pdf' }-const DOC = { name: 'notes.txt', data: 'data:text/plain;base64,aGVsbG8=', kind: 'file' }--test('PDFs route through pdf.attach and files through file.attach, per member', async () => {- const gc = load(() => '(pass)')-- gc.sendToGroupChat('Mixed', MEMBERS, 'review these', null, [IMG, PDF, DOC])- await drain(gc, 'Mixed')-- // 3 attachments × 2 members, each via its own RPC.- assert.equal(gc.attaches.length, 6)- const byMethod = {}- for (const a of gc.attaches) {- byMethod[a.method] = (byMethod[a.method] || 0) + 1- }- assert.deepEqual(byMethod, { 'image.attach_bytes': 2, 'pdf.attach': 2, 'file.attach': 2 })-- const pdfAttach = gc.attaches.find(a => a.method === 'pdf.attach')- assert.equal(pdfAttach.filename, 'spec.pdf')- assert.equal(pdfAttach.data, PDF.data)-})--test('file.attach ref_text is appended to the member turn prompt', async () => {- const gc = load(() => '(pass)')-- gc.sendToGroupChat('Refs', MEMBERS, 'read the notes', null, [DOC])- await drain(gc, 'Refs')-- assert.equal(gc.calls.length, 2)- for (const call of gc.calls) {- assert.ok(call.prompt.includes('Attached files staged in your session workspace:'), 'prompt carries the staging note')- assert.ok(call.prompt.includes('notes.txt → @file:attachments/notes.txt'), 'prompt carries the @file: ref')- }-})--test('formatGroupChatLine labels PDFs and files distinctly', () => {- const gc = load(() => '(pass)')-- const line = gc.formatGroupChatLine(- { from: { kind: 'user', name: 'You' }, text: 'here', images: [PDF, DOC, IMG] },- 'research'- )- assert.equal(- line,- 'You (user): here [attached PDF: spec.pdf] [attached file: notes.txt] [attached image: screenshot.png]'- )-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-chat-empty-sentinel.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-chat-empty-sentinel.test.mjsdeleted file mode 100644index 80dcdfa67ab..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-chat-empty-sentinel.test.mjs+++ /dev/null@@ -1,242 +0,0 @@-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, { busyUntilResumeCall, clarifyUntilResumeCall, approvalUntilResumeCall, conflictOnce = false, deferredTimers = false } = {}) {- const values = new Map()- const atom = initial => {- const slot = { get: () => values.get(slot), set: value => {- if (process.env.TRACE_ATOM && value && typeof value === 'object' && value.Grind) {- console.error('ATOM SET Grind stranded=', JSON.stringify(value.Grind.stranded), new Error().stack.split('\n').slice(2,5).join(' | '))- }- values.set(slot, value)- } }- values.set(slot, initial)- return slot- }- const calls = []- const clarifyResponds = []- const approvalResponds = []- const requests = []- const sessions = new Map()- const runtimeToStored = new Map()- const titleToStored = new Map()- const sharedUiMeta = {}- const uiMetaRevisions = {}- let sessionSequence = 0- const resumeCallCounts = new Map()- let injectedConflict = false-- const resolveSession = (profile, target) => {- const stored = runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))- return stored ? sessions.get(stored) : null- }- const context = {- atom,- setTimeout: fn => {- if (deferredTimers) {- setImmediate(fn)- return 1- }- fn()- return 0- },- clearTimeout: () => undefined,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: {- request: async (method, params) => {- requests.push({ method, params })- if (method === 'profiles.list') {- return {- profiles: [- {- name: 'default',- ui_meta: { ...sharedUiMeta },- ui_meta_revisions: { ...uiMetaRevisions }- }- ]- }- }- if (method === 'profiles.configure') {- if (conflictOnce && !injectedConflict) {- injectedConflict = true- sharedUiMeta['hermes-bots-groups'] = {- version: 2,- rooms: {- Shared: {- revision: 1,- log: [{ id: 'writer-a:1', from: { kind: 'user', name: 'You' }, text: 'alpha', at: 1 }],- members: [{ name: 'alpha' }]- }- }- }- uiMetaRevisions['hermes-bots-groups'] = 1- return {- applied: {- ui_meta: false,- ui_meta_conflicts: { 'hermes-bots-groups': { expected: 0, actual: 1 } },- ui_meta_revisions: { 'hermes-bots-groups': 1 }- }- }- }- const expected = params.ui_meta_expected_revisions || null- if (expected) {- for (const key of Object.keys(params.ui_meta || {})) {- if ((uiMetaRevisions[key] || 0) !== expected[key]) {- return {- applied: {- ui_meta: false,- ui_meta_conflicts: {- [key]: { expected: expected[key], actual: uiMetaRevisions[key] || 0 }- }- }- }- }- }- }- for (const [key, value] of Object.entries(params.ui_meta || {})) {- if (value === null) {- delete sharedUiMeta[key]- } else {- sharedUiMeta[key] = value- }- uiMetaRevisions[key] = (uiMetaRevisions[key] || 0) + 1- }- return { applied: { ui_meta: true, ui_meta_revisions: { ...uiMetaRevisions } } }- }- if (method === 'session.create') {- sessionSequence += 1- const stored = `sid-${params.profile}-${sessionSequence}`- const runtime = `rt-${params.profile}-${sessionSequence}`- const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }- sessions.set(stored, session)- runtimeToStored.set(runtime, stored)- titleToStored.set(`${params.profile}::${params.title}`, stored)- return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }- }- if (method === 'session.resume') {- const session = resolveSession(params.profile, params.session_id)- if (!session) {- const err = new Error(`session not found: ${params.session_id}`)- err.code = 4007- throw err- }- const profile = params.profile- const seen = (resumeCallCounts.get(profile) || 0) + 1- resumeCallCounts.set(profile, seen)- const limit = busyUntilResumeCall && busyUntilResumeCall[profile]- const busy = Boolean(limit && seen <= limit)- const clarify = clarifyUntilResumeCall && clarifyUntilResumeCall[profile]- const pendingClarify = clarify && seen <= clarify.until ? clarify.payload : null- const approval = approvalUntilResumeCall && approvalUntilResumeCall[profile]- const pendingApproval = approval && seen <= approval.until ? approval.payload : null- return {- session_id: session.runtime,- session_key: session.stored,- message_count: session.messages.length,- messages: [...session.messages],- inflight: busy,- running: busy,- ...(pendingClarify ? { pending_clarify: pendingClarify } : {}),- ...(pendingApproval ? { pending_approval: pendingApproval } : {})- }- }- if (method === 'prompt.submit') {- const session = resolveSession(null, params.session_id)- if (!session) {- throw new Error(`runtime session not found: ${params.session_id}`)- }- session.messages.push({ role: 'user', content: params.text })- calls.push({- profile: session.profile,- prompt: params.text,- runtime: session.runtime,- stored: session.stored,- title: session.title- })- const reply = turnScript(session.profile, params.text, calls.length, session)- session.messages.push({ role: 'assistant', content: reply })- return {}- }- if (method === 'clarify.respond') {- clarifyResponds.push({ ...params })- return { ok: true }- }- if (method === 'approval.respond') {- approvalResponds.push({ ...params })- return { resolved: true }- }- 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, harvestStrandedGroupReply, resolveGroupResponders, parseGroupChatMentions, rotateGroupSpeakers, isGroupPassText, formatGroupChatLine, groupSpeakerLabel, buildGroupChatTurnPrompt, trimGroupChatLog, groupChatSyncSnapshot, groupChatGatewayJsonSize, mergeGroupChatSyncSnapshots, mergeRemoteGroupChatSnapshotIntoRooms, scheduleGroupChatServerSync, disbandGroupChat, renameGroupChat, updateGroupChat, durableGroupChatRooms, persistGroupChatRooms, ensureGroupChatSession, uniqueGroupChatName, liveGroupChatNames, groupChatNames, openGroupChat, closeGroupChatMainTab, shouldRenderGroupChatInPane, syncGroupClarify, clearGroupClarify, answerGroupClarify, $groupClarify, $groupChats, $groupNeedsYou, $groupChatWorkspace, $groupMainTabsRev, $botMeta, $lastRoster, GROUP_CHAT_MAX_ROUNDS, GROUP_CHAT_MAX_MESSAGES };\n'- )- vm.runInNewContext(source, context, { filename: 'plugin.js' })- const storageWrites = new Map()- context.plugin.register({- storage: { get: () => null, set: (key, value) => storageWrites.set(key, value) },- register: () => undefined- })- return { ...context.__gc, approvalResponds, calls, clarifyResponds, host: context.host, requests, sessions, storageWrites, sharedUiMeta, uiMetaRevisions }-}--function roomLog(gc, group) {- return (gc.$groupChats.get()[group] || { log: [] }).log-}--const FRIENDLY = '⚠️ The model returned no response after processing tool results. This can happen with some models — try again or rephrase your question.'--async function drain(gc, group) {- for (let i = 0; i < 200 && (gc.$groupChats.get()[group] || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-}--test('(empty) sentinel: a "(empty)" member reply is converted like the gateway, never appended raw', async () => {- const gc = load(profile => {- if (profile === 'research') return '(empty)'- return '(pass)'- })-- gc.sendToGroupChat('Sentinel', [{ name: 'research', title: '' }], '@research thoughts?')- await drain(gc, 'Sentinel')-- const memberEntries = roomLog(gc, 'Sentinel').filter(e => e.from.kind === 'member')- assert.ok(memberEntries.length === 1, `expected exactly 1 member entry, got ${memberEntries.length}`)- assert.equal(memberEntries[0].text, FRIENDLY)- assert.equal(memberEntries[0].text.includes('(empty)'), false)-})--test('(empty) sentinel: normal replies are untouched', async () => {- const gc = load(profile => {- if (profile === 'research') return 'I am not empty.'- return '(pass)'- })-- gc.sendToGroupChat('Sentinel2', [{ name: 'research', title: '' }], '@research hi')- await drain(gc, 'Sentinel2')-- const memberEntries = roomLog(gc, 'Sentinel2').filter(e => e.from.kind === 'member')- assert.equal(memberEntries.length, 1)- assert.equal(memberEntries[0].text, 'I am not empty.')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-chat-identity-edit.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-chat-identity-edit.test.mjsdeleted file mode 100644index 775c4ae536c..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-chat-identity-edit.test.mjs+++ /dev/null@@ -1,52 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--// Group chats have an editable identity: a name (renameable after creation)-// and a room picture (settable during creation and later via Group settings).-// Source-contract style, like the sibling group-chat tests.--test('source contract: creation dialog offers a room picture', () => {- // Shared picture controls (upload / generate / remove) mount in the create- // dialog, and a chosen image lands on the freshly created room record.- assert.match(pluginSource, /function GroupImageControls\(/)- assert.match(pluginSource, /if \(image\) \{\s*\n\s*room\.image = image/)-})--test('source contract: settings dialog edits name and picture after creation', () => {- assert.match(pluginSource, /function GroupChatSettingsDialog\(/)- assert.match(pluginSource, /function renameGroupChat\(/)- assert.match(pluginSource, /function setGroupChatImage\(/)- // The room header exposes the entry point.- assert.match(pluginSource, /Group settings — rename \$\{group\} or set a room picture/)-})--test('source contract: rename re-keys the room AND local memberships, keeps sessions', () => {- // The room record moves wholesale under the new key (sessions included, so- // members keep resuming their per-group sessions by stored sid).- assert.match(pluginSource, /const room = all\[oldName\][\s\S]{0,320}?delete all\[oldName\]/)- // Window-local composer drafts follow the immutable room identity too.- assert.match(pluginSource, /migrateGroupComposerDraft\(groupComposerDraftKey\(oldName, room\), groupComposerDraftKey\(next, room\)\)/)- // Local members' canonical groups lists swap old → new via ui_meta.- assert.match(pluginSource, /botGroups\(meta\)\.map\(g => \(g === oldName \? next : g\)\)/)- // Collisions are rejected, not silently suffixed — rename is explicit intent.- assert.match(pluginSource, /taken\.delete\(oldName\)/)-})--test('source contract: room picture persists and hydrates with the room record', () => {- // Durable writes carry image; hydration restores only a real string.- assert.match(pluginSource, /image: room\.image \|\| null/)- assert.match(pluginSource, /image: typeof room\.image === 'string' && room\.image \? room\.image : null/)-})--test('source contract: room picture shows in the roster row and room header', () => {- // Roster row: one room picture wins over a generic room icon when set.- const rowSource = pluginSource.slice(pluginSource.indexOf('function GroupRow('), pluginSource.indexOf('function RosterSectionHeader('))- assert.match(rowSource, /room\.image\s*\n\s*\? jsx\('img', \{/)- assert.match(rowSource, /name: 'organization'/)- assert.doesNotMatch(rowSource, /members\.slice\([^)]*\)\.map/)- // Header: picture leads the title.- assert.match(pluginSource, /Room picture \(set via Group settings\) leads the title when present/)-})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.mjsdeleted file mode 100644index 5d87ab0cebe..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs+++ /dev/null@@ -1,2100 +0,0 @@-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, { busyUntilResumeCall, clarifyUntilResumeCall, approvalUntilResumeCall, conflictOnce = false, deferredTimers = false } = {}) {- const values = new Map()- const atom = initial => {- const slot = { get: () => values.get(slot), set: value => {- if (process.env.TRACE_ATOM && value && typeof value === 'object' && value.Grind) {- console.error('ATOM SET Grind stranded=', JSON.stringify(value.Grind.stranded), new Error().stack.split('\n').slice(2,5).join(' | '))- }- values.set(slot, value)- } }- values.set(slot, initial)- return slot- }- const calls = []- const clarifyResponds = []- const approvalResponds = []- const requests = []- const sessions = new Map()- const runtimeToStored = new Map()- const titleToStored = new Map()- const sharedUiMeta = {}- const uiMetaRevisions = {}- let sessionSequence = 0- // busyUntilResumeCall[profile] = N: this profile's session.resume reports- // inflight/running for its first N calls, then flips to done — simulating- // a turn that is genuinely still running when harvested, without an- // unbounded real-time wait if a caller polls it (used to exercise the- // stranded/busy-responder guard).- const resumeCallCounts = new Map()- let injectedConflict = false-- const resolveSession = (profile, target) => {- const stored = runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))- return stored ? sessions.get(stored) : null- }- const context = {- atom,- setTimeout: fn => {- if (deferredTimers) {- setImmediate(fn)- return 1- }- fn()- return 0- },- clearTimeout: () => undefined,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: {- request: async (method, params) => {- requests.push({ method, params })- if (method === 'profiles.list') {- return {- profiles: [- {- name: 'default',- ui_meta: { ...sharedUiMeta },- ui_meta_revisions: { ...uiMetaRevisions }- }- ]- }- }- if (method === 'profiles.configure') {- if (conflictOnce && !injectedConflict) {- injectedConflict = true- sharedUiMeta['hermes-bots-groups'] = {- version: 2,- rooms: {- Shared: {- revision: 1,- log: [{ id: 'writer-a:1', from: { kind: 'user', name: 'You' }, text: 'alpha', at: 1 }],- members: [{ name: 'alpha' }]- }- }- }- uiMetaRevisions['hermes-bots-groups'] = 1- return {- applied: {- ui_meta: false,- ui_meta_conflicts: { 'hermes-bots-groups': { expected: 0, actual: 1 } },- ui_meta_revisions: { 'hermes-bots-groups': 1 }- }- }- }- const expected = params.ui_meta_expected_revisions || null- if (expected) {- for (const key of Object.keys(params.ui_meta || {})) {- if ((uiMetaRevisions[key] || 0) !== expected[key]) {- return {- applied: {- ui_meta: false,- ui_meta_conflicts: {- [key]: { expected: expected[key], actual: uiMetaRevisions[key] || 0 }- }- }- }- }- }- }- for (const [key, value] of Object.entries(params.ui_meta || {})) {- if (value === null) {- delete sharedUiMeta[key]- } else {- sharedUiMeta[key] = value- }- uiMetaRevisions[key] = (uiMetaRevisions[key] || 0) + 1- }- return { applied: { ui_meta: true, ui_meta_revisions: { ...uiMetaRevisions } } }- }- if (method === 'session.create') {- sessionSequence += 1- const stored = `sid-${params.profile}-${sessionSequence}`- const runtime = `rt-${params.profile}-${sessionSequence}`- const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }- sessions.set(stored, session)- runtimeToStored.set(runtime, stored)- titleToStored.set(`${params.profile}::${params.title}`, stored)- return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }- }- if (method === 'session.resume') {- const session = resolveSession(params.profile, params.session_id)- if (!session) {- // Shaped like the real gateway's JsonRpcGatewayError (a `.code`- // property, per apps/shared/src/json-rpc-gateway.ts) so- // ensureGroupChatSession's fail-closed `.code !== 4007` check- // exercises the same branch production sees. 4007 mirrors- // session.resume's own "session not found" JSON-RPC error code- // (tui_gateway/methods_session.py).- const err = new Error(`session not found: ${params.session_id}`)- err.code = 4007- throw err- }- const profile = params.profile- const seen = (resumeCallCounts.get(profile) || 0) + 1- resumeCallCounts.set(profile, seen)- const limit = busyUntilResumeCall && busyUntilResumeCall[profile]- const busy = Boolean(limit && seen <= limit)- // clarifyUntilResumeCall[profile] = {payload, until}: the resume- // snapshot carries pending_clarify for the first `until` calls —- // simulating a member blocked on its clarify tool (#90694).- const clarify = clarifyUntilResumeCall && clarifyUntilResumeCall[profile]- const pendingClarify = clarify && seen <= clarify.until ? clarify.payload : null- // Same window shape for pending command approvals (#90694 class).- const approval = approvalUntilResumeCall && approvalUntilResumeCall[profile]- const pendingApproval = approval && seen <= approval.until ? approval.payload : null- return {- session_id: session.runtime,- session_key: session.stored,- message_count: session.messages.length,- messages: [...session.messages],- inflight: busy,- running: busy,- ...(pendingClarify ? { pending_clarify: pendingClarify } : {}),- ...(pendingApproval ? { pending_approval: pendingApproval } : {})- }- }- if (method === 'prompt.submit') {- const session = resolveSession(null, params.session_id)- if (!session) {- throw new Error(`runtime session not found: ${params.session_id}`)- }- session.messages.push({ role: 'user', content: params.text })- calls.push({- profile: session.profile,- prompt: params.text,- runtime: session.runtime,- stored: session.stored,- title: session.title- })- const reply = turnScript(session.profile, params.text, calls.length, session)- session.messages.push({ role: 'assistant', content: reply })- return {}- }- if (method === 'clarify.respond') {- clarifyResponds.push({ ...params })- return { ok: true }- }- if (method === 'approval.respond') {- approvalResponds.push({ ...params })- return { resolved: true }- }- 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, harvestStrandedGroupReply, resolveGroupResponders, parseGroupChatMentions, rotateGroupSpeakers, isGroupPassText, formatGroupChatLine, groupSpeakerLabel, buildGroupChatTurnPrompt, trimGroupChatLog, groupChatSyncSnapshot, groupChatGatewayJsonSize, mergeGroupChatSyncSnapshots, mergeRemoteGroupChatSnapshotIntoRooms, scheduleGroupChatServerSync, disbandGroupChat, renameGroupChat, updateGroupChat, durableGroupChatRooms, persistGroupChatRooms, ensureGroupChatSession, uniqueGroupChatName, liveGroupChatNames, groupChatNames, openGroupChat, closeGroupChatMainTab, shouldRenderGroupChatInPane, syncGroupClarify, clearGroupClarify, answerGroupClarify, $groupClarify, $groupChats, $groupNeedsYou, $groupChatWorkspace, $groupMainTabsRev, $botMeta, $lastRoster, GROUP_CHAT_MAX_ROUNDS, GROUP_CHAT_MAX_MESSAGES };\n'- )- vm.runInNewContext(source, context, { filename: 'plugin.js' })- const storageWrites = new Map()- context.plugin.register({- storage: { get: () => null, set: (key, value) => storageWrites.set(key, value) },- register: () => undefined- })- return { ...context.__gc, approvalResponds, calls, clarifyResponds, host: context.host, requests, sessions, storageWrites, sharedUiMeta, uiMetaRevisions }-}--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('concurrent groups sharing one member keep sessions, deltas, and context isolated', async () => {- const gc = load(() => '(pass)')- const sharedMember = [{ name: 'research', title: '' }]-- // Start both rooms without waiting for either drive to finish.- gc.sendToGroupChat('Alpha', sharedMember, 'ALPHA_ONLY_1')- gc.sendToGroupChat('Beta', sharedMember, 'BETA_ONLY_1')- for (let i = 0; i < 400; i++) {- const rooms = gc.$groupChats.get()- if (!rooms.Alpha?.running && !rooms.Beta?.running) {- break- }- await new Promise(resolve => setImmediate(resolve))- }-- const alphaFirst = gc.calls.find(call => call.title === 'Group: Alpha')- const betaFirst = gc.calls.find(call => call.title === 'Group: Beta')- assert.ok(alphaFirst && betaFirst, 'the shared member took one turn in each room')- assert.notEqual(alphaFirst.stored, betaFirst.stored, 'each room owns a distinct stored session')- assert.notEqual(alphaFirst.runtime, betaFirst.runtime, 'each room owns a distinct runtime session')- assert.equal(alphaFirst.prompt.includes('ALPHA_ONLY_1'), true)- assert.equal(alphaFirst.prompt.includes('BETA_ONLY_1'), false)- assert.equal(betaFirst.prompt.includes('BETA_ONLY_1'), true)- assert.equal(betaFirst.prompt.includes('ALPHA_ONLY_1'), false)-- const roomsAfterFirst = gc.$groupChats.get()- assert.equal(roomsAfterFirst.Alpha.sessions.research, alphaFirst.stored)- assert.equal(roomsAfterFirst.Beta.sessions.research, betaFirst.stored)-- // Interleave a second pair. Each room resumes its own session and receives- // only its unseen room delta, never the sibling room's messages.- const firstCallCount = gc.calls.length- gc.sendToGroupChat('Alpha', sharedMember, 'ALPHA_ONLY_2')- gc.sendToGroupChat('Beta', sharedMember, 'BETA_ONLY_2')- for (let i = 0; i < 400; i++) {- const rooms = gc.$groupChats.get()- if (!rooms.Alpha?.running && !rooms.Beta?.running) {- break- }- await new Promise(resolve => setImmediate(resolve))- }-- const secondCalls = gc.calls.slice(firstCallCount)- const alphaSecond = secondCalls.find(call => call.title === 'Group: Alpha')- const betaSecond = secondCalls.find(call => call.title === 'Group: Beta')- assert.ok(alphaSecond && betaSecond, 'both rooms resumed for the second pair')- assert.equal(alphaSecond.stored, alphaFirst.stored)- assert.equal(betaSecond.stored, betaFirst.stored)- assert.equal(alphaSecond.prompt.includes('ALPHA_ONLY_2'), true)- assert.equal(alphaSecond.prompt.includes('ALPHA_ONLY_1'), false, 'Alpha first delta was already seen')- assert.equal(alphaSecond.prompt.includes('BETA_ONLY_2'), false)- assert.equal(betaSecond.prompt.includes('BETA_ONLY_2'), true)- assert.equal(betaSecond.prompt.includes('BETA_ONLY_1'), false, 'Beta first delta was already seen')- assert.equal(betaSecond.prompt.includes('ALPHA_ONLY_2'), false)-- const alphaSession = gc.sessions.get(alphaFirst.stored)- const betaSession = gc.sessions.get(betaFirst.stored)- assert.equal(alphaSession.messages.some(message => String(message.content).includes('BETA_ONLY')), false)- assert.equal(betaSession.messages.some(message => String(message.content).includes('ALPHA_ONLY')), false)-})--test('recreating a same-name group after disband mints fresh member sessions', async () => {- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }-- // First incarnation of the room.- gc.updateGroupChat('Alpha', r => {- r.roomId = 'r-one'- return r- })- const first = await gc.ensureGroupChatSession('Alpha', member)-- // Disband: the room record is gone; the member's gateway session survives.- const rooms = { ...gc.$groupChats.get() }- delete rooms.Alpha- gc.$groupChats.set(rooms)-- // Recreate under the same display name with a freshly minted roomId.- gc.updateGroupChat('Alpha', r => {- r.roomId = 'r-two'- return r- })- const second = await gc.ensureGroupChatSession('Alpha', member)-- assert.notEqual(first.stored, second.stored, 'the recreated room must not resume the old member session')- assert.equal(gc.sessions.get(first.stored).title, 'Group: r-one')- assert.equal(gc.sessions.get(second.stored).title, 'Group: r-two')-})--test('a transient resume failure fails closed instead of forking the member session', async () => {- // Mirrors findExistingCanonicalChat's fix (87b645f52c): a resume that- // fails for any reason OTHER than "genuinely doesn't exist" (JSON-RPC- // code 4007) must surface, not be read as "no session, mint a new one" —- // that would fork the member's real history and silently overwrite- // room.sessions[key] so the old session becomes unreachable.- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }-- gc.updateGroupChat('Alpha', r => {- r.roomId = 'r-one'- return r- })- const first = await gc.ensureGroupChatSession('Alpha', member)- const roomBefore = gc.$groupChats.get().Alpha-- // Simulate a transient failure (backend still warming up after a restart,- // a network blip on a cross-connection lookup, ...) on the NEXT resume of- // the member's own stored session — a real gateway error, not "not found".- const originalRequest = gc.host.request- gc.host.request = async (method, params) => {- if (method === 'session.resume' && params.session_id === first.stored) {- const err = new Error('gateway temporarily unavailable')- err.code = 5000- throw err- }- return originalRequest(method, params)- }-- await assert.rejects(- () => gc.ensureGroupChatSession('Alpha', member),- /Could not check .*group session/- )-- gc.host.request = originalRequest-- // Nothing was forked: the room's session pointer is untouched, and the- // original session is still the only one on record for this member.- assert.deepEqual(gc.$groupChats.get().Alpha.sessions, roomBefore.sessions)- assert.equal(gc.sessions.size, 1)-})--test('a genuinely nonexistent stored session (4007) still falls through to the title lookup, then create', async () => {- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }-- gc.updateGroupChat('Alpha', r => {- r.roomId = 'r-one'- return r- })-- // A stored sid pointing at a session the gateway no longer has (e.g. an- // out-of-band deletion) is a genuine 4007 on the first target — the loop- // must still try the title lookup and, finding nothing there either,- // create a fresh session rather than throwing.- gc.updateGroupChat('Alpha', r => {- r.sessions = { research: 'sid-gone' }- return r- })-- const result = await gc.ensureGroupChatSession('Alpha', member)- assert.ok(result.stored, 'a fresh session must be minted when nothing resumable exists')- assert.notEqual(result.stored, 'sid-gone')-})--test('group session titles are pinned to the roomId, with a legacy fallback to the display name', async () => {- const gc = load(() => '(pass)')-- // Rooms persisted before roomIds keep name-based titles so their existing- // "Group: <name>" sessions keep resolving after an upgrade.- gc.updateGroupChat('Legacy', r => r)- const legacy = await gc.ensureGroupChatSession('Legacy', { name: 'research', title: '' })- assert.equal(gc.sessions.get(legacy.stored).title, 'Group: Legacy')-- // New rooms pin the title to the immutable roomId, never the display name.- gc.updateGroupChat('New', r => {- r.roomId = 'r-abc'- return r- })- const fresh = await gc.ensureGroupChatSession('New', { name: 'research', title: '' })- assert.equal(gc.sessions.get(fresh.stored).title, 'Group: r-abc')-})--test('same-name group dedup reserves suffix length at the 64-char cap', () => {- const gc = load(() => '(pass)')-- assert.equal(gc.uniqueGroupChatName('Team', new Set(['Other'])), 'Team')-- // Slicing the joined string would chop the " 2"/" 3" suffix off a- // max-length base and collide with the original forever.- const base = 'x'.repeat(64)- const taken = new Set([base, `${base.slice(0, 62)} 2`])-- const next = gc.uniqueGroupChatName(base, taken)-- assert.notEqual(next, base)- assert.equal(next.length, 64)- assert.equal(next, `${base.slice(0, 62)} 3`)-})--test('roomId persists with the room record and survives disband of other rooms', async () => {- const gc = load(() => '(pass)')-- gc.updateGroupChat('Keep', r => {- r.roomId = 'r-keep'- return r- })- gc.updateGroupChat('Gone', r => {- r.roomId = 'r-gone'- return r- })-- await gc.disbandGroupChat('Gone', [{ name: 'builder' }])-- const durable = gc.storageWrites.get('group-chats')- assert.equal(durable.Keep.roomId, 'r-keep', 'roomId survives disband of another room')- assert.ok(!('Gone' in durable), 'disbanded room not persisted')-})--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: \$\{room\.roomId \|\| 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('group room messages and members mirror through bounded gateway profile metadata', async () => {- const gc = load(() => '(pass)')- const members = [- { name: 'research', handle: 'research' },- { name: 'builder', handle: 'builder' }- ]- gc.sendToGroupChat('Research', members, 'What changed?')- for (let i = 0; i < 200 && (gc.$groupChats.get().Research || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- const configure = gc.requests.filter(call => call.method === 'profiles.configure').at(-1)- assert.ok(configure, 'room updates are mirrored to the gateway')- assert.equal(configure.params.name, 'default')- const envelope = configure.params.ui_meta['hermes-bots-groups']- assert.equal(envelope.version, 3)- const researchKey = Object.keys(envelope.rooms).find(key => envelope.rooms[key].name === 'Research')- assert.ok(researchKey, 'Research room present under its durable key')- assert.equal(envelope.rooms[researchKey].log[0].text, 'What changed?')- assert.equal(JSON.stringify(envelope.rooms[researchKey].members.map(member => member.name)), JSON.stringify(['research', 'builder']))- assert.ok(gc.groupChatGatewayJsonSize(envelope) <= 48000)-})--test('group gateway mirror is size bounded and favors recent messages', () => {- const gc = load(() => '(pass)')- const long = 'x'.repeat(5000)- const snapshot = gc.groupChatSyncSnapshot({- Large: {- log: Array.from({ length: 100 }, (_, index) => ({- from: { kind: index % 2 ? 'member' : 'user', name: index % 2 ? 'research' : 'You' },- text: `${index}:${long}`,- at: index- }))- }- })-- assert.ok(gc.groupChatGatewayJsonSize(snapshot) <= 48000)- assert.ok(snapshot.rooms['name:Large'].log.length <= 16)- assert.match(snapshot.rooms['name:Large'].log.at(-1).text, /^99:/)- assert.ok(snapshot.rooms['name:Large'].log.at(-1).text.length <= 1200)-})--test('group gateway mirror preserves threads and budgets escaped Unicode', () => {- const gc = load(() => '(pass)')- const snapshot = gc.groupChatSyncSnapshot({- Unicode: {- log: Array.from({ length: 16 }, (_, index) => ({- from: { kind: 'member', name: 'research' },- text: `message ${index} ${'🧠'.repeat(1200)}`,- at: index,- thread: `thread-${index}`- }))- }- })-- assert.ok(gc.groupChatGatewayJsonSize(snapshot) <= 48000)- assert.equal(snapshot.rooms['name:Unicode'].log.at(-1).thread, 'thread-15')-})--test('empty runtime rooms are omitted from the gateway mirror', () => {- const gc = load(() => '(pass)')- const snapshot = gc.groupChatSyncSnapshot({- Disbanded: { log: [], members: [{ name: 'research' }] }- })-- assert.deepEqual(Object.keys(snapshot.rooms), [])-})--test('an empty hydrate cannot erase a shared gateway room mirror', () => {- const gc = load(() => '(pass)')- const before = gc.requests.length-- gc.scheduleGroupChatServerSync({})-- assert.equal(gc.requests.length, before)-})--test('an explicit final-room disband may clear the gateway room mirror', async () => {- const gc = load(() => '(pass)')-- gc.scheduleGroupChatServerSync({}, { allowEmpty: true, deletedRooms: ['Research'] })- await new Promise(resolve => setImmediate(resolve))-- const configure = gc.requests.filter(call => call.method === 'profiles.configure').at(-1)- assert.deepEqual(Object.keys(configure.params.ui_meta['hermes-bots-groups'].rooms), [])- assert.ok(configure.params.ui_meta['hermes-bots-groups'].deleted['name:Research'] > 0)-})--test('pull-before-push merge preserves disjoint rooms, messages, and members', () => {- const gc = load(() => '(pass)')- const merged = gc.mergeGroupChatSyncSnapshots(- {- version: 1,- rooms: {- Shared: {- log: [{ from: { kind: 'user', name: 'You' }, text: 'remote', at: 1, thread: 'one' }],- members: [{ name: 'research', handle: 'research' }]- },- RemoteOnly: {- log: [{ from: { kind: 'member', name: 'ops' }, text: 'kept', at: 2 }],- members: [{ name: 'ops' }]- }- }- },- {- version: 1,- rooms: {- Shared: {- log: [{ from: { kind: 'member', name: 'builder' }, text: 'local', at: 3, thread: 'one' }],- members: [{ name: 'builder', handle: 'builder' }]- }- }- }- )-- assert.equal(JSON.stringify(merged.rooms['name:Shared'].log.map(entry => entry.text)), JSON.stringify(['remote', 'local']))- assert.equal(JSON.stringify(merged.rooms['name:Shared'].members.map(member => member.name)), JSON.stringify(['research', 'builder']))- assert.equal(merged.rooms['name:RemoteOnly'].log[0].text, 'kept')-})--test('gateway projection hydrates a cold Desktop without dropping local runtime fields', () => {- const gc = load(() => '(pass)')- const merged = gc.mergeRemoteGroupChatSnapshotIntoRooms(- {- rooms: {- Shared: {- log: [- { from: { kind: 'user', name: 'You' }, text: 'remote question', at: 10, thread: 'thread-1' },- { from: { kind: 'member', name: 'research' }, text: 'remote answer', at: 20, thread: 'thread-1' }- ],- members: [{ name: 'research', connectionId: 'mini', sourceScoped: true }]- }- }- },- {- Local: {- log: [{ from: { kind: 'user', name: 'You' }, text: 'local', at: 5, thread: 'thread-local' }],- watermarks: { builder: 1 },- sessions: { builder: 'session-1' },- members: [{ name: 'builder' }],- epoch: 7,- running: true- }- }- )-- assert.equal(- JSON.stringify(merged.Shared.log.map(entry => entry.text)),- JSON.stringify(['remote question', 'remote answer'])- )- assert.equal(merged.Shared.members[0].remoteSource, true)- assert.equal(merged.Local.sessions.builder, 'session-1')- assert.equal(merged.Local.epoch, 7)- assert.equal(merged.Local.running, true)-})--test('room deletion tombstone wins over stale history but not a later recreation', () => {- const gc = load(() => '(pass)')- const stale = gc.mergeGroupChatSyncSnapshots(- {- version: 2,- rooms: { Research: { revision: 1, log: [{ id: 'old', from: { kind: 'user', name: 'You' }, text: 'old', at: 10 }] } }- },- { version: 2, rooms: {}, deleted: { Research: 2 } }- )- assert.equal(stale.rooms['name:Research'], undefined)- assert.equal(stale.deleted['name:Research'], 2)-- const recreated = gc.mergeGroupChatSyncSnapshots(stale, {- version: 2,- rooms: { Research: { revision: 3, log: [{ id: 'new', from: { kind: 'user', name: 'You' }, text: 'new', at: 1 }] } }- })- assert.equal(recreated.rooms['name:Research'].log[0].text, 'new')- assert.equal(recreated.deleted, undefined)-})--test('gateway revisions, not device clocks, order room deletion and recreation', () => {- const gc = load(() => '(pass)')- const merged = gc.mergeGroupChatSyncSnapshots(- {- version: 2,- rooms: {- ClockSkewed: {- revision: 8,- log: [{ id: 'future-clock', from: { kind: 'user', name: 'You' }, text: 'old', at: 9999999999999 }]- }- }- },- { version: 2, rooms: {}, deleted: { ClockSkewed: 9 } }- )-- assert.equal(merged.rooms['name:ClockSkewed'], undefined)- assert.equal(merged.deleted['name:ClockSkewed'], 9)-})--test('a conflicting writer can merge the winner and preserve both stable message ids', () => {- const gc = load(() => '(pass)')- const winner = {- version: 2,- rooms: {- Shared: {- revision: 1,- log: [{ id: 'writer-a:1', from: { kind: 'user', name: 'You' }, text: 'alpha', at: 100 }],- members: [{ name: 'alpha' }]- }- }- }- const loserRetry = gc.mergeGroupChatSyncSnapshots(- winner,- {- version: 2,- rooms: {- Shared: {- revision: 0,- log: [{ id: 'writer-b:1', from: { kind: 'member', name: 'beta' }, text: 'beta', at: 1 }],- members: [{ name: 'beta' }]- }- }- },- { changedRooms: ['Shared'], writeRevision: 2 }- )-- assert.equal(- JSON.stringify(loserRetry.rooms['name:Shared'].log.map(entry => entry.id).sort()),- JSON.stringify(['writer-a:1', 'writer-b:1'])- )- assert.equal(loserRetry.rooms['name:Shared'].revision, 2)-})--test('sync worker retries a gateway CAS conflict and publishes the merged room', async () => {- const gc = load(() => '(pass)', { conflictOnce: true, deferredTimers: true })- gc.$groupChats.set({- Shared: {- log: [{ id: 'writer-b:1', from: { kind: 'member', name: 'beta' }, text: 'beta', at: 2 }],- members: [{ name: 'beta' }],- watermarks: {},- sessions: {},- syncRevision: 0- }- })-- gc.scheduleGroupChatServerSync(gc.$groupChats.get(), { changedRooms: ['Shared'] })- for (let i = 0; i < 20 && (gc.uiMetaRevisions['hermes-bots-groups'] || 0) < 2; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- const stored = gc.sharedUiMeta['hermes-bots-groups']- assert.equal(gc.uiMetaRevisions['hermes-bots-groups'], 2)- assert.equal(- JSON.stringify(stored.rooms['name:Shared'].log.map(entry => entry.id).sort()),- JSON.stringify(['writer-a:1', 'writer-b:1'])- )- assert.equal(- gc.requests.filter(call => call.method === 'profiles.configure').length,- 2- )-})--test('read-back does not clobber a newer local room edit queued during an in-flight write', () => {- const gc = load(() => '(pass)')- const merged = gc.mergeRemoteGroupChatSnapshotIntoRooms(- {- version: 2,- rooms: {- Shared: {- revision: 5,- log: [{ id: 'remote', from: { kind: 'user', name: 'You' }, text: 'remote message', at: 1 }],- members: [{ name: 'old-member' }],- image: 'data:image/png;base64,old'- }- }- },- {- Shared: {- syncRevision: 4,- log: [{ id: 'local', from: { kind: 'user', name: 'You' }, text: 'local message', at: 2 }],- members: [{ name: 'new-member' }],- image: 'data:image/png;base64,new'- }- },- { preserveRooms: ['Shared'] }- )-- assert.equal(JSON.stringify(merged.Shared.members.map(member => member.name)), JSON.stringify(['new-member']))- assert.equal(merged.Shared.image, 'data:image/png;base64,new')- assert.equal(merged.Shared.syncRevision, 4)- assert.equal(- JSON.stringify(merged.Shared.log.map(entry => entry.id).sort()),- JSON.stringify(['local', 'remote'])- )-})--test('rename publishes a new room plus old-name tombstone and cold hydrate cannot resurrect it', () => {- const gc = load(() => '(pass)')- const before = {- version: 2,- rooms: {- Old: {- revision: 4,- log: [{ id: 'turn-1', from: { kind: 'user', name: 'You' }, text: 'history', at: 10 }],- members: [{ name: 'research' }],- image: 'data:image/png;base64,room'- }- }- }- const after = gc.mergeGroupChatSyncSnapshots(- before,- {- version: 2,- rooms: {- New: {- revision: 4,- log: before.rooms.Old.log,- members: before.rooms.Old.members,- image: before.rooms.Old.image- }- }- },- { changedRooms: ['New'], deletedRooms: ['Old'], writeRevision: 5 }- )- const hydrated = gc.mergeRemoteGroupChatSnapshotIntoRooms(after, {})-- assert.equal(after.rooms['name:Old'], undefined)- assert.equal(after.deleted['name:Old'], 5)- assert.equal(after.rooms['name:New'].revision, 5)- assert.equal(after.rooms['name:New'].image, 'data:image/png;base64,room')- assert.equal(hydrated.Old, undefined)- assert.equal(hydrated.New.log[0].text, 'history')- assert.equal(hydrated.New.image, 'data:image/png;base64,room')-})--test('room identity class: rename with a roomId is a same-key field update, never delete+create', () => {- const gc = load(() => '(pass)')- const before = {- version: 3,- rooms: {- 'id:room-42': {- name: 'Old',- roomId: 'room-42',- revision: 4,- log: [{ id: 'turn-1', from: { kind: 'user', name: 'You' }, text: 'history', at: 10 }],- members: [{ name: 'research' }]- }- }- }- const after = gc.mergeGroupChatSyncSnapshots(- before,- {- version: 3,- rooms: {- 'id:room-42': { ...before.rooms['id:room-42'], name: 'New' }- }- },- { changedRooms: ['id:room-42'], writeRevision: 5 }- )-- // Same durable key, new display name, no tombstone needed at all.- assert.equal(Object.keys(after.rooms).length, 1)- assert.equal(after.rooms['id:room-42'].name, 'New')- assert.equal(after.rooms['id:room-42'].revision, 5)- assert.equal(after.deleted, undefined)-- // A lagging gateway still holding the OLD name under the same id cannot- // resurrect it: same key, lower revision, identity follows the winner.- const lagged = gc.mergeGroupChatSyncSnapshots(before, after)- assert.equal(lagged.rooms['id:room-42'].name, 'New')-})--test('room identity class: id tombstones are final even against a higher-revision lagging copy', () => {- const gc = load(() => '(pass)')- const merged = gc.mergeGroupChatSyncSnapshots(- {- version: 3,- // A gateway that was OFFLINE during the disband still carries the room- // with a high revision from busy pre-disband traffic.- rooms: {- 'id:room-9': {- name: 'Zombie',- roomId: 'room-9',- revision: 40,- log: [{ id: 'stale', from: { kind: 'user', name: 'You' }, text: 'stale', at: 1 }]- }- }- },- { version: 3, rooms: {}, deleted: { 'id:room-9': 3 } }- )-- assert.equal(merged.rooms['id:room-9'], undefined, 'disbanded id-keyed room stays dead')- assert.equal(merged.deleted['id:room-9'], 3, 'tombstone survives for other lagging gateways')-- // Same-name RECREATION is unaffected: the new room minted a fresh id.- const recreated = gc.mergeGroupChatSyncSnapshots(merged, {- version: 3,- rooms: {- 'id:room-10': {- name: 'Zombie',- roomId: 'room-10',- revision: 1,- log: [{ id: 'fresh', from: { kind: 'user', name: 'You' }, text: 'fresh', at: 2 }]- }- }- })- assert.equal(recreated.rooms['id:room-10'].log[0].text, 'fresh')- assert.equal(recreated.rooms['id:room-9'], undefined)-})--test('room identity class: cold hydrate follows a remote rename via roomId instead of duplicating', () => {- const gc = load(() => '(pass)')- const merged = gc.mergeRemoteGroupChatSnapshotIntoRooms(- {- version: 3,- rooms: {- 'id:room-7': {- name: 'Renamed',- roomId: 'room-7',- revision: 6,- log: [{ id: 'm1', from: { kind: 'user', name: 'You' }, text: 'hello', at: 1 }],- members: [{ name: 'research' }]- }- }- },- {- // Local copy still under the pre-rename display name, same roomId.- Original: {- roomId: 'room-7',- syncRevision: 5,- log: [{ id: 'm1', from: { kind: 'user', name: 'You' }, text: 'hello', at: 1 }],- watermarks: {},- sessions: { research: 'sid-1' },- members: [{ name: 'research' }]- }- }- )-- assert.equal(merged.Original, undefined, 'old display name is re-keyed, not duplicated')- assert.equal(merged.Renamed.roomId, 'room-7')- assert.equal(merged.Renamed.sessions.research, 'sid-1', 'runtime fields survive the re-key')-})--test('room identity class: renaming an id-keyed room via the rename job shape never tombstones it', () => {- const gc = load(() => '(pass)')- const remote = {- version: 3,- rooms: {- 'id:room-3': {- name: 'Old',- roomId: 'room-3',- revision: 2,- log: [{ id: 'h1', from: { kind: 'user', name: 'You' }, text: 'history', at: 5 }],- members: [{ name: 'research' }]- }- }- }- // Exactly what renameGroupChat schedules: changed [new], deleted [old].- const after = gc.mergeGroupChatSyncSnapshots(- remote,- {- version: 3,- rooms: {- 'id:room-3': { ...remote.rooms['id:room-3'], name: 'New' }- }- },- { changedRooms: ['New'], deletedRooms: ['Old'], writeRevision: 3 }- )- assert.ok(after.rooms['id:room-3'], 'renamed room survives its own rename job')- assert.equal(after.rooms['id:room-3'].name, 'New')- assert.equal(after.deleted?.['id:room-3'], undefined, 'no id tombstone for a same-id rename')- // A residual name:Old tombstone is correct — it retires stale v2/legacy- // copies of this room that older clients published under the name key.- assert.equal(after.deleted?.['name:Old'], 3)-- // Hydrate path: the pull that races the rename write must not delete the- // locally re-keyed record just because the remote copy still says Old.- const merged = gc.mergeRemoteGroupChatSnapshotIntoRooms(remote, {- New: {- roomId: 'room-3',- syncRevision: 2,- log: remote.rooms['id:room-3'].log,- watermarks: {},- sessions: { research: 'sid-9' },- members: [{ name: 'research' }]- }- }, { preserveRooms: ['New'], deletedRooms: ['Old'] })- assert.ok(merged.New, 'locally renamed room survives a stale-name pull')- assert.equal(merged.New.sessions.research, 'sid-9')- assert.equal(merged.Old, undefined)-})--test('fan-out class: a room write is mirrored to every reachable default-profile gateway', async () => {- const gc = load(() => '(pass)', { deferredTimers: true })- const remoteRequests = []- gc.host.profileRoutes = async () => [- { connectionId: 'gw-a', profile: 'default' },- { connectionId: 'gw-b', profile: 'default' },- { connectionId: 'gw-b', profile: 'other' }- ]- gc.host.requestProfile = async (route, method) => {- remoteRequests.push({ connectionId: route.connectionId, method })- if (method === 'profiles.list') {- return { profiles: [{ name: 'default', ui_meta: {}, ui_meta_revisions: {} }] }- }- if (method === 'profiles.configure') {- return { applied: { ui_meta: true, ui_meta_revisions: { 'hermes-bots-groups': 1 } } }- }- return {}- }-- gc.$groupChats.set({- Shared: {- log: [{ id: 'w1', from: { kind: 'user', name: 'You' }, text: 'hi', at: 1 }],- members: [{ name: 'research' }],- watermarks: {},- sessions: {},- syncRevision: 0- }- })- gc.scheduleGroupChatServerSync(gc.$groupChats.get(), { changedRooms: ['Shared'] })- for (let i = 0; i < 60 && remoteRequests.filter(r => r.method === 'profiles.configure').length < 2; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- const configured = new Set(- remoteRequests.filter(r => r.method === 'profiles.configure').map(r => r.connectionId)- )- assert.ok(configured.has('gw-a'), 'gateway A received the room mirror')- assert.ok(configured.has('gw-b'), 'gateway B received the room mirror')-})--test('source contract: workspace + main-window door + prompt rules are wired', () => {- assert.match(pluginSource, /function GroupChatWorkspace\(/)- // Group rows open through the main-window door, feature-detected with the- // in-panel room as the older-desktop fallback.- assert.match(pluginSource, /function openGroupChat\(/)- assert.match(pluginSource, /typeof host\.openWorkspace === 'function'/)- assert.match(pluginSource, /\$groupChatWorkspace\.set\(group\)/)- assert.match(pluginSource, /reply with exactly "\(pass\)"/i)- assert.match(pluginSource, /\[Group chat: "\$\{groupName\}"\]/)-})--test('group selection follows main-window open and close', () => {- const gc = load(() => '(pass)')- let onClose-- gc.host.openWorkspace = (_id, options) => {- onClose = options.onClose- return () => onClose()- }-- gc.openGroupChat('Core')- assert.equal(gc.$groupChatWorkspace.get(), 'Core')- // #89788: the main tab owns the room, so the pane keeps its roster.- assert.equal(gc.shouldRenderGroupChatInPane('Core'), false)-- onClose()- assert.equal(gc.$groupChatWorkspace.get(), null)- assert.equal(gc.shouldRenderGroupChatInPane('Core'), true)-})--test('older and failed workspace hosts keep the in-pane group fallback', () => {- const older = load(() => '(pass)')-- older.openGroupChat('Core')- assert.equal(older.$groupChatWorkspace.get(), 'Core')- assert.equal(older.shouldRenderGroupChatInPane('Core'), true)-- const failed = load(() => '(pass)')-- failed.host.openWorkspace = () => {- throw new Error('workspace unavailable')- }-- failed.openGroupChat('Ops')- assert.equal(failed.$groupChatWorkspace.get(), 'Ops')- assert.equal(failed.shouldRenderGroupChatInPane('Ops'), true)-})--test('main-tab ownership is recorded before the selection atom paints (#89788 follow-up)', () => {- const gc = load(() => '(pass)')- // Simulate a BotsPane render racing the open: sample the gate at the- // moment the selection atom flips. If the tab were recorded after the- // atom set, this probe would observe selected-but-unowned and the- // in-pane duplicate would paint beside the main tab.- let gateAtSelection = null- const realSet = gc.$groupChatWorkspace.set-- gc.$groupChatWorkspace.set = value => {- if (value === 'Core' && gateAtSelection === null) {- gateAtSelection = gc.shouldRenderGroupChatInPane('Core')- }-- realSet(value)- }- gc.host.openWorkspace = () => () => undefined-- gc.openGroupChat('Core')- assert.equal(gateAtSelection, false)-})--test('tab open/close bumps the reactive rev so the pane gate re-evaluates', () => {- const gc = load(() => '(pass)')- let onClose-- gc.host.openWorkspace = (_id, options) => {- onClose = options.onClose- return () => onClose()- }-- const before = gc.$groupMainTabsRev.get()-- gc.openGroupChat('Core')- assert.ok(gc.$groupMainTabsRev.get() > before, 'recording the main tab must bump the rev')-- const afterOpen = gc.$groupMainTabsRev.get()-- onClose()- assert.ok(gc.$groupMainTabsRev.get() > afterOpen, 'closing the main tab must bump the rev')-})--test('closing an older selected group does not clear the newer selection', () => {- const gc = load(() => '(pass)')-- gc.host.openWorkspace = () => () => undefined- gc.openGroupChat('Core')- gc.openGroupChat('Ops')- gc.closeGroupChatMainTab('Core')-- assert.equal(gc.$groupChatWorkspace.get(), 'Ops')-})--test('source contract: active group styling suppresses bot styling', () => {- assert.match(pluginSource, /function botRowOwnsWorkspace\([\s\S]*?if \(activeGroup\) \{\s*return false/)- assert.match(pluginSource, /active && 'bg-\(--ui-row-active-background\)'/)- assert.match(pluginSource, /active: groupChatName === row\.name/)-})--test('source contract: group roster rows expose a confirmed Delete Group action', () => {- assert.match(pluginSource, /function GroupRow\(\{ active, group, members, needsYou, onOpen, onDisband \}\)/)- assert.match(pluginSource, /children: 'Delete Group'/)- assert.match(pluginSource, /title: 'Delete group chat\?'/)- assert.match(pluginSource, /await disbandGroupChat\(deletingGroup\.name, deletingGroup\.members\)/)-})--test('disband: removes only this membership, room log, workspace, and needs-you state', async () => {- const gc = load(() => '(pass)')-- // Two rooms; disband one.- gc.sendToGroupChat('Keep', [{ name: 'research', title: '' }], 'hello keepers')- for (let i = 0; i < 200 && (gc.$groupChats.get().Keep || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }- gc.sendToGroupChat('Gone', [{ name: 'builder', title: '' }], 'hello goners')- for (let i = 0; i < 200 && (gc.$groupChats.get().Gone || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- const rooms = { ...gc.$groupChats.get() }- rooms.Keep = {- ...rooms.Keep,- members: [{ name: 'remote', remoteSource: true, sourceScoped: true, connectionId: 'remote-1' }]- }- gc.$groupChats.set(rooms)-- gc.$botMeta.set({- builder: { groups: ['Gone', 'Keep'], group: 'Gone' },- research: { groups: ['Keep'], group: 'Keep' }- })- gc.$groupChatWorkspace.set('Gone')- gc.$groupNeedsYou.set({ Gone: true, Keep: true })-- await gc.disbandGroupChat('Gone', [{ name: 'builder' }])-- // Room state: gone from the atom (no running drive, so no tombstone).- assert.equal(gc.$groupChats.get().Gone, undefined)- assert.ok(gc.$groupChats.get().Keep, 'other rooms untouched')- // The open room view closed; needs-you cleared for the disbanded room only.- assert.equal(gc.$groupChatWorkspace.get(), null)- assert.equal(gc.$groupNeedsYou.get().Gone, undefined)- assert.equal(gc.$groupNeedsYou.get().Keep, true)- // Disband removes only this membership; other groups survive.- assert.equal(JSON.stringify(gc.$botMeta.get().builder.groups), JSON.stringify(['Keep']))- assert.equal(gc.$botMeta.get().builder.group, 'Keep')- assert.equal(JSON.stringify(gc.$botMeta.get().research.groups), JSON.stringify(['Keep']))- assert.equal(gc.$botMeta.get().research.group, 'Keep')- // Persisted room map no longer carries the room.- const durable = gc.storageWrites.get('group-chats')- assert.ok(durable && !('Gone' in durable), 'disbanded room not persisted')- assert.ok('Keep' in durable, 'surviving room still persisted')- assert.equal(durable.Keep.members.length, 1, 'surviving room keeps remote member descriptors')- assert.equal(durable.Keep.members[0].connectionId, 'remote-1')-})--test('disband: an empty rendered roster cannot leave a metadata-only group row', async () => {- const gc = load(() => '(pass)')-- gc.$botMeta.set({ builder: { groups: ['Remote'], group: 'Remote' } })- gc.$groupChats.set({- Remote: { log: [], members: [], watermarks: {}, sessions: {}, running: false }- })-- await gc.disbandGroupChat('Remote', [])-- assert.equal(gc.$groupChats.get().Remote, undefined, 'room record is deleted')- assert.equal(JSON.stringify(gc.$botMeta.get().builder.groups), JSON.stringify([]))- assert.equal(gc.$botMeta.get().builder.group, null)- assert.equal(- JSON.stringify(gc.groupChatNames(gc.$botMeta.get(), gc.$groupChats.get())),- JSON.stringify([]),- 'stale bot metadata cannot reconstruct a deleted zero-member row'- )-})--test('disband: an empty rendered roster recovers the exact source-qualified metadata owner', async () => {- const gc = load(() => '(pass)')- const remote = {- name: 'builder',- connectionId: 'remote-1',- connectionKind: 'remote',- sourceScoped: true,- remoteSource: true,- route: {- connectionId: 'remote-1',- mode: 'remote',- profile: 'builder',- targetProfile: 'builder'- }- }-- gc.$lastRoster.set([remote])- gc.$botMeta.set({- builder: { groups: ['Keep'], group: 'Keep' },- 'remote-1::builder': { groups: ['Remote'], group: 'Remote' }- })- gc.$groupChats.set({- Remote: { log: [], members: [], watermarks: {}, sessions: {}, running: false }- })-- await gc.disbandGroupChat('Remote', [])-- assert.equal(JSON.stringify(gc.$botMeta.get()['remote-1::builder'].groups), JSON.stringify([]))- assert.equal(gc.$botMeta.get()['remote-1::builder'].group, null)- assert.equal(JSON.stringify(gc.$botMeta.get().builder.groups), JSON.stringify(['Keep']))- assert.equal(gc.$botMeta.get().builder.group, 'Keep', 'same-named local metadata is untouched')-})--test('disband: skips source-qualified remote members instead of mutating same-named local metadata', async () => {- const gc = load(() => '(pass)')- gc.$botMeta.set({ builder: { groups: ['Keep'], group: 'Keep' } })-- await gc.disbandGroupChat('Remote', [- { name: 'builder', remoteSource: true, sourceScoped: true, connectionId: 'remote-1' }- ])-- assert.equal(JSON.stringify(gc.$botMeta.get().builder.groups), JSON.stringify(['Keep']))- assert.equal(gc.$botMeta.get().builder.group, 'Keep')- assert.equal(gc.$botMeta.get()['[object Object]'], undefined)-})--test('disband: a running room leaves an epoch-bumped empty tombstone so in-flight turns bail', async () => {- const gc = load(() => '(pass)')-- gc.sendToGroupChat('Live', [{ name: 'research', title: '' }], 'kick off')- for (let i = 0; i < 200 && (gc.$groupChats.get().Live || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- // Simulate a drive still in flight at disband time.- const rooms = { ...gc.$groupChats.get() }- rooms.Live = { ...rooms.Live, running: true, epoch: 3 }- gc.$groupChats.set(rooms)-- await gc.disbandGroupChat('Live', [{ name: 'research' }])-- const tomb = gc.$groupChats.get().Live- assert.ok(tomb, 'tombstone present while a drive is mid-turn')- assert.equal(tomb.log.length, 0)- assert.equal(tomb.running, false)- assert.equal(tomb.epoch, 4, 'epoch bumped so the loop bails at its member boundary')- assert.equal(tomb.tombstone, true, 'flagged so persistence and name-dedup skip it')- const durable = gc.storageWrites.get('group-chats')- assert.ok(!durable || !('Live' in (durable || {})), 'tombstone is never persisted')-- // Regression (#90028 live E2E): updateGroupChat persists the WHOLE atom- // map — an unrelated room write while the tombstone lingers must not- // smuggle the tombstone into durable storage, and the disbanded name must- // be immediately reusable (uniqueGroupChatName would suffix it otherwise).- gc.updateGroupChat('Other', room => {- room.log.push({ at: Date.now(), from: { kind: 'user' }, text: 'x', thread: 't' })- return room- })- const durable2 = gc.storageWrites.get('group-chats')- assert.ok(durable2 && 'Other' in durable2, 'real room persists')- assert.ok(!('Live' in durable2), 'tombstone excluded from later whole-map writes')- assert.equal(gc.uniqueGroupChatName('Live', new Set(gc.liveGroupChatNames())), 'Live',- 'disbanded name is immediately reusable — tombstone does not hold it')-})--test('source contract: workspace deletion stays behind a ConfirmDialog', () => {- assert.match(pluginSource, /function disbandGroupChat\(/)- assert.match(pluginSource, /title: 'Delete group chat\?'/)- assert.match(pluginSource, /await disbandGroupChat\(deletingGroup\.name, deletingGroup\.members\)/)-})--test('default profile speaks as Hermes in room transcripts, not @default', () => {- const gc = load(() => '(pass)')- const line = gc.formatGroupChatLine({ from: { kind: 'member', name: 'default' }, text: 'hello room' }, 'builder')- assert.equal(line, 'Hermes: hello room')- assert.doesNotMatch(line, /default/)-- // Other members keep their profile name; the (you) suffix survives.- const you = gc.formatGroupChatLine({ from: { kind: 'member', name: 'default' }, text: 'hi' }, 'default')- assert.equal(you, 'Hermes (you): hi')- const plain = gc.formatGroupChatLine({ from: { kind: 'member', name: 'builder' }, text: 'yo' }, 'research')- assert.equal(plain, 'builder: yo')-})--test('speaker labels honor friendly identity: Bot Mode title, then display_name, never a stale Hermes', () => {- const gc = load(() => '(pass)')-- // A renamed default (core display_name via `hermes profile rename`) must- // read as its new name — the community report was "Lucy" still showing- // "Hermes is thinking…" in group rooms.- gc.$lastRoster.set([{ name: 'default', display_name: 'Lucy' }])- assert.equal(gc.groupSpeakerLabel('default'), 'Lucy')- assert.equal(- gc.formatGroupChatLine({ from: { kind: 'member', name: 'default' }, text: 'hi' }, 'builder'),- 'Lucy: hi'- )-- // A Bot Mode title outranks display_name (same precedence as displayName).- gc.$botMeta.set({ default: { title: 'Moxie' } })- assert.equal(gc.groupSpeakerLabel('default'), 'Moxie')-- // Secondary profiles get their title too — the thinking line names the- // renamed bot, not the raw profile slug.- gc.$botMeta.set({ research: { title: 'Radar' } })- gc.$lastRoster.set([])- assert.equal(gc.groupSpeakerLabel('research'), 'Radar')-- // Untitled rows keep today's behavior: default → Hermes, others verbatim.- gc.$botMeta.set({})- assert.equal(gc.groupSpeakerLabel('default'), 'Hermes')- assert.equal(gc.groupSpeakerLabel('builder'), 'builder')-})--test('speaker labels never borrow a remote row\u2019s display_name for a local speaker', () => {- const gc = load(() => '(pass)')- // Only a remote/thin row named default exists — its display_name belongs- // to that connection, not to the active gateway's default.- gc.$lastRoster.set([{ name: 'default', display_name: 'HomelabBot', remoteSource: true }])- assert.equal(gc.groupSpeakerLabel('default'), 'Hermes')-})--test('turn prompt addresses the default profile as @hermes', () => {- const gc = load(() => '(pass)')- const prompt = gc.buildGroupChatTurnPrompt({- groupName: 'Core',- members: [{ name: 'default', title: '' }, { name: 'builder', title: '' }],- viewer: { name: 'default', title: '' },- deltaLines: []- })- assert.match(prompt, /You are @hermes,/)- assert.doesNotMatch(prompt, /@default\b/)-- const peerView = gc.buildGroupChatTurnPrompt({- groupName: 'Core',- members: [{ name: 'default', title: '' }, { name: 'builder', title: '' }],- viewer: { name: 'builder', title: '' },- deltaLines: []- })- assert.match(peerView, /group chat with @hermes/)-})--test('mention routing: @hermes resolves to the default member', () => {- const gc = load(() => '(pass)')- const members = [{ name: 'default', title: '' }, { name: 'builder', title: '' }]- const parsed = gc.parseGroupChatMentions('@hermes take a look', members)- assert.equal(parsed.mentioned.has('default'), true)- assert.equal(parsed.mentioned.size, 1)-})--test('source contract: workspace speaker labels use displayName with a click-to-reveal handle', () => {- // Speaker labels come from the roster displayName (default → Hermes)…- assert.match(pluginSource, /displayName\(member \|\| \{ name: entry\.from\.name \}, meta\)/)- // …and clicking a speaker reveals the full disambiguated handle, with the- // gateway/device name appended for cross-connection speakers.- assert.match(pluginSource, /setRevealedSpeaker\(revealed \? null : entryKey\)/)- assert.match(pluginSource, /\$\{display\}\$\{entry\.from\.source \? `-\$\{entry\.from\.source\}` : ''\} \(@\$\{botHandle\(entry\.from\.name, member \|\| undefined\)\}\)/)-})--test('source contract: room messages carry the speaker avatar via the roster appearance pipeline', () => {- const start = pluginSource.indexOf('function GroupChatWorkspace(')- const end = pluginSource.indexOf('function BotsPane(')- const workspace = pluginSource.slice(start, end === -1 ? undefined : end)-- // Per-message avatar: appearance resolved the same way as BotRow (custom- // image/pet honored, backfilled PNG dropped so the math face animates).- assert.match(workspace, /botAppearance\(entry\.from\.name, meta\)/)- assert.match(workspace, /image && !isBackfilledFacePng\(image\)/)- assert.match(workspace, /jsx\(BotFace, \{\s*shape,\s*color,\s*image: photo \? image : null,\s*size: 24,\s*name: entry\.from\.name/)-- // Header stays quiet: member avatars belong to messages, while the header- // exposes a concise count instead of an overlapping face stack.- assert.doesNotMatch(workspace, /members\.slice\(0, 6\)\.map\(/)- assert.match(workspace, /children: members\.length > 0 && availableMembers < members\.length \? availabilityLabel : `\$\{members\.length\} bots`/)-})--test('stranded harvest: a timed-out turn whose reply landed late posts into the room and clears the marker', async () => {- const gc = load(() => '(pass)')-- // Room with a stranded marker for research: baseline 0 messages.- gc.updateGroupChat('Late', r => {- r.stranded = { research: 0 }- r.sessions = { research: 'sid-research' }- return r- })- // The member's session finished after we stopped waiting.- gc.sessions.set('sid-research', {- stored: 'sid-research',- runtime: 'rt-research',- profile: 'research',- title: 'Group: Late',- messages: [- { role: 'user', content: 'the turn prompt' },- { role: 'assistant', content: 'Here is the full research result, delivered late.' }- ]- })-- await gc.harvestStrandedGroupReply('Late', { name: 'research', title: '' })-- const log = roomLog(gc, 'Late')- assert.equal(log.length, 1)- assert.equal(log[0].from.name, 'research')- assert.match(log[0].text, /delivered late/)- assert.equal(gc.$groupChats.get().Late.stranded.research, undefined, 'marker consumed')-})--test('stranded harvest: a rescued reply prefers the substantive answer over a trailing synthetic (pass)', async () => {- const gc = load(() => '(pass)')-- // #94376 class bug at the second call site: the late-landing turn ends- // with a Codex intent-ack continuation nudge that gets a synthetic- // "(pass)" — the harvest must still surface the substantive answer that- // preceded it, not the trailing pass.- gc.updateGroupChat('Rescue', r => {- r.stranded = { research: 0 }- r.sessions = { research: 'sid-research' }- return r- })- gc.sessions.set('sid-research', {- stored: 'sid-research',- runtime: 'rt-research',- profile: 'research',- title: 'Group: Rescue',- messages: [- { role: 'user', content: 'the turn prompt' },- { role: 'assistant', content: 'Here is the full research result, delivered late.' },- { role: 'user', content: '[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.]' },- { role: 'assistant', content: '(pass)' }- ]- })-- await gc.harvestStrandedGroupReply('Rescue', { name: 'research', title: '' })-- const log = roomLog(gc, 'Rescue')- assert.equal(log.length, 1)- assert.equal(log[0].from.name, 'research')- assert.match(log[0].text, /delivered late/)- assert.equal(gc.$groupChats.get().Rescue.stranded.research, undefined, 'marker consumed')-})--test('stranded + still busy: the round loop never re-submits into a member whose harvest just confirmed they are still running', async () => {- // research is confirmed busy on exactly its first two session.resume- // calls — the number of harvest-only touches the FIXED code makes across- // two rounds. If the responder guard is missing, research gets re-- // selected and picks up two EXTRA resume calls of its own (session- // resolution + turn baseline) before its very first post-resubmit poll- // — call #4 — which then reports done, so the mutated run still finishes- // fast (no real wall-clock wait) while still proving the resubmission- // happened.- const gc = load(profile => (profile === 'builder' ? 'builder here, all good' : '(pass)'), {- busyUntilResumeCall: { research: 2 }- })-- // research's session is pre-seeded and resolvable, exactly like the- // sibling stranded-harvest test above — its stranded marker is the- // pre-thread bare-number shape (still supported: harvestStrandedGroupReply- // normalizes both shapes, and presence in `stranded` is what the round-loop- // guard checks, not the marker's value shape).- gc.sessions.set('sid-research', {- stored: 'sid-research',- runtime: 'rt-research',- profile: 'research',- title: 'Group: Grind',- messages: []- })-- // research is already stranded from an earlier (unmodeled) timeout, and- // its session is STILL genuinely running per session.resume. Both members- // are mentioned, so without the busy-responder guard both would be- // re-selected this round — and resubmitting into research's live session- // would trigger the gateway's default busy policy (redirect/hard-- // interrupt), destroying the very turn the stranded marker exists to wait- // out.- gc.updateGroupChat('Grind', r => {- r.stranded = { research: 0 }- r.sessions = { research: 'sid-research' }- r.log = [{ from: { kind: 'user', name: 'You' }, text: '@research @builder status?', at: 1 }]- r.watermarks = { 'legacy::research': 0, 'legacy::builder': 0 }- return r- })-- await gc.runGroupChatRounds('Grind', [{ name: 'research', title: '' }, { name: 'builder', title: '' }], 'legacy')-- assert.equal(- gc.calls.filter(c => c.profile === 'research').length,- 0,- 'research (still busy) must never receive a new prompt.submit'- )- assert.equal(- gc.$groupChats.get().Grind.stranded.research,- 0,- 'marker survives untouched — harvest confirmed research is still running'- )- assert.equal(gc.calls.filter(c => c.profile === 'builder').length, 1, 'builder (not stranded) still gets its turn')-})--test('stranded harvest: a late (pass) or no-new-message consumes the marker without posting', async () => {- const gc = load(() => '(pass)')-- gc.updateGroupChat('Quiet2', r => {- r.stranded = { builder: 2 }- r.sessions = { builder: 'sid-builder' }- return r- })- gc.sessions.set('sid-builder', {- stored: 'sid-builder',- runtime: 'rt-builder',- profile: 'builder',- title: 'Group: Quiet2',- messages: [- { role: 'user', content: 'p1' },- { role: 'user', content: 'prompt' },- { role: 'assistant', content: '(pass)' }- ]- })-- await gc.harvestStrandedGroupReply('Quiet2', { name: 'builder', title: '' })-- assert.equal(roomLog(gc, 'Quiet2').length, 0)- assert.equal(gc.$groupChats.get().Quiet2.stranded.builder, undefined)-})--test('stranded markers persist so late replies survive a window reload', async () => {- const gc = load(() => '(pass)')-- gc.updateGroupChat('Persist', r => {- r.stranded = { research: 3 }- return r- })-- const durable = gc.storageWrites.get('group-chats')- assert.ok(durable && durable.Persist, 'room persisted')- assert.equal(durable.Persist.stranded.research, 3, 'stranded marker rides the durable map')-})--test('source contract: long visible turns extend the deadline up to a hard cap', () => {- assert.match(pluginSource, /const GROUP_TURN_HARD_CAP_MS = /)- assert.match(pluginSource, /deadline = Math\.min\(started \+ GROUP_TURN_HARD_CAP_MS/)-})--test('source contract: the working line names the member on turn', () => {- assert.match(pluginSource, /is thinking…/)- assert.match(pluginSource, /r\.turn = member\.name/)- assert.match(pluginSource, /r\.turn = null/)-})--test('source contract: creating a group with a taken name mints a fresh room, never reopens the old log', () => {- assert.match(pluginSource, /const taken = new Set\(liveGroupChatNames\(\)\)/)- assert.match(pluginSource, /const groupName = uniqueGroupChatName\(base, taken\)/)- assert.match(pluginSource, /const roomId = mintGroupRoomId\(\)/)- assert.match(pluginSource, /room\.roomId = roomId/)-})--test('turn prompt: results are full quality — only chatter is asked to stay short', () => {- const gc = load(() => '(pass)')- const prompt = gc.buildGroupChatTurnPrompt({- groupName: 'Core',- members: [{ name: 'research', title: '' }, { name: 'builder', title: '' }],- viewer: { name: 'research', title: '' },- deltaLines: []- })- assert.match(prompt, /never thin out real content/i)- assert.match(prompt, /Keep chatter short/i)-})--test('threads: room composer mints a new thread; replies land in it', async () => {- const gc = load(() => '(pass)')-- const t1 = gc.sendToGroupChat('Rooms', [{ name: 'research', title: '' }], 'first topic')- for (let i = 0; i < 200 && (gc.$groupChats.get().Rooms || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }- const t2 = gc.sendToGroupChat('Rooms', [{ name: 'research', title: '' }], 'second topic')- for (let i = 0; i < 200 && (gc.$groupChats.get().Rooms || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- assert.ok(t1 && t2 && t1 !== t2, 'each composer send mints a distinct thread')- const log = roomLog(gc, 'Rooms')- assert.equal(log[0].thread, t1)- assert.equal(log[1].thread, t2)-})--test('threads: replying with an explicit thread id continues that thread and scopes the member delta to it', async () => {- const prompts = []- const gc = load((profile, prompt) => {- prompts.push(prompt)- return prompt.includes('billing') ? 'On the billing fix.' : '(pass)'- })-- const billing = gc.sendToGroupChat('Scoped', [{ name: 'research', title: '' }], 'fix the billing bug')- for (let i = 0; i < 200 && (gc.$groupChats.get().Scoped || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }- gc.sendToGroupChat('Scoped', [{ name: 'research', title: '' }], 'research pricing')- for (let i = 0; i < 200 && (gc.$groupChats.get().Scoped || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- // Continue the BILLING thread explicitly.- const again = gc.sendToGroupChat('Scoped', [{ name: 'research', title: '' }], 'billing follow-up: ship it', billing)- for (let i = 0; i < 200 && (gc.$groupChats.get().Scoped || {}).running; i++) {- await new Promise(resolve => setImmediate(resolve))- }-- assert.equal(again, billing, 'explicit thread id is reused, not re-minted')- const followUpPrompt = prompts.find(p => p.includes('ship it'))- assert.ok(followUpPrompt, 'follow-up turn ran')- assert.equal(followUpPrompt.includes('research pricing'), false, 'other thread never leaks into the delta')-- // Member replies carry the thread of the turn that produced them.- const memberEntries = roomLog(gc, 'Scoped').filter(e => e.from.kind === 'member')- assert.ok(memberEntries.length >= 1)- assert.ok(memberEntries.every(e => e.thread === billing), 'replies land in the thread that triggered them')-})--test('threads: hydration assigns legacy thread ids — lull splits, follow-ups stay together', () => {- const gc = load(() => '(pass)')- assert.match(pluginSource, /function assignLegacyThreads\(log\)/)-- const fn = new Function(- `${pluginSource.slice(pluginSource.indexOf('const GROUP_THREAD_GAP_MS'), pluginSource.indexOf('/** Merged room view'))}; return assignLegacyThreads`- )()- const M = 60000- const u = (text, at) => ({ from: { kind: 'user', name: 'You' }, text, at })- const m = (name, text, at) => ({ from: { kind: 'member', name }, text, at })-- const log = fn([- u('task one', 0),- m('a', 'r1', 1 * M),- u('quick follow-up', 3 * M), // inside the 15-min window: SAME thread- m('a', 'r2', 4 * M),- u('new topic much later', 60 * M), // after the lull: new thread- m('a', 'r3', 61 * M)- ])- assert.equal(log[0].thread, log[2].thread, 'follow-up stays in the same thread')- assert.equal(log[2].thread, log[3].thread)- assert.notEqual(log[0].thread, log[4].thread, 'post-lull message starts a new thread')- assert.equal(log[4].thread, log[5].thread)- void gc-})--test('source contract: thread UI — folded rows, per-thread reply box, new-thread composer', () => {- assert.match(pluginSource, /Open this thread/)- assert.match(pluginSource, /Collapse thread/)- assert.match(pluginSource, /Reply in thread…/)- assert.match(pluginSource, /children: 'New Thread'/)- assert.match(pluginSource, /const markKey = `\$\{thread\}::\$\{memberKey\}`/)-})--function groupChatWorkspaceSource() {- const start = pluginSource.indexOf('function GroupChatWorkspace')- const end = pluginSource.indexOf('function closeGroupChatMainTab')- assert.ok(start >= 0, 'GroupChatWorkspace is defined')- assert.ok(end > start, 'closeGroupChatMainTab follows GroupChatWorkspace')- return pluginSource.slice(start, end)-}--test('source contract: group chat log lines expose CopyButton on the entry body', () => {- const src = groupChatWorkspaceSource()- assert.match(pluginSource, /CopyButton/)- assert.match(src, /CopyButton/)- assert.match(src, /text:\s*entry\.text/)- assert.match(src, /stopPropagation:\s*true/)- assert.match(src, /appearance:\s*['"]icon['"]/)- assert.match(src, /buttonSize:\s*['"]icon['"]/)- assert.match(src, /['"]group /)- assert.doesNotMatch(src, /playSpeechText/)- assert.doesNotMatch(src, /RefreshCw/)- assert.doesNotMatch(src, /readAloud/)- assert.doesNotMatch(src, /ActionBarPrimitive\.Reload/)-})--test('source contract: group chat message bodies opt back into selectable text', () => {- // styles.css sets user-select: none app-wide and re-enables it only for- // [data-selectable-text="true"] surfaces. Without this opt-in on the entry- // body, drag-select and Cmd/Ctrl+C are dead in group chat logs.- const src = groupChatWorkspaceSource()- assert.match(src, /'data-selectable-text':\s*'true'/)-})--test('group room preview renders the bot HANDLE, not the raw profile name', () => {- // #89484: the room line read "@default: …" while the bot answers to- // @hermes, so users concluded mention routing was broken.- assert.match(pluginSource, /const lastHandle = botHandle\(lastFrom \|\| 'bot', members\.find\(/)- assert.match(pluginSource, /\? `\$\{last\.from\?\.kind === 'user' \? 'You' : `@\$\{lastHandle\}`\}/)- assert.doesNotMatch(pluginSource, /`@\$\{last\.from\?\.name \|\| 'bot'\}`/)-})--// ── group clarify (#90694): member questions surface in the room ──────────--const CLARIFY_PAYLOAD = {- request_id: 'req-clarify-1',- question: 'Which env should I target?',- choices: ['staging', 'prod'],- multi_select: false-}--test('a member blocked on clarify surfaces its question and holds the turn open', async () => {- // research reports pending_clarify on its first two resumes after the- // submit; the turn must NOT read it as done/pass while the question waits.- const gc = load(() => 'targeting staging', {- clarifyUntilResumeCall: { research: { payload: CLARIFY_PAYLOAD, until: 3 } }- })-- const thread = gc.sendToGroupChat('Core', [MEMBERS[0]], '@research deploy it', null, [])- await new Promise(resolve => setTimeout(resolve, 0))- await new Promise(resolve => setTimeout(resolve, 0))-- // Mirrored while blocked, cleared once the resume stops reporting it.- const log = gc.$groupChats.get().Core.log.filter(e => e.thread === thread)- const replies = log.filter(e => e.from.kind === 'member')-- assert.equal(replies.length, 1, 'the finished reply still lands after the clarify clears')- assert.equal(replies[0].text, 'targeting staging')- assert.equal(Object.keys(gc.$groupClarify.get()).length, 0, 'the mirrored question is cleared once resolved')- // The mirror pass ran while the question was blocking: it badges the room- // needs-you. The sabotaged (pre-fix) poll never inspects pending_clarify,- // so this stays unset — the observable proof the gate executed.- assert.equal(gc.$groupNeedsYou.get().Core, true, 'the blocking question badged the room')-})--test('syncGroupClarify mirrors, badges needs-you, and is idempotent per request', () => {- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }-- const blocked = gc.syncGroupClarify('Core', member, { pending_clarify: CLARIFY_PAYLOAD })- assert.equal(blocked, true)-- const mirrored = Object.values(gc.$groupClarify.get())- assert.equal(mirrored.length, 1)- assert.equal(mirrored[0].requestId, 'req-clarify-1')- assert.equal(mirrored[0].question, 'Which env should I target?')- assert.equal(JSON.stringify(mirrored[0].choices), JSON.stringify(['staging', 'prod']))- assert.equal(gc.$groupNeedsYou.get().Core, true)-- // Same request again: no new entry, identity preserved.- const first = mirrored[0]- gc.syncGroupClarify('Core', member, { pending_clarify: CLARIFY_PAYLOAD })- assert.equal(Object.values(gc.$groupClarify.get())[0], first)-- // Question resolved server-side: the mirror clears.- const still = gc.syncGroupClarify('Core', member, {})- assert.equal(still, false)- assert.equal(Object.keys(gc.$groupClarify.get()).length, 0)-})--test('older backends without pending_clarify never mirror a question', () => {- const gc = load(() => '(pass)')-- assert.equal(gc.syncGroupClarify('Core', { name: 'research' }, { messages: [] }), false)- assert.equal(Object.keys(gc.$groupClarify.get()).length, 0)-})--test('answerGroupClarify routes clarify.respond and clears the mirror', async () => {- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }-- gc.syncGroupClarify('Core', member, { pending_clarify: CLARIFY_PAYLOAD })- const entry = Object.values(gc.$groupClarify.get())[0]-- await gc.answerGroupClarify(entry, member, 'staging')-- assert.equal(JSON.stringify(gc.clarifyResponds), JSON.stringify([{ request_id: 'req-clarify-1', answer: 'staging' }]))- assert.equal(Object.keys(gc.$groupClarify.get()).length, 0)-})--test('answerGroupClarify sends one respond per batch question, in order', async () => {- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }- const batch = {- request_id: 'req-batch-1',- questions: [- { qid: 'q0', question: 'Env?', choices: ['staging', 'prod'] },- { qid: 'q1', question: 'Region?', choices: [] }- ]- }-- gc.syncGroupClarify('Core', member, { pending_clarify: batch })- const entry = Object.values(gc.$groupClarify.get())[0]-- await gc.answerGroupClarify(entry, member, { q0: 'staging', q1: 'eu-west' })-- assert.equal(- JSON.stringify(gc.clarifyResponds),- JSON.stringify([- { request_id: 'req-batch-1', question_id: 'q0', answer: 'staging' },- { request_id: 'req-batch-1', question_id: 'q1', answer: 'eu-west' }- ])- )- assert.equal(Object.keys(gc.$groupClarify.get()).length, 0)-})--test('disband clears the room mirrored questions', async () => {- const gc = load(() => '(pass)')-- gc.syncGroupClarify('Core', { name: 'research' }, { pending_clarify: CLARIFY_PAYLOAD })- gc.syncGroupClarify('Other', { name: 'ops' }, { pending_clarify: { ...CLARIFY_PAYLOAD, request_id: 'req-2' } })-- await gc.disbandGroupChat('Core', [])-- const remaining = Object.values(gc.$groupClarify.get())- assert.equal(remaining.length, 1)- assert.equal(remaining[0].group, 'Other')-})--test('source contract: room renders clarify cards and the poll gates on them', () => {- assert.match(pluginSource, /function GroupClarifyCard\(/)- assert.match(pluginSource, /syncGroupClarify\(group, member, state\)/)- assert.match(pluginSource, /const done = !busy && !awaitingUser/)- assert.match(pluginSource, /busy \|\| awaitingUser/)- assert.match(pluginSource, /roomClarifies\.map\(entry =>/)- assert.match(pluginSource, /'clarify\.respond'/)-})--// ── group approvals: same hidden-session class as clarify (#90694) ─────────--const APPROVAL_PAYLOAD = {- request_id: 'req-approval-1',- command: 'rm -rf ./build',- description: 'Clean the build directory',- choices: ['once', 'session', 'deny']-}--test('a member blocked on a command approval surfaces an approval card and holds the turn', async () => {- const gc = load(() => 'build cleaned', {- approvalUntilResumeCall: { research: { payload: APPROVAL_PAYLOAD, until: 3 } }- })-- const thread = gc.sendToGroupChat('Core', [MEMBERS[0]], '@research clean up', null, [])- await new Promise(resolve => setTimeout(resolve, 0))- await new Promise(resolve => setTimeout(resolve, 0))-- const log = gc.$groupChats.get().Core.log.filter(e => e.thread === thread)- const replies = log.filter(e => e.from.kind === 'member')-- assert.equal(replies.length, 1, 'the finished reply still lands after the approval clears')- assert.equal(replies[0].text, 'build cleaned')- assert.equal(Object.keys(gc.$groupClarify.get()).length, 0)- assert.equal(gc.$groupNeedsYou.get().Core, true, 'the blocking approval badged the room')-})--test('syncGroupClarify mirrors an approval with kind, command, and server choices', () => {- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }-- const blocked = gc.syncGroupClarify('Core', member, {- session_id: 'rt-research-1',- pending_approval: APPROVAL_PAYLOAD- })- assert.equal(blocked, true)-- const entry = Object.values(gc.$groupClarify.get())[0]- assert.equal(entry.kind, 'approval')- assert.equal(entry.command, 'rm -rf ./build')- assert.equal(entry.question, 'Clean the build directory')- assert.equal(JSON.stringify(entry.choices), JSON.stringify(['once', 'session', 'deny']))- assert.equal(entry.sessionId, 'rt-research-1')-})--test('an approval without a server choice set falls back to once/deny', () => {- const gc = load(() => '(pass)')-- gc.syncGroupClarify('Core', { name: 'research' }, {- pending_approval: { request_id: 'req-a2', command: 'ls' }- })-- const entry = Object.values(gc.$groupClarify.get())[0]- assert.equal(JSON.stringify(entry.choices), JSON.stringify(['once', 'deny']))-})--test('answerGroupClarify routes approvals through approval.respond with session + choice', async () => {- const gc = load(() => '(pass)')- const member = { name: 'research', title: '' }-- gc.syncGroupClarify('Core', member, { session_id: 'rt-research-1', pending_approval: APPROVAL_PAYLOAD })- const entry = Object.values(gc.$groupClarify.get())[0]-- await gc.answerGroupClarify(entry, member, 'once')-- assert.equal(- JSON.stringify(gc.approvalResponds),- JSON.stringify([{ session_id: 'rt-research-1', request_id: 'req-approval-1', choice: 'once' }])- )- assert.equal(gc.clarifyResponds.length, 0, 'approvals never touch the clarify wire')- assert.equal(Object.keys(gc.$groupClarify.get()).length, 0)-})--test('clarify outranks approval when a snapshot carries both', () => {- const gc = load(() => '(pass)')-- gc.syncGroupClarify('Core', { name: 'research' }, {- pending_clarify: CLARIFY_PAYLOAD,- pending_approval: APPROVAL_PAYLOAD- })-- const entry = Object.values(gc.$groupClarify.get())[0]- assert.equal(entry.kind, 'clarify')- assert.equal(entry.requestId, 'req-clarify-1')-})--test('source contract: approval card renders the command and routes approval.respond', () => {- assert.match(pluginSource, /pending_approval/)- assert.match(pluginSource, /'approval\.respond'/)- assert.match(pluginSource, /kind: 'approval'/)- assert.match(pluginSource, /wants to run a command/)-})--test('durableGroupChatRooms excludes tombstoned rooms — the remote-merge persist path\'s own durable-map builder, independent of updateGroupChat\'s inline one', () => {- const gc = load(() => '(pass)')-- const durable = gc.durableGroupChatRooms({- Live: { tombstone: true, log: [], watermarks: {}, epoch: 4, running: false },- Keep: { log: [{ from: { kind: 'user' }, text: 'hi', at: 1 }], watermarks: {}, members: [] }- })-- assert.ok(!('Live' in durable), 'tombstone excluded from the remote-merge persist path too')- assert.ok('Keep' in durable, 'real room still persisted')-})--test('durableGroupChatRooms carries roomId — omitting it drops the durable id on the next cold hydrate', () => {- const gc = load(() => '(pass)')-- const durable = gc.durableGroupChatRooms({- Team: {- log: [{ from: { kind: 'user' }, text: 'hi', at: 1 }],- watermarks: {},- members: [],- roomId: 'room-abc123'- },- Legacy: {- log: [{ from: { kind: 'user' }, text: 'hi', at: 1 }],- watermarks: {},- members: []- }- })-- assert.equal(durable.Team.roomId, 'room-abc123', 'immutable room identity must survive the remote-merge persist path')- assert.equal(durable.Legacy.roomId, null, 'a room with no roomId persists an explicit null, not undefined')-})--test('remote-merge reachability: a disband tombstone that survives a merge (gateway has not received the delete yet) is never written to storage', async () => {- const gc = load(() => '(pass)')-- // Simulate a drive still mid-turn at disband time, exactly like the- // sibling disband test above — this room is a live tombstone in $groupChats.- gc.$groupChats.set({- Live: { tombstone: true, log: [], watermarks: {}, epoch: 4, running: false }- })-- // The remote gateway has NOT yet received the delete (plausible now that- // sync fans out to every reachable default-profile gateway independently)- // — its snapshot still carries a live copy of the room under the same- // display name.- const merged = gc.mergeRemoteGroupChatSnapshotIntoRooms(- {- rooms: {- Live: {- log: [{ from: { kind: 'member', name: 'research' }, text: 'still going', at: 1 }],- members: [{ name: 'research' }]- }- }- },- gc.$groupChats.get()- )-- // The merge spreads `...existing` before its explicit field overrides,- // none of which touch `tombstone` — so the flag survives into the merged- // room. This is the reachability step: without it, durableGroupChatRooms- // would never even see a tombstoned room from this path.- assert.equal(merged.Live.tombstone, true, 'tombstone forwarded by the merge (reachability precondition)')-- await gc.persistGroupChatRooms(merged)-- const durable = gc.storageWrites.get('group-chats')- assert.ok(durable && !('Live' in durable), 'merged tombstone must not resurrect as a persisted room')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-composer-drafts.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-composer-drafts.test.mjsdeleted file mode 100644index 6c4f0d57067..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-composer-drafts.test.mjs+++ /dev/null@@ -1,106 +0,0 @@-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 between(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 load() {- const context = { Map, Object }- const roomKey = between('function groupChatRoomKey(', '/** Lift any historical projection shape')- const drafts = between('const groupComposerDrafts = new Map()', 'function GroupChatWorkspace(')-- vm.runInNewContext(- `${roomKey}\n${drafts}\nglobalThis.drafts = {- clearGroupComposerDraft,- groupComposerDraftKey,- groupComposerDraftSnapshot,- migrateGroupComposerDraft,- restoreGroupComposerDraft,- updateGroupComposerDraft- }`,- context- )-- return context.drafts-}--test('workspace retirement and re-registration restore the exact room draft', () => {- const drafts = load()- const key = drafts.groupComposerDraftKey('Launch room', { roomId: 'room-1' })- const attachment = { data: 'data:image/png;base64,abc', kind: 'image', name: 'plan.png' }-- drafts.updateGroupComposerDraft(key, state => ({- ...state,- activeReplyThread: 'thread-1',- main: 'main draft',- pendingAttachments: { main: [attachment], 'thread-1': [attachment] },- replies: { 'thread-1': 'reply draft' }- }))-- // Dropping the component reference simulates pane retirement. A fresh- // registration reads the same module-scope, roomId-qualified snapshot.- const remounted = drafts.groupComposerDraftSnapshot(key)-- assert.equal(remounted.main, 'main draft')- assert.equal(remounted.replies['thread-1'], 'reply draft')- assert.equal(remounted.activeReplyThread, 'thread-1')- assert.equal(remounted.pendingAttachments.main[0].name, 'plan.png')-})--test('legacy name-keyed drafts migrate when an immutable room id appears', () => {- const drafts = load()- const legacy = drafts.groupComposerDraftKey('Launch room', {})- const current = drafts.groupComposerDraftKey('Renamed room', { roomId: 'room-1' })-- drafts.updateGroupComposerDraft(legacy, state => ({ ...state, main: 'keep me' }))- drafts.migrateGroupComposerDraft(legacy, current)-- assert.equal(drafts.groupComposerDraftSnapshot(current).main, 'keep me')- assert.equal(drafts.groupComposerDraftSnapshot(legacy).main, '')-})--test('a failed send cannot overwrite text entered after the optimistic clear', () => {- const drafts = load()- const key = 'id:room-1'-- drafts.updateGroupComposerDraft(key, state => ({ ...state, main: 'send this' }))- const before = drafts.groupComposerDraftSnapshot(key)- const cleared = drafts.updateGroupComposerDraft(key, state => ({ ...state, main: '' }))-- drafts.updateGroupComposerDraft(key, state => ({ ...state, main: 'newer typing' }))-- assert.equal(drafts.restoreGroupComposerDraft(key, cleared.revision, before), null)- assert.equal(drafts.groupComposerDraftSnapshot(key).main, 'newer typing')-})--test('disband removes only that room draft', () => {- const drafts = load()-- drafts.updateGroupComposerDraft('id:a', state => ({ ...state, main: 'a' }))- drafts.updateGroupComposerDraft('id:b', state => ({ ...state, main: 'b' }))- drafts.clearGroupComposerDraft('id:a')-- assert.equal(drafts.groupComposerDraftSnapshot('id:a').main, '')- assert.equal(drafts.groupComposerDraftSnapshot('id:b').main, 'b')-})--test('GroupChatWorkspace owns composer state through the room draft store', () => {- const workspace = between('function GroupChatWorkspace(', '/** Live closers for group-chat MAIN-window tabs')-- assert.match(workspace, /groupComposerDraftKey\(group, room\)/)- assert.match(workspace, /restoreGroupComposerDraft\(composerKeyRef\.current, cleared\.revision, before\)/)- assert.match(workspace, /clearGroupComposerDraft\(composerKeyRef\.current\)/)- assert.doesNotMatch(workspace, /useState\(''\).*?draft/)- assert.doesNotMatch(workspace, /useState\(\{\}\).*?replyDrafts/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjsdeleted file mode 100644index 490152d8fed..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-member-hold.test.mjs+++ /dev/null@@ -1,128 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #93129: a bot told to stop must STAY stopped. The hold helpers are pure and-// vm-sliced out of plugin.js exactly like group-turn-races.test.mjs does for-// the #93127 helpers. NOTE: vm-realm arrays/objects fail strict deepEqual-// against host literals (different realm prototypes) — normalize with spread-// or JSON round-trip before comparing.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadHelpers() {- const start = pluginSource.indexOf('// --- member-hold helpers (#93129)')- const end = pluginSource.indexOf('// --- end member-hold helpers ---', start)- assert.notEqual(start, -1, 'plugin carries the member-hold helper block')- assert.notEqual(end, -1, 'member-hold helper block has a stable end marker')- const context = {}- vm.runInNewContext(- `${pluginSource.slice(start, end)}-globalThis.classifyGroupHoldDirective = classifyGroupHoldDirective-globalThis.applyGroupHoldDirective = applyGroupHoldDirective-globalThis.heldMemberWatermarkAdvance = heldMemberWatermarkAdvance`,- context- )- return context-}--// ── stop detection ───────────────────────────────────────────────────────────--test('explicit stop with a mention holds the mentioned member', () => {- const { classifyGroupHoldDirective } = loadHelpers()- for (const text of ['stop @impl', '@impl stop', '@impl please halt', 'pause @impl for now']) {- const action = classifyGroupHoldDirective(text, ['impl'], false)- assert.deepEqual([...action.hold], ['impl'], `"${text}" should hold`)- assert.deepEqual([...action.release], [])- }-})--test('stop word without any mention holds nobody', () => {- const { classifyGroupHoldDirective } = loadHelpers()- const action = classifyGroupHoldDirective('stop', [], false)- assert.deepEqual([...action.hold], [])-})--test('conservative choice: "don\'t stop @x" still holds (documented trade-off)', () => {- const { classifyGroupHoldDirective } = loadHelpers()- const action = classifyGroupHoldDirective("don't stop @impl", ['impl'], false)- assert.deepEqual([...action.hold], ['impl'])-})--test('"stopped" as part of another word does not trigger a hold', () => {- const { classifyGroupHoldDirective } = loadHelpers()- // \b(stop|halt|pause)\b — "stopped" is a different token- const action = classifyGroupHoldDirective('@impl unstoppable work ahead', ['impl'], false)- assert.deepEqual([...action.hold], [])- // a plain non-stop mention releases instead (direct address overrides hold)- assert.deepEqual([...action.release], ['impl'])-})--// ── hold lifecycle ───────────────────────────────────────────────────────────--test('stop sets a hold; resume for the same member clears it', () => {- const { applyGroupHoldDirective } = loadHelpers()- const stamp = { at: 1000, byMessageId: 'm1', thread: 't1' }- const held = applyGroupHoldDirective({}, { mentioned: ['impl'], everyone: false }, 'stop @impl', stamp)- assert.ok(held.impl)- assert.equal(held.impl.at, 1000)- const released = applyGroupHoldDirective(held, { mentioned: ['impl'], everyone: false }, '@impl resume', stamp)- assert.equal(released.impl, undefined)-})--test('a direct non-stop mention of a held member releases the hold', () => {- const { applyGroupHoldDirective } = loadHelpers()- const held = { impl: { at: 1, byMessageId: null, thread: null } }- const next = applyGroupHoldDirective(held, { mentioned: ['impl'], everyone: false }, '@impl what is your status?', {})- assert.equal(next.impl, undefined)-})--test('@all resume releases every hold', () => {- const { applyGroupHoldDirective } = loadHelpers()- const held = { impl: { at: 1 }, docs: { at: 2 } }- const next = applyGroupHoldDirective(held, { mentioned: [], everyone: true }, '@all resume', {})- assert.deepEqual(JSON.parse(JSON.stringify(next)), {})-})--test('@all stop holds every member — symmetric with @all resume', () => {- const { applyGroupHoldDirective } = loadHelpers()- const next = applyGroupHoldDirective(- {},- { mentioned: [], everyone: true },- '@all stop',- { at: 5 },- ['impl', 'docs']- )- assert.ok(next.impl)- assert.ok(next.docs)- assert.equal(next.impl.at, 5)-})--test('an unrelated room message leaves holds untouched (same object back)', () => {- const { applyGroupHoldDirective } = loadHelpers()- const held = { impl: { at: 1 } }- const next = applyGroupHoldDirective(held, { mentioned: [], everyone: false }, 'receipt round complete', {})- assert.equal(next, held)-})--test('holding one member does not disturb another\'s hold', () => {- const { applyGroupHoldDirective } = loadHelpers()- const held = { impl: { at: 1 } }- const next = applyGroupHoldDirective(held, { mentioned: ['docs'], everyone: false }, 'stop @docs', { at: 2 })- assert.ok(next.impl)- assert.ok(next.docs)-})--// ── skip must not spin ───────────────────────────────────────────────────────--test('held skip consumes the delta exactly once', () => {- const { heldMemberWatermarkAdvance } = loadHelpers()- // fresh delta → advance to log length- assert.equal(heldMemberWatermarkAdvance(3, 7), 7)- // already consumed → no write, no spin- assert.equal(heldMemberWatermarkAdvance(7, 7), null)- assert.equal(heldMemberWatermarkAdvance(9, 7), null)- // unset watermark treated as 0- assert.equal(heldMemberWatermarkAdvance(undefined, 2), 2)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-mention-composer.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-mention-composer.test.mjsdeleted file mode 100644index f792b3f68d1..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-mention-composer.test.mjs+++ /dev/null@@ -1,69 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Group-composer mentions (#89049): the room's "new thread" composer and the-// reply-in-thread box mount a member-scoped @-mention popover instead of a-// dead plain Input. Source-shape assertions plus a functional check of the-// caret tokenizer, extracted and run in isolation.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--test('group room composers mount GroupMentionInput, not bare Input', () => {- // Main composer (new thread) and thread reply box both use the wrapper.- const mainComposer = source.match(/jsx\(GroupMentionInput, \{\s*'aria-label': `Message \$\{group\}`/)- const replyComposer = source.match(/jsx\(GroupMentionInput, \{\s*'aria-label': 'Reply in thread'/)- assert.ok(mainComposer, 'main group composer must render GroupMentionInput')- assert.ok(replyComposer, 'thread reply box must render GroupMentionInput')-- // Neither composer renders a dead plain Input anymore.- assert.ok(!/jsx\(Input, \{\s*'aria-label': `Message \$\{group\}`/.test(source))- assert.ok(!/jsx\(Input, \{\s*'aria-label': 'Reply in thread'/.test(source))-- // Both receive the seated members for the popover scope (onSubmitDraft- // rides along so Enter submits from the multi-line textarea, #89884).- assert.ok(/GroupMentionInput\(\{ members, onChange, onSubmitDraft, value/.test(source))-})--test('popover offers @everyone/@all and inserts parser-compatible strings', () => {- const component = source.slice(- source.indexOf('function GroupMentionInput'),- source.indexOf('function GroupChatWorkspace')- )- assert.ok(component.includes("['everyone', 'all']"), 'quick picks for the room-wide broadcast')- // Insertion writes exactly "@handle " — the shape parseGroupChatMentions resolves.- assert.ok(component.includes('`${value.slice(0, token.start)}@${handle} ${value.slice(caret)}`'))- // Member handles come from the same botHandle used by the parser.- assert.ok(component.includes('botHandle(member.name, member)'))- // mousedown insertion must preventDefault so the input keeps focus.- assert.ok(/onMouseDown: event => \{\s*event\.preventDefault\(\)/.test(component))-})--test('mentionTokenAt finds the active @-token at the caret', () => {- const start = source.indexOf('function mentionTokenAt')- const end = source.indexOf('function GroupMentionInput')- assert.ok(start > 0 && end > start, 'mentionTokenAt must precede GroupMentionInput')-- const ctx = {}- vm.createContext(ctx)- vm.runInContext(source.slice(start, end) + '\nthis.fn = mentionTokenAt', ctx)- const fn = ctx.fn-- // Mid-word @ tokens resolve with the right query + start offset.- // (Field-wise compare: vm-context objects have a foreign Object prototype,- // which strict deepEqual rejects.)- const eq = (actual, expected) => {- assert.equal(actual?.query, expected?.query)- assert.equal(actual?.start, expected?.start)- }- eq(fn('hey @al', 7), { query: 'al', start: 4 })- eq(fn('@', 1), { query: '', start: 0 })- eq(fn('ping @every', 11), { query: 'every', start: 5 })-- // Not a mention context: no token → popover stays closed.- assert.equal(fn('email me a@b', 12), null)- assert.equal(fn('plain text', 10), null)- // Caret before the @ is not inside the token.- assert.equal(fn('hey @al', 3), null)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-room-ux.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-room-ux.test.mjsdeleted file mode 100644index c52ede26d58..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-room-ux.test.mjs+++ /dev/null@@ -1,98 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--// Room UX cluster (Aug 2026 desktop audit): three confirmed defects in the-// group-chat surface, fixed together.-//-// #89884 — the composer was a single-line Input; Enter always submitted and-// multi-line prompts were impossible.-// #89835 — rooms opened at scroll position 0 with no anchoring; new replies-// streamed in below the fold.-// #89545 — a member whose reply outlived the turn loop stayed stranded-// until the user's NEXT send (harvest only ran inside the loop).--test('room composer is a textarea with Enter=submit, Shift+Enter=newline (#89884)', () => {- // Slice ONLY GroupMentionInput — functions merged between it and- // GroupChatWorkspace (e.g. GroupClarifyCard) legitimately use Input.- const start = source.indexOf('function GroupMentionInput')- const nextFn = source.indexOf('\nfunction ', start + 1)- const component = source.slice(start, nextFn)-- // The control is the SDK Textarea, not the single-line Input.- assert.match(component, /jsx\(Textarea, \{/)- assert.doesNotMatch(component, /jsx\(Input, \{/)- // Enter (no Shift) submits through the injected handler...- assert.match(component, /event\.key === 'Enter' && !event\.shiftKey/)- assert.match(component, /onSubmitDraft\?\.\(\)/)- // ...and the popover branch still owns Enter while it is open.- assert.match(component, /insert\(options\[active\]\.handle\)/)-})--test('room composer swallows IME composition Enters before submit/mention (#93528)', () => {- // macOS Chinese IME: Enter that confirms a candidate word fires a keydown- // the composer mistook for a send — the message went out mid-composition.- // The guard must run BEFORE the popover branch AND the submit branch, and- // cover both Chromium's isComposing flag and the keyCode 229 legacy- // VK_PROCESSKEY that macOS IMEs emit after compositionend.- const start = source.indexOf('function GroupMentionInput')- const nextFn = source.indexOf('\nfunction ', start + 1)- const component = source.slice(start, nextFn)-- const guard = component.indexOf('event.nativeEvent?.isComposing || event.keyCode === 229')- assert.ok(guard >= 0, 'IME guard present in GroupMentionInput')- const afterGuard = component.slice(guard)- // Guard returns immediately (no mention insert, no submit)...- assert.match(afterGuard.slice(0, 80), /return/)- // ...and it sits before both the popover branch and the submit branch.- assert.ok(afterGuard.indexOf('if (open) {') > 0, 'guard precedes popover branch')- assert.ok(component.indexOf("event.key === 'Enter' && !event.shiftKey") > guard, 'guard precedes submit branch')-})--test('clarify free-text input swallows IME composition Enters (#93528)', () => {- const clarify = source.slice(source.indexOf('function GroupClarifyCard'), source.indexOf('function openGroupChat'))- const guard = clarify.indexOf('event.nativeEvent?.isComposing || event.keyCode === 229')- assert.ok(guard >= 0, 'IME guard present in GroupClarifyCard')- assert.ok(clarify.indexOf("event.key === 'Enter' && questions.length === 1") > guard, 'guard precedes submit branch')-})--test('both room composers wire onSubmitDraft (#89884)', () => {- assert.match(source, /onSubmitDraft: submit,/)- assert.match(source, /onSubmitDraft: \(\) => submitReply\(id\),/)-})--test('room log anchors to the bottom with a user-scroll guard (#89835)', () => {- const workspace = source.slice(source.indexOf('function GroupChatWorkspace'))- assert.match(workspace, /bottomSentinelRef/)- assert.match(workspace, /stickToBottomRef/)- // Effect keys on log growth; the guard keeps history reading stable.- assert.match(workspace, /\[room\.log\.length, room\.running\]/)- assert.match(workspace, /scrollIntoView/)-})--test('retained-pane reopen re-anchors to the bottom (#89835 follow-up)', () => {- // A hot-mounted room pane never remounts when the user tabs back to it, so- // the workspace re-anchors on the hidden → visible edge, fed by the- // feature-detected host.paneVisibility authority (always-visible fallback- // keeps older SDKs on the previous behavior).- const workspace = source.slice(source.indexOf('function GroupChatWorkspace'))- assert.match(workspace, /visible = true/)- assert.match(workspace, /wasVisibleRef/)- assert.match(workspace, /\[visible\]/)- const mainView = source.slice(source.indexOf('function GroupChatMainView'), source.indexOf('function openGroupChat'))- assert.match(mainView, /typeof host\.paneVisibility === 'function'/)- assert.match(mainView, /plugin-workspace:\$\{ID\}:group:\$\{slugify\(group\)\}/)- assert.match(mainView, /atom\(true\)/)-})--test('stranded replies get a bounded background harvest after the loop settles (#89545)', () => {- assert.match(source, /function harvestStrandedUntilSettled\(/)- // The loop's finally block kicks it off only when members remain stranded.- assert.match(source, /strandedLeft\.length/)- // Bounded: interval + max tries, and it yields to a live loop.- const harvester = source.slice(source.indexOf('async function harvestStrandedUntilSettled'))- assert.match(harvester.slice(0, 1600), /HARVEST_MAX_TRIES/)- assert.match(harvester.slice(0, 1600), /room\.running/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-stop-thread.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-stop-thread.test.mjsdeleted file mode 100644index 37bf1365f66..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-stop-thread.test.mjs+++ /dev/null@@ -1,308 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #91868/#94569: a REAL stop path for group-chat rounds. Before-// stopGroupThread, the loop's only cancellation primitives were the epoch-// bump (checked at member boundaries only) and #93129 holds (skip FUTURE-// turns) — the plugin issued ZERO session.interrupt RPCs, so "stop" meant-// "wait for the in-flight member to finish its whole model turn". The-// primitive bumps the epoch, holds every member, interrupts the member ON-// TURN, and the runGroupChatMemberTurnLeased poll loop abandons a turn whose-// epoch went stale while its member is held.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--/** Harness mirroring group-turn-lease.test.mjs: run plugin.js in a vm with a- * scripted gateway. `busyPolls` makes session.resume report the member as- * inflight for the first N polls, so a stop can land mid-turn. */-function load({ reply = 'long answer', busyPolls = 0, onResumePoll = 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 sessions = new Map()- const runtimeToStored = new Map()- const titleToStored = new Map()- let sessionSequence = 0- const rpcLog = []- let resumePolls = 0-- const resolveSession = (profile, target) =>- (stored => (stored ? sessions.get(stored) : null))(- runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))- )-- const handle = async (method, params) => {- rpcLog.push({ method, params })-- if (method === 'session.create') {- sessionSequence += 1- const stored = `sid-${sessionSequence}`- const runtime = `rt-${sessionSequence}`- const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }- sessions.set(stored, session)- runtimeToStored.set(runtime, stored)- titleToStored.set(`${params.profile}::${params.title}`, stored)- return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }- }-- if (method === 'session.resume') {- const session = resolveSession(params.profile, params.session_id)-- if (!session) {- const err = new Error(`session not found: ${params.session_id}`)- err.code = 4007- throw err- }-- sessionSequence += 1- const runtime = `rt-${sessionSequence}`- session.runtime = runtime- runtimeToStored.set(runtime, session.stored)-- // Post-submit polls: stay "busy" for the first `busyPolls` polls so a- // stop can land mid-turn, then settle. `onResumePoll` lets a test fire- // the stop from inside the poll cadence.- const submitted = session.messages.length > 0- let busy = false-- if (submitted) {- resumePolls += 1- busy = resumePolls <= busyPolls-- if (typeof onResumePoll === 'function') {- onResumePoll(resumePolls)- }- }-- return {- session_id: runtime,- session_key: session.stored,- message_count: busy ? 0 : session.messages.length,- messages: busy ? [] : [...session.messages],- inflight: busy,- running: false- }- }-- if (method === 'prompt.submit') {- const session = resolveSession(null, params.session_id)-- if (!session) {- const err = new Error(`session-scoped RPC rejected: ${params.session_id} not in memory`)- err.code = 4001- throw err- }-- session.messages.push({ role: 'user', content: params.text })- session.messages.push({ role: 'assistant', content: reply })- return {}- }-- if (method === 'session.interrupt') {- return { interrupted: true }- }-- return {}- }-- const context = {- atom,- setTimeout: fn => {- fn()- return 0- },- clearTimeout: () => undefined,- Date,- console,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: {- request: async (method, params) => handle(method, params),- requestProfile: async (route, method, params) => handle(method, params),- retainProfile: async () => () => undefined,- 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.__stop = { stopGroupThread, runGroupChatMemberTurn, $groupChats, $groupActivity, currentGroupActivity, updateGroupChat, GROUP_ACTIVITY_LABELS, GROUP_ACTIVITY_GLYPHS };\n'- )- vm.runInNewContext(source, context, { filename: 'plugin.js' })- context.plugin.register({- storage: { get: () => null, set: () => undefined },- register: () => undefined- })- return {- ...context.__stop,- context,- rpcLog,- calls: method => rpcLog.filter(entry => entry.method === method)- }-}--const MEMBERS = [- { name: 'alpha', title: '' },- { name: 'beta', title: '' },- { name: 'gamma', title: '' }-]--/** Seed a room mid-round: epoch 3, running, alpha on turn with a live- * session id, nobody held yet. */-function seedRoom(gc, { turn = 'alpha' } = {}) {- gc.$groupChats.set({- Room: {- log: [],- watermarks: {},- sessions: { alpha: 'live-alpha-sid' },- epoch: 3,- running: true,- turn,- holds: {},- members: MEMBERS- }- })-}--test('stopGroupThread bumps the epoch, clears running/turn, and holds every member', async () => {- const gc = load()- seedRoom(gc)-- await gc.stopGroupThread('Room', 't1', MEMBERS)-- const room = gc.$groupChats.get().Room- assert.equal(room.epoch, 4, 'epoch bumped — the driving loop bails at its next boundary')- assert.equal(room.running, false)- assert.equal(room.turn, null)-- for (const member of MEMBERS) {- assert.ok(room.holds[member.name], `${member.name} is held — no future turn until an explicit release`)- assert.equal(room.holds[member.name].thread, 't1')- }-})--test('stopGroupThread interrupts the member ON TURN via its live session', async () => {- const gc = load()- seedRoom(gc, { turn: 'alpha' })-- await gc.stopGroupThread('Room', 't1', MEMBERS)-- const interrupts = gc.calls('session.interrupt')- assert.equal(interrupts.length, 1, 'exactly one interrupt — the serial loop has one member in flight')- assert.equal(interrupts[0].params.session_id, 'live-alpha-sid')-})--test('stopGroupThread with nobody on turn stops the room without any interrupt RPC', async () => {- const gc = load()- seedRoom(gc, { turn: null })-- await gc.stopGroupThread('Room', 't1', MEMBERS)-- assert.equal(gc.calls('session.interrupt').length, 0)- assert.equal(gc.$groupChats.get().Room.running, false)- assert.equal(gc.$groupChats.get().Room.epoch, 4)-})--test('stopGroupThread records a stopped activity event visible in the CURRENT run', async () => {- const gc = load()- seedRoom(gc)-- await gc.stopGroupThread('Room', 't1', MEMBERS)-- const events = gc.currentGroupActivity('Room')- const stopped = events.find(event => event.kind === 'stopped')- assert.ok(stopped, 'stopped event is tagged with the POST-bump epoch, so it survives the epoch filter')- assert.equal(stopped.member, 'You')- assert.equal(stopped.thread, 't1')- // The label comes from the shared GROUP_ACTIVITY_LABELS map (the plugin's- // label pattern) — and stays plain English, no hardcoded localized text.- assert.ok(gc.GROUP_ACTIVITY_LABELS.stopped)- assert.ok(gc.GROUP_ACTIVITY_GLYPHS.stopped)-})--test('stopGroupThread falls back to the durable room roster when called without members', async () => {- const gc = load()- seedRoom(gc)-- await gc.stopGroupThread('Room', 't1')-- const room = gc.$groupChats.get().Room- assert.equal(Object.keys(room.holds).length, MEMBERS.length)- assert.equal(gc.calls('session.interrupt').length, 1)-})--test('poll loop abandons an in-flight turn once a stop bumps the epoch and holds the member', async () => {- let gcRef = null- const gc = load({- busyPolls: 50,- onResumePoll: polls => {- // Fire the stop from inside the poll cadence, after the second- // busy poll — exactly the mid-turn click the Stop button produces.- if (polls === 2) {- void gcRef.stopGroupThread('Room', 't1', [{ name: 'helper', title: '' }])- }- }- })- gcRef = gc-- const reply = await gc.runGroupChatMemberTurn('Room', { name: 'helper', title: '' }, 'long task', 't1', [])-- assert.equal(reply, null, 'abandoned turn yields no reply')- const postStopPolls = gc.calls('session.resume').length- assert.ok(postStopPolls <= 6, `poll loop exited promptly after the stop, not at the deadline (${postStopPolls} resumes)`)- assert.equal(gc.$groupChats.get().Room.running, false)-})--test('an ordinary newer-send epoch bump WITHOUT a hold does not abandon the poll — late work still lands', async () => {- let gcRef = null- const gc = load({- reply: 'finished anyway',- busyPolls: 3,- onResumePoll: polls => {- if (polls === 1) {- // A newer user send bumps the epoch but holds nobody. The in-flight- // poll must keep going so the finished reply can still be delivered- // (the #93127 commit check decides its fate at the boundary).- gcRef.updateGroupChat('Room', r => {- r.epoch = (r.epoch || 0) + 1- return r- })- }- }- })- gcRef = gc-- const reply = await gc.runGroupChatMemberTurn('Room', { name: 'helper', title: '' }, 'long task', 't1', [])-- assert.equal(reply, 'finished anyway', 'epoch churn alone never abandons a live turn')-})--test('Stop button: workspace renders it while the room is running and wires it to stopGroupThread', () => {- const workspace = pluginSource.slice(pluginSource.indexOf('function GroupChatWorkspace'))- // Visible while a round is running…- assert.match(workspace, /room\.running\s*\?\s*jsx\('button'/, 'Stop button is gated on room.running')- // …and wired to the real primitive, not a per-member interrupt spray.- assert.match(workspace, /stopGroupThread\(/, 'button calls the stopGroupThread primitive')- assert.doesNotMatch(workspace, /stopAllBots/, 'the #94570 interrupt-only shell was rewired, not kept')-})--test('no hardcoded CJK label in the room workspace (the #94570 shell shipped a localized 停止)', () => {- const workspace = pluginSource.slice(pluginSource.indexOf('function GroupChatWorkspace'))- assert.doesNotMatch(workspace, /停止/, 'the #94570 hardcoded label must not survive the salvage')- assert.doesNotMatch(workspace, /[\u4e00-\u9fff]/, 'labels stay in the plugin label pattern — plain English strings')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-to-local-bot-handoff.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-to-local-bot-handoff.test.mjsdeleted file mode 100644index 8feedb4a20d..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-to-local-bot-handoff.test.mjs+++ /dev/null@@ -1,120 +0,0 @@-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 atom = initial => {- let value = initial- return { get: () => value, set: next => { value = typeof next === 'function' ? next(value) : next }, listen: () => () => {} }-}-const jsx = (type, props = {}) => ({ type, props })-const find = (tree, predicate) => {- if (tree == null || typeof tree !== 'object') return null- if (Array.isArray(tree)) {- for (const child of tree) { const match = find(child, predicate); if (match) return match }- return null- }- return predicate(tree) ? tree : find(tree.props?.children, predicate)-}--function load({ rejectOpen = false, rejectPrepare = false } = {}) {- const timeline = []- const host = {- state: {- profile: { get: () => 'default', listen: () => {} },- gateway: { get: () => 'open', listen: () => {} },- connectionId: { get: () => 'local', listen: () => {} }- },- request: async () => ({ profiles: [], sessions: [] }),- notify: () => {}, notifyError: error => timeline.push({ type: 'error', error }),- openSession: async () => {}, ensureAgent: async () => {}, requestProfile: async () => ({}),- activeConnectionId: () => 'local', warmAgent: () => {}, warmProfile: () => {},- newChat: () => timeline.push({ type: 'newChat' }), navigate: () => {}- }- const ui = 'Button Checkbox Codicon ConfirmDialog ContextMenu ContextMenuContent ContextMenuItem ContextMenuSeparator ContextMenuTrigger CopyButton Dialog DialogContent DialogDescription DialogFooter DialogHeader DialogTitle DropdownMenu DropdownMenuContent DropdownMenuItem DropdownMenuTrigger EmptyState GlyphSpinner Input ScrollArea SearchField Select SelectContent SelectItem SelectTrigger SelectValue Switch Textarea Tip'.split(' ')- const context = {- atom, jsx, jsxs: jsx, cn: (...values) => values.filter(Boolean).join(' '), haptic: () => {},- useEffect: () => {}, useMemo: fn => fn(), useRef: value => ({ current: typeof value === 'function' ? value() : value }),- useState: value => [typeof value === 'function' ? value() : value, () => {}],- useValue: store => store?.get ? store.get() : store,- useQuery: () => ({ data: [], isLoading: false, isFetching: false, refetch: () => {} }),- ...Object.fromEntries(ui.map(name => [name, name])),- PALETTE_AREA: 'palette', COMPOSER_AREAS: { middleware: 'middleware' },- profileColor: () => '#000', queryClient: { invalidateQueries: () => {} }, relativeTime: () => 'now',- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => {} } },- setTimeout, clearTimeout, console, Date, Math, JSON, Promise, Map, Set, URL, Error,- Array, Object, String, Boolean, Number, RegExp, host- }- const code = 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.__h={BotRow,BotsPane,openRosterBot,openGroupChat,groupChatMainTabs,$groupChatWorkspace,$groupChats};')- vm.runInNewContext(code, context, { filename: 'plugin.js' })- context.openBotCanonicalChat = async bot => {- timeline.push({ type: 'canonicalOpen', bot })- if (rejectOpen) throw new Error('canonical open failed')- return { registryId: 'stored-chat', openedId: 'stored-chat' }- }- if (rejectPrepare) context.prepareBotSource = async () => { throw new Error('source preparation failed') }- const api = context.__h- const registerGroup = group => {- api.$groupChats.set({ ...api.$groupChats.get(), [group]: { log: [], watermarks: {}, sessions: {}, stranded: {} } })- host.openWorkspace = id => () => timeline.push({ type: 'workspaceClose', id })- api.openGroupChat(group)- return { closed: () => timeline.filter(event => event.type === 'workspaceClose' && event.id.includes(':group:')).length }- }- const botRow = bot => {- const tree = api.BotRow({ bot, onEdit: () => {} })- return tree.type === 'button' ? tree : tree.props.children[0].props.children- }- const activeOnOpen = find(api.BotsPane(), node => node?.props && typeof node.props.onOpen === 'function' && 'roster' in node.props).props.onOpen- return { api, timeline, registerGroup, botRow, activeOnOpen }-}--const drain = async () => { await new Promise(resolve => setImmediate(resolve)); await new Promise(resolve => setImmediate(resolve)) }-const bot = { name: 'alpha', title: 'Alpha' }-const assertCloseBeforeOpen = runtime => {- const closed = runtime.timeline.findIndex(event => event.type === 'workspaceClose' && event.id.includes(':group:'))- const opened = runtime.timeline.findIndex(event => event.type === 'canonicalOpen')- assert.ok(closed >= 0 && opened >= 0 && closed < opened)-}--test('central owner open closes the registered group tab before canonical open', async () => {- const runtime = load(), tab = runtime.registerGroup('Core')- assert.equal(await runtime.api.openRosterBot(bot), true)- assert.equal(tab.closed(), 1)- assert.equal(runtime.api.groupChatMainTabs.has('Core'), false)- assertCloseBeforeOpen(runtime)-})--test('BotRow and Active Now both delegate through the central owner open', async () => {- for (const invoke of [runtime => runtime.botRow(bot).props.onClick(), runtime => runtime.activeOnOpen(bot)]) {- const runtime = load(); runtime.registerGroup('Core'); invoke(runtime); await drain(); assertCloseBeforeOpen(runtime)- }-})--test('failed canonical open restores the group fallback and surfaces an error', async () => {- const runtime = load({ rejectOpen: true }), tab = runtime.registerGroup('Core')- assert.equal(await runtime.api.openRosterBot(bot), false)- assert.equal(tab.closed(), 1)- assert.equal(runtime.api.$groupChatWorkspace.get(), 'Core')- assert.equal(runtime.api.groupChatMainTabs.has('Core'), true)- assert.ok(runtime.timeline.some(event => event.type === 'error'))-})--test('failed source preparation restores the group fallback', async () => {- const runtime = load({ rejectPrepare: true }); runtime.registerGroup('Core')- assert.equal(await runtime.api.openRosterBot({ ...bot, sourceScoped: true, connectionId: 'local' }), false)- assert.equal(runtime.api.$groupChatWorkspace.get(), 'Core')-})--test('owner open with no selected group is safe', async () => {- const runtime = load()- assert.equal(await runtime.api.openRosterBot(bot), true)- assert.equal(runtime.timeline.some(event => event.type === 'workspaceClose' && event.id.includes(':group:')), false)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-lease.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-lease.test.mjsdeleted file mode 100644index 446611e4f51..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-lease.test.mjs+++ /dev/null@@ -1,303 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #93602: sub-profile bot silent in a group room. A member turn is a-// session-scoped RPC sequence (resume → attach → prompt.submit → poll) issued-// with the runtime id its FIRST rpc minted, but every requestForBot call rides-// its own request-scoped socket lease — at refcount 0 the leased secondary is-// disposed, the gateway detaches the runtime session on WS disconnect, the-// orphan reaper frees it, and the next RPC dies 4001 "not in memory" with no-// reply in the room. The fix holds a retained per-turn lease-// (host.retainProfile) across the whole sequence and adds a one-shot-// catch-and-retry on prompt.submit that re-resumes via the STORED id.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--/** Harness mirroring group-chat-attachments.test.mjs, extended with a- * refcounted host.requestProfile/host.retainProfile pair so socket lease- * lifetimes are assertable. */-function load({ failFirstSubmitWith = null, failEverySubmitWith = null, reply = 'hello from turn', replyMessages = 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 sessions = new Map()- const runtimeToStored = new Map()- const titleToStored = new Map()- let sessionSequence = 0- let submits = 0- const rpcLog = []-- // Mock socket-pool refcount for the member's route: every RPC takes a- // per-request lease (acquire → handle → release), exactly like- // requestGatewayForAgent in store/gateway.ts. `disposals` counts every time- // the refcount hits 0 — each one is a socket close that reaps the runtime- // session in production.- let refcount = 0- let disposals = 0- const timeline = []-- const acquire = () => {- refcount += 1- }- const release = () => {- refcount -= 1- if (refcount === 0) {- disposals += 1- }- }-- const resolveSession = (profile, target) =>- (stored => (stored ? sessions.get(stored) : null))(- runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))- )-- const handle = async (method, params) => {- if (method === 'session.create') {- sessionSequence += 1- const stored = `sid-${sessionSequence}`- const runtime = `rt-${sessionSequence}`- const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }- sessions.set(stored, session)- runtimeToStored.set(runtime, stored)- titleToStored.set(`${params.profile}::${params.title}`, stored)- return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }- }- if (method === 'session.resume') {- const session = resolveSession(params.profile, params.session_id)- if (!session) {- const err = new Error(`session not found: ${params.session_id}`)- err.code = 4007- throw err- }- // Every resume mints a FRESH runtime id — the stored id is the durable- // identity, mirroring the gateway's resume contract.- sessionSequence += 1- const runtime = `rt-${sessionSequence}`- session.runtime = runtime- runtimeToStored.set(runtime, session.stored)- return {- session_id: runtime,- session_key: session.stored,- message_count: session.messages.length,- messages: params.omit_messages ? [] : [...session.messages],- inflight: false,- running: false- }- }- if (method === 'image.attach_bytes' || method === 'pdf.attach' || method === 'file.attach') {- const session = resolveSession(null, params.session_id)- if (!session) {- const err = new Error(`session-scoped RPC rejected: ${params.session_id} not in memory`)- err.code = 4001- throw err- }- return { attached: true }- }- if (method === 'prompt.submit') {- submits += 1- if (failEverySubmitWith) {- throw failEverySubmitWith- }- if (submits === 1 && failFirstSubmitWith) {- throw failFirstSubmitWith- }- const session = resolveSession(null, params.session_id)- if (!session) {- const err = new Error(`session-scoped RPC rejected: ${params.session_id} not in memory`)- err.code = 4001- throw err- }- session.messages.push({ role: 'user', content: params.text })- if (replyMessages) {- for (const msg of replyMessages) {- session.messages.push(msg)- }- } else {- session.messages.push({ role: 'assistant', content: reply })- }- return {}- }- return {}- }-- const context = {- atom,- setTimeout: fn => {- fn()- return 0- },- clearTimeout: () => undefined,- Date,- console,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: {- request: async (method, params) => handle(method, params),- requestProfile: async (route, method, params) => {- acquire()- try {- return await handle(method, params)- } finally {- release()- rpcLog.push({ method, refcountAfter: refcount })- timeline.push(method)- }- },- retainProfile: async () => {- timeline.push('retain')- acquire()- let released = false- return () => {- if (!released) {- released = true- timeline.push('release')- release()- }- }- },- 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.__lease = { runGroupChatMemberTurn, submitGroupTurnPrompt, isSessionGoneError, $groupChats };\n'- )- vm.runInNewContext(source, context, { filename: 'plugin.js' })- context.plugin.register({- storage: { get: () => null, set: () => undefined },- register: () => undefined- })- return {- ...context.__lease,- context,- rpcLog,- timeline,- stats: () => ({ refcount, disposals, submits })- }-}--const LOCAL_MEMBER = { name: 'helper', title: '' }-const ROUTED_MEMBER = { name: 'helper', connectionId: 'mini', remoteSource: true }-const IMG = { name: 'shot.png', data: 'data:image/png;base64,iVBORw0KGgo=' }--test('isSessionGoneError: 4001 and "not in memory" are recoverable, 4007 is not', () => {- const gc = load()- const gone = new Error('x')- gone.code = 4001- assert.equal(gc.isSessionGoneError(gone), true)- assert.equal(gc.isSessionGoneError(new Error('session_id=rt-1 not in memory')), true)- const missing = new Error('session not found')- missing.code = 4007- assert.equal(gc.isSessionGoneError(missing), false)- assert.equal(gc.isSessionGoneError(null), false)- assert.equal(gc.isSessionGoneError(new Error('network blip')), false)-})--test('a 4001 on the first prompt.submit recovers via session.resume on the STORED id and delivers', async () => {- const reaped = new Error("session-scoped RPC rejected: session_id='rt-1' not in memory")- reaped.code = 4001- const gc = load({ failFirstSubmitWith: reaped, reply: 'recovered reply' })-- const reply = await gc.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi there', 't1', [])-- assert.equal(reply, 'recovered reply')- // One failed submit + exactly one retry — never more.- assert.equal(gc.stats().submits, 2)- // The recovery re-resumed the durable stored id, not the dead runtime id.- const room = gc.$groupChats.get().Room- assert.ok(room.sessions.helper, 'stored session id survives in the room record')-})--test('a persistent non-4001 submit failure is NOT retried and still surfaces', async () => {- const fatal = new Error('backend exploded')- const gc = load({ failEverySubmitWith: fatal })-- await assert.rejects(() => gc.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi', 't1', []), /backend exploded/)- assert.equal(gc.stats().submits, 1)-})--test('the per-turn lease is acquired before any session RPC and held across attach+submit', async () => {- const gc = load({ reply: 'routed reply' })-- const reply = await gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'look at this', 't1', [IMG])-- assert.equal(reply, 'routed reply')- // The retain landed before the first session-scoped RPC on the route.- assert.equal(gc.timeline[0], 'retain')- // The socket was NEVER disposed mid-turn: after every per-request lease- // released, the turn lease still held the refcount above zero.- for (const rpc of gc.rpcLog) {- assert.ok(rpc.refcountAfter >= 1, `${rpc.method} left refcount ${rpc.refcountAfter} — socket disposed mid-turn`)- }- // Exactly one disposal, and only via the turn lease's own release at the end.- assert.equal(gc.stats().disposals, 1)- assert.equal(gc.timeline[gc.timeline.length - 1], 'release')-})--test('the per-turn lease is released after the turn — refcount returns to zero', async () => {- const gc = load({ reply: 'done' })-- await gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', [])-- assert.equal(gc.stats().refcount, 0)- assert.equal(gc.stats().disposals, 1)-})--test('the per-turn lease is released even when the turn fails', async () => {- const fatal = new Error('backend exploded')- const gc = load({ failEverySubmitWith: fatal })-- await assert.rejects(() => gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', []))-- assert.equal(gc.stats().refcount, 0)-})--test('hosts without retainProfile still run the turn (feature detection)', async () => {- const gc = load({ reply: 'legacy ok' })- delete gc.context.host.retainProfile-- const reply = await gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', [])-- assert.equal(reply, 'legacy ok')-})--// #94376: a Codex intent-ack continuation nudge can land a substantive-// answer, then get a synthetic "(pass)" reply to the nudge itself. The-// substantive answer must still surface, not the trailing pass.-test('a substantive answer followed by a synthetic continuation (pass) still surfaces the answer', async () => {- const gc = load({- replyMessages: [- { role: 'assistant', content: "Yes. I welcomed them, and I'll review their first assignments with them." },- { role: 'user', content: '[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.]' },- { role: 'assistant', content: '(pass)' }- ]- })-- const reply = await gc.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'Did you welcome the new teammate?', 't1', [])-- assert.equal(reply, "Yes. I welcomed them, and I'll review their first assignments with them.")-})--test('a genuine pass-only turn (no prior substantive answer) still reads as silent', async () => {- const gc = load({ reply: '(pass)' })-- const reply = await gc.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'anything new?', 't1', [])-- assert.equal(reply, '(pass)')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjsdeleted file mode 100644index 391da6b7b10..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-races.test.mjs+++ /dev/null@@ -1,105 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #93127: duplicate room delivery. Two raceable paths existed:-// 1. a member turn mid-flight when the room epoch bumps still commits its-// reply + watermark when it returns (the stale loop only noticed-// supersession at the NEXT member boundary), and-// 2. the stale loop and the fresh loop can both append the same reply.-// The fix re-checks the epoch after the turn returns (shouldCommitMemberTurn)-// and drops adjacent byte-identical member echoes (isDuplicateGroupAppend).--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadHelpers() {- const start = pluginSource.indexOf('// --- room-turn decision helpers (#93127)')- const end = pluginSource.indexOf('// --- end room-turn decision helpers ---', start)- assert.notEqual(start, -1, 'plugin carries the room-turn helper block')- assert.notEqual(end, -1, 'room-turn helper block has a stable end marker')- const context = {}- vm.runInNewContext(- `${pluginSource.slice(start, end)}-globalThis.shouldCommitMemberTurn = shouldCommitMemberTurn-globalThis.isDuplicateGroupAppend = isDuplicateGroupAppend`,- context- )- return context-}--const memberEntry = (name, text, thread = 't1', at = Date.now(), source) => ({- id: 'x',- at,- from: { kind: 'member', name, ...(source ? { source } : {}) },- text,- thread-})--test('a superseded turn is discarded — epoch moved on while the turn ran', () => {- const { shouldCommitMemberTurn } = loadHelpers()- assert.equal(shouldCommitMemberTurn(3, 4), false)- assert.equal(shouldCommitMemberTurn(3, 7), false)- // explicit same-thread supersession- assert.equal(shouldCommitMemberTurn(3, 4, true), false)-})--test('a current turn commits — epoch unchanged since dispatch', () => {- const { shouldCommitMemberTurn } = loadHelpers()- assert.equal(shouldCommitMemberTurn(3, 3), true)- assert.equal(shouldCommitMemberTurn(0, 0), true)-})--test('a cross-thread epoch bump does NOT discard finished work (no fresh loop re-drives it)', () => {- const { shouldCommitMemberTurn } = loadHelpers()- // Epoch moved, but no newer user entry landed in THIS thread: the- // superseding send lives in another thread whose loop filters this one- // out — dropping the reply would lose completed work forever.- assert.equal(shouldCommitMemberTurn(3, 4, false), true)-})--test('adjacent identical member reply is a duplicate append', () => {- const { isDuplicateGroupAppend } = loadHelpers()- const last = memberEntry('impl', 'Stopped. Standing by.')- const dup = isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Stopped. Standing by.', 't1')- assert.equal(dup, true)-})--test('identical text from a DIFFERENT member is not a duplicate', () => {- const { isDuplicateGroupAppend } = loadHelpers()- const last = memberEntry('impl', 'Confirmed.')- assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'reviewer' }, 'Confirmed.', 't1'), false)-})--test('identical text from the same member on another SOURCE is not a duplicate', () => {- const { isDuplicateGroupAppend } = loadHelpers()- const last = memberEntry('impl', 'Confirmed.', 't1', Date.now(), 'laptop')- assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Confirmed.', 't1'), false)-})--test('same text after an intervening entry is not a duplicate — only the LAST entry is checked', () => {- const { isDuplicateGroupAppend } = loadHelpers()- // The helper only ever receives the immediately-preceding entry; an- // intervening entry means lastEntry is the interloper, not the echo.- const intervening = memberEntry('reviewer', 'ack')- assert.equal(isDuplicateGroupAppend(intervening, { kind: 'member', name: 'impl' }, 'Confirmed.', 't1'), false)-})--test('identical text in a DIFFERENT thread is not a duplicate', () => {- const { isDuplicateGroupAppend } = loadHelpers()- const last = memberEntry('impl', 'Confirmed.', 'thread-a')- assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Confirmed.', 'thread-b'), false)-})--test('identical text outside the recency window is not a duplicate', () => {- const { isDuplicateGroupAppend } = loadHelpers()- const hourAgo = Date.now() - 60 * 60 * 1000- const last = memberEntry('impl', 'Done.', 't1', hourAgo)- assert.equal(isDuplicateGroupAppend(last, { kind: 'member', name: 'impl' }, 'Done.', 't1'), false)-})--test('user entries are never deduped', () => {- const { isDuplicateGroupAppend } = loadHelpers()- const last = { id: 'x', at: Date.now(), from: { kind: 'user', name: 'You' }, text: 'stop', thread: 't1' }- assert.equal(isDuplicateGroupAppend(last, { kind: 'user', name: 'You' }, 'stop', 't1'), false)-})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.mjsdeleted file mode 100644index 9a3aca0d2fe..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs+++ /dev/null@@ -1,318 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Bot Mode sessions are ALWAYS hidden from the global Sessions sidebar-// (canonical Bot Chats and group-chat member sessions alike) via the core-// generic `hidden` session flag. There is no user pref: session.create-// passes hidden:true unconditionally, and hideOwnedBotSessions() sweeps-// every known plugin-owned session id through session.set_hidden so rows-// born visible under the old pref get reconciled.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadCreate() {- 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: () => {},- backendTargetProfile: (route, name) => route?.targetProfile || name,- botOwner: name => ({ bot: { name }, key: name, name, route: null }),- requestForBot: (_bot, method, params) => context.host.request(method, params),- 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 always passes hidden:true — no pref gate', async () => {- const { create, created } = loadCreate()- await create('alpha')- assert.equal(created.length, 1)- assert.equal(created[0].hidden, true)- assert.equal(created[0].title, 'Bot Chat')-})--test('group member session.create is unconditionally hidden too', () => {- // Source contract on ensureGroupChatSession: the create carries a literal- // hidden:true, with no $hideBotChats conditional anywhere in the plugin.- const fn = source.slice(source.indexOf('async function ensureGroupChatSession('), source.indexOf('const GROUP_TURN_TIMEOUT_MS'))- assert.match(fn, /hidden: true/)- assert.equal(source.includes('$hideBotChats'), false, 'the old pref atom must be gone')-})--test('hideOwnedBotSessions sweeps room member sessions by id', async () => {- const start = source.indexOf('function hideOwnedBotSessions()')- const end = source.indexOf('/** Fetch server-side avatars', start)- const calls = []- const context = {- host: {- setPersistedSessionHidden: async (_route, options) => {- calls.push({ method: 'session.set_hidden', params: { session_id: options.sessionId, hidden: options.hidden } })- },- request: async (method, params) => {- calls.push({ method, params })- return {}- }- },- $botMeta: { get: () => ({}) },- $lastRoster: { get: () => [] },- backendTargetProfile: (route, name) => route?.targetProfile || name,- botConnectionRoute: () => null,- botMetaKey: bot => bot.name,- requestForBot: (_bot, method, params) => context.host.request(method, params),- $groupChats: {- get: () => ({- Core: { sessions: { alpha: 'room-core-a', beta: 'room-core-b' } },- Quiet: { sessions: { alpha: 'room-core-a' } }, // duplicate id — must dedupe- Legacy: {} // pre-sessions room shape- })- },- sweepBotProfileSessions: async () => undefined- }- const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')- vm.runInNewContext(section, context, { filename: 'h.js' })- await context.__h.hideOwnedBotSessions()-- const ids = calls.filter(c => c.method === 'session.set_hidden').map(c => c.params.session_id).sort()- assert.deepEqual(ids, ['room-core-a', 'room-core-b'])- const hiddenCalls = calls.filter(c => c.method === 'session.set_hidden')- assert.ok(hiddenCalls.every(c => c.params.hidden === true))-})--test('hideOwnedBotSessions never consults stored canonical pointers', () => {- // Canonical Bot Chats are hidden by the TITLE sweep (they are identified by- // name, not by pointer) — the load-time reconciliation must not read- // $botMeta chat ids or verify them via profiles.list.- const start = source.indexOf('function hideOwnedBotSessions()')- const end = source.indexOf('// Titles Bot Mode itself mints', start)- const section = source.slice(start, end)- assert.doesNotMatch(section, /botMeta/)- assert.doesNotMatch(section, /profiles\.list/)-})--test('remote group member sessions derive their immutable owner from persisted room members', async () => {- const start = source.indexOf('function hideOwnedBotSessions()')- const end = source.indexOf('/** Fetch server-side avatars', start)- const ambient = []- const routed = []- const owner = {- name: 'worker',- sourceScoped: true,- route: {- connectionId: 'source-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'backend-worker'- }- }- const context = {- host: {- request: async (method, params) => ambient.push({ method, params }),- setPersistedSessionHidden: async (route, options) => routed.push({ route, options })- },- $botMeta: { get: () => ({}) },- $lastRoster: { get: () => [] },- $groupChats: {- get: () => ({- Core: {- sessions: { 'source-a::worker': 'remote-room-1' },- members: [owner]- }- })- },- groupMemberKey: member => `${member.route.connectionId}::${member.name}`,- botConnectionRoute: bot => bot.route || null,- backendTargetProfile: (route, fallback) => route?.targetProfile || fallback,- requestForBot: async () => {- throw new Error('gateway RPC must not be used')- },- sweepBotProfileSessions: async () => undefined- }- const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')- vm.runInNewContext(section, context, { filename: 'h-remote.js' })-- await context.__h.hideOwnedBotSessions()-- assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)- assert.equal(routed.length, 1)- assert.equal(routed[0].route.connectionId, 'source-a')- assert.equal(routed[0].route.targetProfile, 'backend-worker')- assert.equal(routed[0].options.sessionId, 'remote-room-1')-})--test('same session id on two remote group owners never hides an ambient collision', async () => {- const start = source.indexOf('function hideOwnedBotSessions()')- const end = source.indexOf('/** Fetch server-side avatars', start)- const ambient = []- const routed = []- const owner = connectionId => ({- name: 'worker',- sourceScoped: true,- route: { connectionId, mode: 'remote', profile: 'worker', targetProfile: 'backend-worker' }- })- const ownerA = owner('source-a')- const ownerB = owner('source-b')- const context = {- host: {- request: async (method, params) => ambient.push({ method, params }),- setPersistedSessionHidden: async (route, options) => routed.push({ route, options })- },- $botMeta: { get: () => ({}) },- $lastRoster: { get: () => [] },- $groupChats: {- get: () => ({- A: { sessions: { 'source-a::worker': 'same-id' }, sessionOwners: { 'source-a::worker': ownerA } },- B: { sessions: { 'source-b::worker': 'same-id' }, sessionOwners: { 'source-b::worker': ownerB } }- })- },- groupMemberKey: member => `${member.route.connectionId}::${member.name}`,- botConnectionRoute: bot => bot.route || null,- backendTargetProfile: (route, fallback) => route?.targetProfile || fallback,- requestForBot: async () => {- throw new Error('gateway RPC must not be used')- },- sweepBotProfileSessions: async () => undefined- }- const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')- vm.runInNewContext(section, context, { filename: 'h-collision.js' })-- await context.__h.hideOwnedBotSessions()-- assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)- assert.deepEqual(routed.map(call => call.route.connectionId).sort(), ['source-a', 'source-b'])- assert.ok(routed.every(call => call.options.sessionId === 'same-id'))-})--test('malformed persisted owner for a source-qualified group session fails closed', async () => {- const start = source.indexOf('function hideOwnedBotSessions()')- const end = source.indexOf('/** Fetch server-side avatars', start)- const ambient = []- const routed = []- const context = {- host: { request: async (method, params) => ambient.push({ method, params }) },- $botMeta: { get: () => ({}) },- $lastRoster: { get: () => [] },- $groupChats: {- get: () => ({- LegacyRemote: {- sessions: { 'source-a::worker': 'same-id' },- sessionOwners: { 'source-a::worker': { name: 'worker' } }- }- })- },- groupMemberKey: member => member?.name,- requestForBot: async (bot, method, params) => routed.push({ bot, method, params }),- sweepBotProfileSessions: async () => undefined- }- const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')- vm.runInNewContext(section, context, { filename: 'h-malformed-owner.js' })-- await context.__h.hideOwnedBotSessions()-- assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)- assert.equal(routed.length, 0)-})--test('sweepBotProfileSessions hides Bot-Mode-titled rows per roster bot, and only those', async () => {- // Ownership-based half of the sweep: CLI-born "Agent Inbox" / extra- // "Bot Chat" rows live in bot profiles but are unknown to $botMeta /- // $groupChats, so the id-based sweep never reaches them. This sweep lists- // each roster bot's own sessions and hides rows by exact plumbing title- // ('Bot Chat', 'Agent Inbox', 'Group: …' prefix) — never a user-titled row.- const start = source.indexOf('function hideOwnedBotSessions()')- const end = source.indexOf('/** Fetch server-side avatars', start)- const calls = []- const nowSeconds = 1_000- const rowsByProfile = {- alpha: [- { id: 'a-1', title: 'Bot Chat', started_at: 1 },- { id: 'a-2', title: 'Agent Inbox', started_at: 1 },- { id: 'a-3', title: 'Group: Core', started_at: 1 },- { id: 'a-4', title: 'My real conversation', started_at: 1 },- { id: 'a-5', title: 'Bot Chat notes', started_at: 1 }, // not an exact title — kept- { id: 'a-6', title: 'Bot Chat', started_at: nowSeconds - 299 }, // live draft — kept- { id: 'a-7', title: 'Agent Inbox' }, // missing age metadata — kept fail-closed- { id: 'a-8', title: 'Bot Chat', started_at: nowSeconds - 300 } // boundary reached — hidden- ],- remy: [{ id: 'r-1', title: 'Agent Inbox', started_at: 1 }]- }- const context = {- host: {- request: async () => ({}),- listPersistedSessions: async (route, options) => {- calls.push({ bot: options.profile, method: 'persisted.list', params: options, route })- return { sessions: rowsByProfile[options.profile] || [] }- },- setPersistedSessionHidden: async (route, options) => {- calls.push({ bot: options.profile, method: 'persisted.set_hidden', params: options, route })- }- },- $botMeta: { get: () => ({}) },- $groupChats: { get: () => ({}) },- $lastRoster: { get: () => [{ name: 'alpha' }, { name: 'remy', remoteSource: true, connectionId: 'mini' }] },- PROFILE_SESSION_LIST_LIMIT: 200,- botConnectionRoute: bot =>- bot.remoteSource- ? { connectionId: bot.connectionId, mode: 'remote', profile: bot.name, targetProfile: bot.name }- : null,- backendTargetProfile: (route, fallback) => route?.targetProfile || fallback,- requestForBot: async (bot, method, params) => {- calls.push({ bot: bot.name, method, params })- if (method === 'session.list') {- return { sessions: rowsByProfile[params.profile] || [] }- }- return {}- }- }- const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions, sweepBotProfileSessions };\n')- vm.runInNewContext(section, context, { filename: 's.js' })- await context.__h.sweepBotProfileSessions(nowSeconds)-- const lists = calls.filter(c => c.method === 'persisted.list')- assert.deepEqual(lists.map(c => c.params.profile).sort(), ['alpha', 'remy'])- // Visible-rows-only listing keeps the sweep idempotent.- assert.ok(lists.every(c => !c.params.include_hidden))-- const hidden = calls.filter(c => c.method === 'persisted.set_hidden')- assert.deepEqual(- hidden.map(c => c.params.sessionId).sort(),- ['a-1', 'a-2', 'a-3', 'a-8', 'r-1'],- 'exact plumbing titles only — user-titled and brand-new rows stay visible'- )- assert.ok(hidden.every(c => c.params.hidden === true))- // Remote-source rows keep their immutable source owner on the REST route.- assert.equal(hidden.find(c => c.params.sessionId === 'r-1').route.connectionId, 'mini')-})--test('hideOwnedBotSessions chains the ownership sweep and survives its absence of context', async () => {- // The load/reconnect entrypoint runs BOTH halves: known ids first, then- // the roster-wide title sweep (best-effort — a throwing sweep never- // breaks the id half).- assert.match(source, /return Promise\.all\(\[known, sweepBotProfileSessions\(\)\.catch\(\(\) => undefined\)\]\)/)-})--test('the canonical-chat adoption scan lists with include_hidden', () => {- // The one session.list consumer that must see the always-hidden rows:- // findExistingCanonicalChat (the registry lookup) — canonical Bot Chats- // are born hidden, so a visible-only scan would miss the very row that IS- // the bot's identity. The lookup rides the bot's own source (requestForBot)- // and fails CLOSED: a thrown lookup never falls through to minting.- assert.match(- source,- /requestForBot\(bot, 'session\.list', \{\s*profile: backendTargetProfile\(route, name\),\s*title: CANONICAL_CHAT_TITLE,[\s\S]{0,200}?include_hidden: true\s*\}\)\s*\} catch \(error\) \{[\s\S]{0,800}?const rows = res\?\.sessions \?\? \[\]\s*return rows\.find\(row => isCanonicalBotChatHistory\(row\)\)/- )-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjsdeleted file mode 100644index 2f228921016..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bots.test.mjs+++ /dev/null@@ -1,222 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Per-bot Hide/Unhide: right-click → Hide Bot persists `hidden: true` in bot-// meta (local ctx.storage + server ui_meta via saveBotMeta), hidden bots drop-// out of the roster list, and a header eye toggle — rendered only while at-// least one bot is hidden — reveals them dimmed for right-click → Unhide.-// Hiding is a roster-DISPLAY concern only: mentions, group chats, and the-// name-collision check keep the full roster.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function load({ toastsOn = false } = {}) {- 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 notifications = []- const requests = []- const context = {- atom,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: {- state: {- profile: { get: () => 'default', listen: () => undefined },- gateway: { get: () => 'open', listen: () => undefined }- },- request: (method, params) => {- requests.push({ method, params })- return Promise.resolve({ applied: { ui_meta: true } })- },- notify: params => notifications.push(params)- },- sdk: new Proxy({}, { get: () => 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(`-globalThis.__hide = {- isBotHidden,- fallbackSelectionAfterHide,- mergeServerMeta,- saveBotMeta,- trackInboundActivity,- $botMeta,- $botUnread,- $selectedBot,- $lastRoster,- $showHiddenBots,- $activityToasts,- setPluginCtx: value => { pluginCtx = value }-};-`)- vm.runInNewContext(source, context, { filename: 'plugin.js' })- if (toastsOn) {- context.__hide.$activityToasts.set(true)- }- return { ...context.__hide, notifications, requests }-}--test('hide: saveBotMeta persists hidden:true locally and ships it in server ui_meta', async () => {- const t = load()- const writes = []- t.setPluginCtx({ storage: { set: (key, value) => writes.push({ key, value }) } })-- await t.saveBotMeta('default', { hidden: true })-- assert.equal(t.$botMeta.get().default.hidden, true)- assert.equal(writes.at(-1).key, 'bot-meta')- assert.equal(writes.at(-1).value.default.hidden, true)- const configure = t.requests.find(r => r.method === 'profiles.configure')- assert.equal(configure.params.ui_meta['hermes-bots'].hidden, true)-})--test('roster: hidden bots are filtered out; remote-source rows of the same name stay visible', () => {- const t = load()- t.$botMeta.set({ ghost: { hidden: true } })- const roster = [- { name: 'default' },- { name: 'ghost' },- { name: 'ghost', remoteSource: true, connectionId: 'mini' }- ]- const meta = t.$botMeta.get()- const visible = roster.filter(bot => !t.isBotHidden(bot, meta))-- assert.equal(JSON.stringify(visible.map(b => `${b.remoteSource ? 'r:' : ''}${b.name}`)), JSON.stringify(['default', 'r:ghost']))-})--test('unhide: hidden:false clears locally AND survives a mergeServerMeta round-trip', async () => {- const t = load()- const writes = []- t.setPluginCtx({ storage: { set: (key, value) => writes.push({ key, value }) } })- t.$botMeta.set({ ghost: { hidden: true, title: 'Ghost' } })-- await t.saveBotMeta('ghost', { hidden: false })- assert.equal(t.$botMeta.get().ghost.hidden, false, 'local merge must clear the flag')- const configure = t.requests.find(r => r.method === 'profiles.configure')- assert.equal(configure.params.ui_meta['hermes-bots'].hidden, false, 'server copy carries the literal false')-- // Machine B: its stale local copy still says hidden:true; the server- // overlay (which merges OVER local) must win with the false.- t.$botMeta.set({ ghost: { hidden: true, title: 'Ghost' } })- t.mergeServerMeta([{ name: 'ghost', ui_meta: { 'hermes-bots': { hidden: false, title: 'Ghost' } } }])- assert.equal(t.$botMeta.get().ghost.hidden, false, 'server false must beat stale local true')-})--test('cross-machine: a hide done elsewhere lands via mergeServerMeta and persists to storage', () => {- const t = load()- const writes = []- t.setPluginCtx({ storage: { set: (key, value) => writes.push({ key, value }) } })- t.$botMeta.set({ ghost: { title: 'Ghost' } })-- t.mergeServerMeta([{ name: 'ghost', ui_meta: { 'hermes-bots': { hidden: true, title: 'Ghost' } } }])-- assert.equal(t.$botMeta.get().ghost.hidden, true)- assert.equal(writes.at(-1).value.ghost.hidden, true)-})--test('selection: hiding the selected bot falls back to the first visible bot', () => {- const t = load()- t.$selectedBot.set('ghost')- t.$botMeta.set({ ghost: { hidden: true } })- t.$lastRoster.set([{ name: 'ghost' }, { name: 'scribe' }, { name: 'default' }])-- t.fallbackSelectionAfterHide('ghost')-- assert.equal(t.$selectedBot.get(), 'scribe')-})--test('selection: falls back to default when nothing else is visible', () => {- const t = load()- t.$selectedBot.set('ghost')- t.$botMeta.set({ ghost: { hidden: true } })- t.$lastRoster.set([{ name: 'ghost' }])-- t.fallbackSelectionAfterHide('ghost')-- assert.equal(t.$selectedBot.get(), 'default')-})--test('selection: hiding default with nothing else visible keeps the selection (Routines must not chase a ghost)', () => {- const t = load()- t.$selectedBot.set('default')- t.$botMeta.set({ default: { hidden: true } })- t.$lastRoster.set([{ name: 'default' }])-- t.fallbackSelectionAfterHide('default')-- assert.equal(t.$selectedBot.get(), 'default')-})--test('selection: hiding an unselected bot never moves the selection', () => {- const t = load()- t.$selectedBot.set('scribe')- t.$botMeta.set({ ghost: { hidden: true } })- t.$lastRoster.set([{ name: 'ghost' }, { name: 'scribe' }])-- t.fallbackSelectionAfterHide('ghost')-- assert.equal(t.$selectedBot.get(), 'scribe')-})--test('activity: a hidden bot accumulates unread silently but never toasts, even with toasts on', () => {- const t = load({ toastsOn: true })- t.$botMeta.set({ ghost: { hidden: true } })- t.$selectedBot.set('default')-- const rosterAt = ts => [{ name: 'ghost', last_session: { last_active: ts, preview: 'Message from writer: hi' } }]- t.trackInboundActivity(rosterAt(100)) // seeding poll- t.trackInboundActivity(rosterAt(200)) // activity past the watermark-- assert.equal(t.$botUnread.get().ghost, true, 'unread must accumulate while hidden')- assert.equal(t.notifications.length, 0, 'hidden bots never toast')-})--// ── source shape ─────────────────────────────────────────────────────────────--test('shape: visible and hidden bots render through separate recoverable sections', () => {- assert.match(- pluginSource,- /const visibleRoster = roster\.filter\(bot => !isBotHidden\(bot, allMeta\)\)/- )- assert.match(pluginSource, /const matchingHiddenBots = rowKindFilter === 'groups' \? \[\] : filteredHiddenBots/)-})--test('shape: Hidden section renders only when recovery is relevant', () => {- assert.match(pluginSource, /const showHiddenSection = hiddenBots\.length > 0/)- assert.match(pluginSource, /onClick: \(\) => \$showHiddenBots\.set\(!hiddenExpanded\)/)-})--test('shape: revealed hidden rows are flagged and can be restored', () => {- const botRow = pluginSource.slice(pluginSource.indexOf('function BotRow('), pluginSource.indexOf('// ── model picker'))- assert.match(botRow, /name: 'eye-closed'/)- assert.match(botRow, /children: hidden \? 'Unhide' : 'Hide'/)- assert.match(botRow, /saveBotMeta\(bot, \{ hidden: !hidden \}\)/)-})--test('shape: hiding never filters mentions, group flows, or the meta/activity sweeps', () => {- // The full-roster consumers keep the FULL roster: mergeServerMeta,- // avatar pulls, and activity tracking all run on activeSourceRoster —- // which is derived from the unfiltered roster, not visibleRoster.- assert.match(pluginSource, /const activeSourceRoster = roster\.filter\(bot => !bot\.remoteSource\)/)- assert.match(pluginSource, /mergeServerMeta\(activeSourceRoster, data\?\.fetchedAt \|\| 0\)/)- assert.match(pluginSource, /trackInboundActivity\(roster\)/)- // Mention resolution never consults the hidden flag.- const mentions = pluginSource.slice(- pluginSource.indexOf('function resolveRosterMentions('),- pluginSource.indexOf('/** Source-qualified identity for a roster row')- )- assert.doesNotMatch(mentions, /hidden/i)-})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.mjsdeleted file mode 100644index de484a1d080..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/hub-picker-guard.test.mjs+++ /dev/null@@ -1,27 +0,0 @@-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-member-normalize.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/legacy-member-normalize.test.mjsdeleted file mode 100644index fefbbd39653..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/legacy-member-normalize.test.mjs+++ /dev/null@@ -1,138 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #92794: older builds persisted group members with a FRIENDLY name as-// `name` (e.g. `name: '大司命'` for the profile slug `taiyi`). Key matching-// alone seats such a descriptor as a ghost NEXT TO its own live roster row-// ("4 bots" in a 2-bot room — reproduced live), and any path that passes the-// ghost's identity onward targets a profile that does not exist on disk.-// resolveLegacyMemberDescriptor() re-tries an unmatched descriptor by-// friendly name against same-connection roster rows before seating.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--const NL = String.fromCharCode(10)--function stripImports(source) {- const out = []- let inImportBlock = false- for (const line of source.split(NL)) {- if (inImportBlock) {- if (line.includes(' from ')) inImportBlock = false- continue- }- if (line.startsWith('import ')) {- if (!line.includes(' from ')) inImportBlock = true- continue- }- out.push(line)- }- return out.join(NL)-}--function load({ groups, meta = {} }) {- const start = pluginSource.indexOf('function groupChatMemberBots(')- const end = pluginSource.indexOf('/** Persist source-qualified identities', start)- assert.notEqual(start, -1)- assert.notEqual(end, -1)-- const context = {- $groupChats: { get: () => groups },- $botMeta: { get: () => meta },- botGroups: m => (m && Array.isArray(m.groups) ? m.groups : []),- botRosterMeta: (bot, metaByName) => metaByName?.[bot?.name] || null,- botRosterKey: bot => `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`,- botFriendlyNames: bot => [- bot?.ui_meta?.['hermes-bots']?.title,- // localTitle: the real impl reads the Bot Mode title from $botMeta for- // local rows — mirror that so meta-titled bots resolve like production.- !bot?.remoteSource ? context.$botMeta.get()?.[bot?.name]?.title : null,- bot?.title,- bot?.display_name- ]- }- const section = stripImports(pluginSource.slice(start, end))- .concat(NL + 'globalThis.__m = { groupChatMemberBots, resolveLegacyMemberDescriptor };' + NL)- vm.runInNewContext(section, context, { filename: 'member-seat.js' })- return context.__m-}--const TAIYI = {- connectionId: 'local',- name: 'taiyi',- display_name: '大司命',- remoteSource: false-}-const TESTBOT = { connectionId: 'local', name: 'testbot', display_name: '', remoteSource: false }--test('legacy display-name descriptors seat their live row once, not as extra ghosts', () => {- const { groupChatMemberBots } = load({- groups: {- room: {- // The legacy shape: friendly names persisted as `name`.- members: [- { connectionId: 'local', name: '大司命', handle: '大司命' },- { connectionId: 'local', name: 'Testbot', handle: 'Testbot' }- ]- }- },- roster: [TAIYI, TESTBOT],- meta: {- taiyi: { groups: ['room'] },- testbot: { groups: ['room'], title: 'Testbot' }- }- })-- const seated = groupChatMemberBots('room', [TAIYI, TESTBOT], {- taiyi: { groups: ['room'] },- testbot: { groups: ['room'], title: 'Testbot' }- })-- // Two members, not four: each legacy descriptor resolved to its live row.- // (vm-realm arrays fail assert.deepEqual on prototype identity — compare- // via JSON, per the harness contract in the field notes.)- assert.equal(seated.length, 2, `seated ${seated.map(b => b.name)}`)- assert.equal(JSON.stringify(seated.map(b => b.name).sort()), JSON.stringify(['taiyi', 'testbot']))-})--test('a genuinely unknown descriptor still seats as a degraded ghost', () => {- const { groupChatMemberBots } = load({- groups: { room: { members: [{ connectionId: 'gone', name: 'vanished' }] } },- roster: [TAIYI],- meta: { taiyi: { groups: ['room'] } }- })-- const seated = groupChatMemberBots('room', [TAIYI], { taiyi: { groups: ['room'] } })- assert.equal(seated.length, 2)- assert.ok(seated.some(b => b.name === 'vanished'), 'orphan ghost preserved')-})--test('a connectionless pre-scoping descriptor resolves against local rows', () => {- // The oldest legacy shape: no connectionId at all (pre-connection-scoping- // rooms only ever held this machine's bots). Reproduced live: such ghosts- // keyed as legacy::<display-name> and doubled the seated roster.- const { resolveLegacyMemberDescriptor } = load({ groups: {}, roster: [] })- const resolved = resolveLegacyMemberDescriptor({ name: '大司命' }, [TAIYI])- assert.equal(resolved.name, 'taiyi')-})--test('friendly-name matching never crosses connections', () => {- const remoteTwin = { connectionId: 'other-box', name: 'shadow', display_name: '大司命', remoteSource: true }- const { resolveLegacyMemberDescriptor } = load({ groups: {}, roster: [] })-- const resolved = resolveLegacyMemberDescriptor(- { connectionId: 'local', name: '大司命' },- [remoteTwin]- )- // Same friendly name on ANOTHER connection must not capture the member.- assert.equal(resolved.name, '大司命')- assert.equal(resolved.connectionId, 'local')-})--test('exact slug descriptors pass through untouched', () => {- const { resolveLegacyMemberDescriptor } = load({ groups: {}, roster: [] })- const descriptor = { connectionId: 'local', name: 'taiyi', route: { targetProfile: 'taiyi' } }- assert.equal(resolveLegacyMemberDescriptor(descriptor, [TAIYI]), descriptor)-})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.mjsdeleted file mode 100644index 8add88a4f35..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/legacy-sdk-compat.test.mjs+++ /dev/null@@ -1,91 +0,0 @@-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', 'useMemo', '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-completions.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-completions.test.mjsdeleted file mode 100644index 71120fd77da..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/mention-completions.test.mjs+++ /dev/null@@ -1,146 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// The mention-completions source (#88060): typing @ offers roster handles.-// Extract the registered provide() by running plugin registration with a-// stubbed ctx/queryClient and exercising the captured contribution.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadProvide({ roster, active = 'default', focused = active, meta = {} } = {}) {- const registrations = []- const atom = value => {- let current = value-- return { get: () => current, set: next => (current = next), listen: () => () => undefined }- }- const jsx = (type, props = {}) => ({ type, props })- const context = {- atom,- jsx,- jsxs: jsx,- useQuery: () => ({}),- useValue: v => (v?.get ? v.get() : v),- useState: v => [v, () => undefined],- setTimeout,- clearTimeout,- performance,- window: {- setTimeout,- clearTimeout,- performance,- requestAnimationFrame: () => 0,- cancelAnimationFrame: () => undefined,- addEventListener: () => undefined,- removeEventListener: () => undefined- },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- queryClient: {- // Key-exact semantics like the real QueryClient (v5): a 2-element- // ROSTER_KEY lookup MUST miss the 3-element cache keys useRoster- // writes — the bug behind issue #89303 was invisible under the old- // key-ignoring mock.- getQueryData: key =>- key.length === 3 && key[0] === 'hermes-bots' && key[1] === 'roster'- ? roster- : undefined,- getQueriesData: () => (Array.isArray(roster?.profiles) ? [[['hermes-bots', 'roster', 'local'], roster]] : []),- invalidateQueries: () => undefined,- setQueryData: () => undefined- },- host: {- state: {- profile: { get: () => active, listen: () => () => undefined },- focusedSessionProfile: { get: () => focused, listen: () => () => undefined },- gateway: { get: () => null, listen: () => () => undefined },- connectionId: { get: () => 'local', listen: () => () => undefined }- },- request: async () => ({}),- onEvent: () => () => undefined- },- COMPOSER_AREAS: { middleware: 'composer.middleware', atCompletions: 'composer.atCompletions' },- sdk: new Proxy({}, { get: () => undefined })- }- const code = source- .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('\nglobalThis.__botMeta = $botMeta;')- vm.runInNewContext(code, context)- context.__botMeta.set(meta)-- const ctx = {- register: c => registrations.push(c),- storage: { get: async () => undefined, set: async () => undefined }- }-- try {- context.plugin.register(ctx)- } catch {- /* registration walks UI surfaces the stub doesn't fully model — the- contributions registered before any throw are what we assert on */- }-- const contribution = registrations.find(c => c.area === 'composer.atCompletions')- assert.ok(contribution, 'mention-completions contribution registered')-- return contribution.data.provide-}--const ROSTER = {- profiles: [- { name: 'default' },- { name: 'researcher' },- { name: 'writer', connectionLabel: 'Homelab', handle: 'writer-homelab' }- ]-}--test('offers roster handles for a matching prefix, excluding the active profile', () => {- const provide = loadProvide({ roster: ROSTER, active: 'researcher' })- const all = provide('')- const inserts = all.map(i => i.insert)-- assert.ok(inserts.includes('@hermes'), 'default surfaces as @hermes')- assert.ok(inserts.includes('@writer-homelab'), 'multi-source handle used')- assert.ok(!inserts.includes('@researcher'), 'active profile excluded')-})--test('prefix-filters against the handle', () => {- const provide = loadProvide({ roster: ROSTER, active: 'default' })-- assert.deepStrictEqual([...provide('wri').map(i => i.insert)], ['@writer-homelab'])- assert.strictEqual(provide('zzz').length, 0)-})--test('filters self by the focused Bot Chat owner, not the gateway socket profile', () => {- const provide = loadProvide({- active: 'default',- focused: 'renametest',- roster: {- profiles: [- { name: 'default', display_name: 'Lucy' },- { name: 'renametest' }- ]- }- })-- const inserts = provide('').map(item => item.insert)- assert.ok(- inserts.includes('@lucy'),- 'renamed default profile remains mentionable from the focused bot chat'- )- assert.ok(- !inserts.includes('@renametest'),- 'focused bot excludes itself even when the socket stays on default'- )-})--test('empty roster cache yields no rows (never throws)', () => {- const provide = loadProvide({ roster: undefined })-- assert.strictEqual(provide('a').length, 0)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-identification.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-identification.test.mjsdeleted file mode 100644index f3baf159640..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/mention-identification.test.mjs+++ /dev/null@@ -1,155 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// The @mention middleware is IDENTIFICATION-ONLY (Aug 2026 redesign): it-// resolves the user's @tags against the live roster and annotates the draft-// with who they refer to. It never delivers anything — the agent owns-// messaging via its Bot-Chat message_agent tool, so there is exactly one-// send path, no renderer-side shellout instructions, and no verbatim-// forwarding of the user's text (the class behind #91397/#91304/#91339).--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function load({- activeProfile = 'research',- focusedProfile = activeProfile,- profiles = ['research', 'ops'],- title = null,- unionProfiles = null,- requestProfileSpy = 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(profile =>- typeof profile === 'string' ? { name: profile } : profile- )- }- }- return {}- },- ...(requestProfileSpy ? { requestProfile: requestProfileSpy } : {}),- state: {- profile: { get: () => activeProfile, listen: () => undefined },- focusedSessionProfile: { get: () => focusedProfile, listen: () => undefined },- connectionId: { get: () => 'local', listen: () => undefined },- gateway: { listen: () => undefined }- }- },- ...(unionProfiles- ? { queryClient: { getQueryData: () => ({ profiles: unionProfiles }) } }- : {})- }- 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 }-}--test('identification: a local mention annotates who the user means', async () => {- const { handler } = load()- const result = await handler({ text: 'please @ops review the diff' })- assert.match(result.text, /@mentions resolved from the Bot Mode roster/)- assert.match(result.text, /@ops = agent profile "ops"/)- assert.match(result.text, /message_agent/)-})--test('containment: the note never teaches a shellout and never forwards a command', async () => {- const { handler } = load()- const result = await handler({ text: 'ask @ops to summarize' })- assert.doesNotMatch(result.text, /hermes -p/)- assert.doesNotMatch(result.text, /terminal call/i)- assert.doesNotMatch(result.text, /background=true/)-})--test('containment: the note tells the agent to compose, never forward verbatim', async () => {- const { handler } = load()- const result = await handler({ text: '@ops handle this' })- assert.match(result.text, /compose your own message/i)- assert.match(result.text, /never forward/i)-})--test('security: a poisoned bot title stays inert prose (no shell context exists)', async () => {- const title = 'Evil" ; touch /tmp/pwned ; echo "$(touch /tmp/pwned2)"'- const { handler } = load({- activeProfile: 'ops',- focusedProfile: 'ops',- profiles: [{ name: 'ops' }, { name: 'research', display_name: title }]- })- const result = await handler({ text: 'ping @research please' })- // The note is plain prose fed to the model — there is no command to break- // out of. The only invariant left: no hermes command is ever emitted.- assert.doesNotMatch(result.text, /`hermes/)-})--test('remote mentions: identified with their device, never delivered by the renderer', async () => {- const delivered = []- const { handler } = load({- activeProfile: 'default',- focusedProfile: 'default',- unionProfiles: [- { name: 'default', connectionId: 'local' },- {- name: 'dixie',- connectionId: 'mac-mini',- connectionLabel: 'Mac Mini',- handle: 'dixie',- remoteSource: true- }- ],- requestProfileSpy: async (...args) => {- delivered.push(args)- return {}- }- })-- const result = await handler({ text: '@dixie what is the disk space?' })- assert.match(result.text, /@dixie = agent profile "dixie"/)- assert.match(result.text, /on Mac Mini/)- // The renderer must NOT deliver: no requestProfile traffic at all.- await new Promise(resolve => setTimeout(resolve, 50))- assert.equal(delivered.length, 0, 'middleware must never deliver over Connections')-})--test('unknown @ and emails pass through untouched', async () => {- const { handler } = load()- const untouched = 'mail [email protected] and ping @nosuchbot'- const result = await handler({ text: untouched })- assert.equal(result.text, untouched)-})--test('source contract: the delivery machinery is gone from plugin.js', () => {- assert.doesNotMatch(pluginSource, /deliverRemoteRosterMentions/)- assert.doesNotMatch(pluginSource, /pollRemoteDmReply/)- assert.doesNotMatch(pluginSource, /ensureRemoteCanonicalChat/)- assert.doesNotMatch(pluginSource, /REMOTE_DM_TIMEOUT_MS/)- // The middleware must not know how to build a bot-to-bot hermes command.- assert.doesNotMatch(pluginSource, /\[@mention handoff/)- assert.doesNotMatch(pluginSource, /Desktop is delivering/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-renamed-bots.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-renamed-bots.test.mjsdeleted file mode 100644index afa10e47462..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/mention-renamed-bots.test.mjs+++ /dev/null@@ -1,188 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Renamed bots stay taggable (Discord report, Aug 2026): renaming a bot —-// Bot Mode title or `hermes profile rename` display_name — must update what-// the user can @-tag it with, in the mention middleware, group rooms, and-// the composer autocomplete. Old profile handles keep resolving.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function runtime({ meta } = {}) {- const context = {- console,- setTimeout,- clearTimeout,- Date,- URL,- atom: initial => {- let value = initial- return { get: () => value, set: next => (value = next), listen: () => () => undefined }- },- host: {- request: async () => ({}),- requestProfile: async () => ({}),- state: {- profile: { get: () => 'default', listen: () => undefined },- connectionId: { get: () => 'local', listen: () => undefined },- gateway: { listen: () => 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.__x = { mentionNameForms, botFriendlyNames, botMentionTag, resolveRosterMentions, parseGroupChatMentions, groupMemberKey, durableGroupChatMembers, $botMeta };\n'- )- vm.runInNewContext(code, context, { filename: 'plugin.js' })- if (meta) {- context.__x.$botMeta.set(meta)- }- return context.__x-}--test('mentionNameForms: slugged + collapsed, reserved tokens dropped', () => {- const { mentionNameForms } = runtime()-- assert.deepEqual(JSON.parse(JSON.stringify(mentionNameForms('Research Buddy'))), ['research-buddy', 'researchbuddy'])- assert.deepEqual(JSON.parse(JSON.stringify(mentionNameForms('Ops'))), ['ops'])- // A bot renamed "Hermes" or "everyone" cannot hijack reserved tags.- assert.equal(mentionNameForms('Hermes').length, 0)- assert.equal(mentionNameForms('@everyone').length, 0)- assert.equal(mentionNameForms('').length, 0)-})--test('botMentionTag: renamed slug wins, profile handle is the fallback', () => {- const { botMentionTag } = runtime({ meta: { writer: { title: 'Research Buddy' } } })-- assert.equal(botMentionTag({ name: 'writer' }), 'research-buddy')- assert.equal(botMentionTag({ name: 'ops' }), 'ops')- assert.equal(botMentionTag({ name: 'default' }), 'hermes')- // display_name (hermes profile rename) drives the tag too.- assert.equal(botMentionTag({ name: 'scout', display_name: 'Deal Finder' }), 'deal-finder')-})--test('resolveRosterMentions: renamed bots resolve by friendly tag AND old handle', () => {- const { resolveRosterMentions } = runtime({ meta: { writer: { title: 'Research Buddy' } } })- const roster = [{ name: 'default' }, { name: 'writer' }, { name: 'scout', display_name: 'Deal Finder' }]- const live = { name: 'default', connectionId: 'local' }-- const byTitle = resolveRosterMentions('hey @research-buddy check this', roster, live)- assert.deepEqual(JSON.parse(JSON.stringify(byTitle.map(b => b.name))), ['writer'])-- const byDisplayName = resolveRosterMentions('ping @dealfinder please', roster, live)- assert.deepEqual(JSON.parse(JSON.stringify(byDisplayName.map(b => b.name))), ['scout'])-- // The profile name keeps working after a rename.- const byName = resolveRosterMentions('hey @writer', roster, live)- assert.deepEqual(JSON.parse(JSON.stringify(byName.map(b => b.name))), ['writer'])-})--test('parseGroupChatMentions: display_name and ui_meta title forms address a member', () => {- const { parseGroupChatMentions, groupMemberKey } = runtime()- const members = [- { name: 'research', title: '' },- { name: 'builder', title: '', display_name: 'Site Smith' },- { name: 'ops', title: '', ui_meta: { 'hermes-bots': { title: 'Night Watch' } } }- ]-- const bySlug = parseGroupChatMentions('@site-smith and @night-watch please', members)- assert.equal(bySlug.mentioned.has(groupMemberKey(members[1])), true)- assert.equal(bySlug.mentioned.has(groupMemberKey(members[2])), true)- assert.equal(bySlug.mentioned.has(groupMemberKey(members[0])), false)-- const collapsed = parseGroupChatMentions('@sitesmith take a look', members)- assert.equal(collapsed.mentioned.has(groupMemberKey(members[1])), true)-})--test('durableGroupChatMembers persists the friendly identity for renamed-tag mentions', () => {- const { durableGroupChatMembers, $botMeta } = runtime()- $botMeta.set({ writer: { title: 'Research Buddy' } })-- const [stored] = durableGroupChatMembers([{ name: 'writer', connectionId: 'local' }])- assert.equal(stored.title, 'Research Buddy')-- const [remote] = durableGroupChatMembers([- { name: 'scout', display_name: 'Deal Finder', connectionId: 'mac-mini', remoteSource: true }- ])- assert.equal(remote.display_name, 'Deal Finder')-})--test('composer autocomplete offers the renamed tag and matches on the display name', () => {- const registrations = []- const atom = value => {- let current = value- return { get: () => current, set: next => (current = next), listen: () => () => undefined }- }- const jsx = (type, props = {}) => ({ type, props })- const roster = { profiles: [{ name: 'default' }, { name: 'writer' }, { name: 'ops' }] }- const context = {- atom,- jsx,- jsxs: jsx,- useQuery: () => ({}),- useValue: v => (v?.get ? v.get() : v),- useState: v => [v, () => undefined],- setTimeout,- clearTimeout,- performance,- window: {- setTimeout,- clearTimeout,- performance,- requestAnimationFrame: () => 0,- cancelAnimationFrame: () => undefined,- addEventListener: () => undefined,- removeEventListener: () => undefined- },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- queryClient: { getQueryData: () => roster, invalidateQueries: () => undefined, setQueryData: () => undefined },- host: {- state: { profile: { get: () => 'default', listen: () => () => undefined }, gateway: { get: () => null, listen: () => () => undefined } },- request: async () => ({}),- onEvent: () => () => undefined- },- COMPOSER_AREAS: { middleware: 'composer.middleware', atCompletions: 'composer.atCompletions' },- sdk: new Proxy({}, { get: () => undefined })- }- const code = source- .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('\nglobalThis.__botMeta = $botMeta;')- vm.runInNewContext(code, context)- context.__botMeta.set({ writer: { title: 'Research Buddy' } })-- try {- context.plugin.register({- register: c => registrations.push(c),- storage: { get: async () => undefined, set: async () => undefined }- })- } catch {- /* registration walks UI surfaces the stub doesn't fully model */- }-- const provide = registrations.find(c => c.area === 'composer.atCompletions').data.provide-- // The renamed bot completes under its friendly prefix and inserts the tag.- const renamed = provide('rese')- assert.deepEqual(JSON.parse(JSON.stringify(renamed.map(i => i.insert))), ['@research-buddy'])-- // Old profile-handle muscle memory still finds it (insert is the new tag).- const byHandle = provide('wri')- assert.deepEqual(JSON.parse(JSON.stringify(byHandle.map(i => i.insert))), ['@research-buddy'])-- // Un-renamed bots keep their plain handle.- const plain = provide('op')- assert.deepEqual(JSON.parse(JSON.stringify(plain.map(i => i.insert))), ['@ops'])-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-roster-cache-key.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-roster-cache-key.test.mjsdeleted file mode 100644index b76bd18e88f..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/mention-roster-cache-key.test.mjs+++ /dev/null@@ -1,208 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// useRoster() keys its query on [...ROSTER_KEY, connectionId] — one cache-// entry per connection the window has been on. The imperative roster readers-// (the @mention completions and the mention middleware) used to call-// getQueryData(ROSTER_KEY) with the BARE key, which is an exact-key match in-// TanStack Query and therefore matched NOTHING: completions offered no-// roster handles and remote @name-device mentions passed through the-// middleware unhandled (the local profiles.list fallback only knows bare-// local names). Reproduced on a two-source install where the same profile-// name exists locally and on an SSH connection ("Vera"): typing-// `@default-vera` did nothing. These tests model the REAL cache semantics —-// entries stored under the suffixed key, exact-key reads missing them,-// prefix reads finding them — so the key-shape regression is pinned.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--/** Faithful-enough TanStack Query v5 cache: getQueryData matches ONLY the- * exact key, getQueriesData prefix-matches a key family. */-function makeQueryClient() {- const entries = new Map()- const keyOf = key => JSON.stringify(key)-- return {- setQueryData: (key, value) => {- entries.set(keyOf(key), { key, value })- },- getQueryData: key => entries.get(keyOf(key))?.value,- getQueriesData: ({ queryKey }) =>- [...entries.values()]- .filter(({ key }) => queryKey.every((part, index) => key[index] === part))- .map(({ key, value }) => [key, value]),- invalidateQueries: () => undefined- }-}--// One profile name on two sources: locally and on the SSH connection "vera".-// The union roster disambiguates the remote row as @default-vera.-const ROSTER = {- profiles: [- { name: 'default', connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device' },- {- name: 'default',- handle: 'default-vera',- connectionId: 'vera',- connectionKind: 'ssh',- connectionLabel: 'Vera',- remoteSource: true,- sourceScoped: true- }- ]-}--function load({ cacheKeyConnection = 'local' } = {}) {- const registrations = []- const delivered = []- let submitted = false- const atom = value => {- let current = value-- return { get: () => current, set: next => (current = next), listen: () => () => undefined }- }- const jsx = (type, props = {}) => ({ type, props })- const queryClient = makeQueryClient()-- // Exactly where useRoster writes it: suffixed with the connection id.- queryClient.setQueryData(['hermes-bots', 'roster', cacheKeyConnection], ROSTER)-- const context = {- atom,- jsx,- jsxs: jsx,- useQuery: () => ({}),- useValue: v => (v?.get ? v.get() : v),- useState: v => [v, () => undefined],- setTimeout,- clearTimeout,- performance,- window: {- setTimeout,- clearTimeout,- performance,- requestAnimationFrame: () => 0,- cancelAnimationFrame: () => undefined,- addEventListener: () => undefined,- removeEventListener: () => undefined- },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- queryClient,- host: {- state: {- profile: { get: () => 'default', listen: () => () => undefined },- connectionId: { get: () => 'local', listen: () => () => undefined },- gateway: { get: () => null, listen: () => () => undefined }- },- request: async () => ({}),- requestProfile: async (route, method, params) => {- delivered.push([route?.connectionId, route?.profile, method])-- if (method === 'profiles.list') {- return {- profiles: [{ name: 'default', ui_meta: { 'hermes-bots': { chat: 'remote-pin' } } }]- }- }-- if (method === 'session.resume') {- if (params?.omit_messages) {- return { session_id: 'remote-1', session_key: 'remote-pin' }- }-- // Baseline read before the submit, then the reply poll after it:- // once the submit happened, hand back an assistant message so the- // bounded reply poll terminates on its first pass (~2s) instead of- // idling until the 180s timeout.- if (!submitted) {- return { messages: [] }- }-- return {- messages: [- { role: 'user', content: 'ping' },- { role: 'assistant', content: 'first' },- { role: 'assistant', content: 'ok' }- ]- }- }-- if (method === 'prompt.submit') {- submitted = true- }-- return {}- },- onEvent: () => () => undefined- },- COMPOSER_AREAS: { middleware: 'composer.middleware', atCompletions: 'composer.atCompletions' },- PALETTE_AREA: 'palette',- sdk: new Proxy({}, { get: () => undefined })- }- const code = 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('\nglobalThis.__botMeta = $botMeta;')- vm.runInNewContext(code, context)- context.__botMeta.set({})-- const ctx = {- register: c => registrations.push(c),- storage: { get: async () => undefined, set: async () => undefined }- }-- try {- context.plugin.register(ctx)- } catch {- /* registration walks UI surfaces the stub doesn't fully model — the- contributions registered before any throw are what we assert on */- }-- const completions = registrations.find(c => c.id === 'mention-completions')- const middleware = registrations.find(c => c.id === 'mention-middleware')- assert.ok(completions, 'mention-completions contribution registered')- assert.ok(middleware, 'mention middleware registered')-- return { provide: completions.data.provide, handler: middleware.data.handler, delivered, queryClient }-}--test('the roster cache entry lives under the connection-suffixed key, invisible to the bare-key read', () => {- // Documents the regression's shape: the entry useRoster writes is NOT- // reachable through an exact getQueryData(ROSTER_KEY).- const { queryClient } = load()-- assert.equal(queryClient.getQueryData(['hermes-bots', 'roster']), undefined)- assert.equal(queryClient.getQueriesData({ queryKey: ['hermes-bots', 'roster'] }).length, 1)-})--test('mention completions offer remote @name-device handles from the suffixed cache entry', () => {- const { provide } = load()- const inserts = provide('').map(item => item.insert)-- assert.ok(inserts.includes('@default-vera'), `expected @default-vera in ${JSON.stringify(inserts)}`)-})--test('the middleware identifies a remote @name-device mention without delivering (identification-only)', async () => {- const { handler, delivered } = load()- const result = await handler({ text: '@default-vera what is the disk space on the server?' })-- assert.match(result.text, /@mentions resolved from the Bot Mode roster/)- assert.match(result.text, /@default-vera/)- // No CLI handoff is composed and the renderer performs NO delivery — the- // agent owns messaging via its message_agent tool.- assert.doesNotMatch(result.text, /hermes -p '?default/)- await new Promise(resolve => setTimeout(resolve, 0))- assert.equal(delivered.length, 0, 'middleware must not deliver over Connections')-})--test('a roster cached under another connection id still resolves (fallback entry)', () => {- // The window moved connections; the stale entry is the only one cached.- const { provide } = load({ cacheKeyConnection: 'vera' })- const inserts = provide('').map(item => item.insert)-- assert.ok(inserts.includes('@default-vera'), `expected @default-vera in ${JSON.stringify(inserts)}`)-})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.mjsdeleted file mode 100644index 1e539cdd543..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/model-inherit.test.mjs+++ /dev/null@@ -1,96 +0,0 @@-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 },- requestForBot: (_bot, method, params) => request(method, params),- 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({ name: '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({ name: '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({ name: '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/model-picker-settle.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/model-picker-settle.test.mjsdeleted file mode 100644index 95949339ad9..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/model-picker-settle.test.mjs+++ /dev/null@@ -1,175 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #95279 regression: the Bot Mode model picker's catalog read must always-// SETTLE and must not churn the network on every surface remount.-//-// The picker's query rides the BOT's own socket (a second, lazily dialed pool-// backend — exactly the Bots-only context of #95279). Two defects there left-// the picker unusable while Bots was active:-//-// 1. The RPC promise had NO deadline. A wedged dial left it pending forever-// → the spinner never settled and the picker was dead ("model picker-// never settles").-// 2. Every fetch forced `refresh: true`, bypassing react-query's cache, so-// each Bots view remount (tab re-front, dialog reopen, pane visibility-// flip) knocked the picker back into its loading state and discarded the-// staged selection mid-edit.-//-// These tests pin the contract: bounded settlement (reject → free-text-// fallback) and a cached, unforced catalog read.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadPickerHarness({ requestProfile } = {}) {- const values = new Map()- const atom = initial => {- const slot = {- get: () => values.get(slot),- set: value => values.set(slot, value),- listen: () => undefined- }- values.set(slot, initial)- return slot- }- const jsx = (type, props = {}) => ({ type, props })- const routed = []- let query- const stateValues = [true, false, '']- const context = {- atom,- Checkbox: 'Checkbox',- GlyphSpinner: 'GlyphSpinner',- Input: 'Input',- ScrollArea: 'ScrollArea',- Textarea: 'Textarea',- document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },- host: {- getGateway: () => 'ambient-gateway',- requestProfile: async (...args) => {- routed.push(args)-- return requestProfile ? requestProfile(...args) : new Promise(() => {})- },- request: async (...args) => {- routed.push(['ambient', ...args])-- return requestProfile ? requestProfile(...args) : new Promise(() => {})- },- state: {- gateway: { get: () => 'open', listen: () => undefined },- profile: { get: () => 'default', listen: () => undefined }- }- },- jsx,- jsxs: jsx,- queryClient: { invalidateQueries: () => undefined },- sdk: {},- useQuery: options => {- query = options-- return { data: undefined, isLoading: false, error: null }- },- useState: initial => [stateValues.length ? stateValues.shift() : initial, () => undefined],- window: { setTimeout, clearTimeout }- }- 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(/^import .* from 'react'\r?\n/m, '')- .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')- .replace('export default {', 'globalThis.plugin = {')- .concat('\nglobalThis.__useModelOptions = useModelOptions;')- vm.runInNewContext(code, context, { filename: 'plugin.js' })-- return { context, query: () => query, routed }-}--const remoteBot = {- connectionId: 'remote-a',- name: 'default',- remoteSource: true,- route: {- connectionId: 'remote-a',- mode: 'remote',- profile: 'default',- targetProfile: 'backend-default'- },- sourceScoped: true,- targetProfile: 'backend-default'-}--test('#95279: the picker catalog query settles when the bot gateway never answers', async t => {- // Fake clocks: tick past the settle budget without waiting real time. The- // harness captured the mocked setTimeout above (enable runs first).- t.mock.timers.enable({ apis: ['setTimeout'] })-- const runtime = loadPickerHarness({ requestProfile: () => new Promise(() => {}) })- runtime.context.__useModelOptions(remoteBot)- const query = runtime.query()-- assert.equal(typeof query.queryFn, 'function')-- let settled = false-- query.queryFn().then(- () => {- settled = 'resolved'- },- () => {- settled = 'rejected'- }- )-- // Past the settle budget the bounded fetch must have rejected (the picker- // then renders its free-text fallback). A macrotask boundary drains every- // microtask hop of the rejection chain before we look.- t.mock.timers.tick(30_000)- await new Promise(resolve => setImmediate(resolve))-- assert.equal(settled, 'rejected')-})--test('#95279: the picker catalog read is cached, not force-refreshed on every mount', async () => {- const runtime = loadPickerHarness({- requestProfile: async () => ({ providers: [{ models: ['m1'], name: 'Prov', slug: 'prov' }] })- })- runtime.context.__useModelOptions(remoteBot)- const query = runtime.query()-- // Same bot + route ⇒ one stable cache key, so Bots view remounts reuse the- // fetched catalog instead of knocking the picker back into its spinner.- assert.deepEqual(query.queryKey[1], 'model-options')- assert.deepEqual(query.queryKey[2], 'remote-a::default')-- const data = await query.queryFn()-- assert.deepEqual(JSON.parse(JSON.stringify(data)), {- providers: [{ models: ['m1'], name: 'Prov', slug: 'prov' }]- })-- // No forced refresh: the read participates in the staleTime cache. A forced- // refresh here is what made every remount re-enter the loading state and- // wipe the user's in-progress pick (#95279).- assert.deepEqual(JSON.parse(JSON.stringify(runtime.routed)), [- [remoteBot.route, 'model.options', { include_unconfigured: true, explicit_only: false }]- ])-})--test('#95279: picker query stays disabled for orphaned rows and keyed active for local bots', () => {- const runtime = loadPickerHarness()-- // An orphaned row must not dispatch at all (renders free-text fallback).- runtime.context.__useModelOptions({ name: 'ghost', remoteSource: true })- const orphanQuery = runtime.query()- assert.equal(orphanQuery.enabled, false)-- // A local (non source-scoped) bot reads the ambient gateway under the- // stable 'active' key.- runtime.context.__useModelOptions({ name: 'default' })- const localQuery = runtime.query()- assert.equal(localQuery.enabled, true)- assert.deepEqual(localQuery.queryKey[2], 'active')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/model-switch-confirm.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/model-switch-confirm.test.mjsdeleted file mode 100644index 1ae57f0966d..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/model-switch-confirm.test.mjs+++ /dev/null@@ -1,188 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #95293 remainder: a GUARDED model switch made from the Bots surface must-// surface the SAME confirm flow the core picker uses, then resend with-// `confirm_expensive_model: true` once the user confirms.-//-// The Bots editor's switch path is `applyAdvancedConfig` → `profiles.configure`-// (it does NOT route through use-model-controls). The gateway now answers-// `confirm_required` + `confirm_message` for guarded picks on this surface too-// (same handshake as `config.set model`); the plugin must:-//-// 1. route that response through the shared confirm handler-// (`surfaceModelSwitchConfirm` from the plugin SDK — one applier, no-// forked confirm logic per surface),-// 2. NOT count the pending model section as a failed section, and-// 3. resend ONLY the model section with `confirm_expensive_model: true`-// when the user clicks Confirm.-//-// Pre-fix, the confirm_required response matched no branch: the pick silently-// dropped (no confirm, no resend) — exactly issue #95293 on the Bots surface.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadHarness({ request }) {- const values = new Map()- const atom = initial => {- const slot = {- get: () => values.get(slot),- set: value => values.set(slot, value),- listen: () => undefined- }- values.set(slot, initial)- return slot- }- const jsx = (type, props = {}) => ({ type, props })- const routed = []- const confirms = []- const invalidated = []- const context = {- atom,- Checkbox: 'Checkbox',- GlyphSpinner: 'GlyphSpinner',- Input: 'Input',- ScrollArea: 'ScrollArea',- Textarea: 'Textarea',- document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },- host: {- getGateway: () => 'ambient-gateway',- request: async (method, params) => {- routed.push([method, params])-- return request(method, params)- },- requestProfile: async (route, method, params) => {- routed.push([method, params])-- return request(method, params)- },- state: {- gateway: { get: () => 'open', listen: () => undefined },- profile: { get: () => 'default', listen: () => undefined }- }- },- jsx,- jsxs: jsx,- queryClient: { invalidateQueries: key => invalidated.push(key) },- sdk: {},- // The shared confirm handler the core picker uses, exported through the- // plugin SDK. The stub records the options so the test can drive the- // Confirm action exactly like a user click would.- surfaceModelSwitchConfirm: options => {- confirms.push(options)-- return 'notification-1'- },- useQuery: () => ({ data: undefined, isLoading: false, error: null }),- useState: initial => [initial, () => undefined],- window: { setTimeout, clearTimeout }- }- 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(/^import .* from 'react'\r?\n/m, '')- .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')- .replace('export default {', 'globalThis.plugin = {')- .concat('\nglobalThis.__applyAdvancedConfig = applyAdvancedConfig;')- vm.runInNewContext(code, context, { filename: 'plugin.js' })-- return { applyAdvancedConfig: context.__applyAdvancedConfig, confirms, invalidated, routed }-}--const bot = { name: 'zeta' }--const dirtyModelState = {- loaded: true,- provider: 'opencode-go',- model: 'muse-spark-1.2-contributor',- soul: '',- skills: [],- toolsets: [],- mcp: [],- dirtyModel: true,- dirtySoul: false,- dirtySkills: false,- dirtyToolsets: false,- dirtyMcp: false-}--test('guarded Bots-mode switch surfaces the shared confirm flow instead of silently dropping', async () => {- const { applyAdvancedConfig, confirms, routed } = loadHarness({- request: async () => ({- ok: true,- applied: {},- confirm_required: true,- confirm_message: 'CONTRIBUTOR TIER: this model may train on your data.'- })- })-- const res = await applyAdvancedConfig(bot, { ...dirtyModelState })-- // The first request is the normal (unconfirmed) configure call.- assert.equal(routed.length, 1)- assert.equal(routed[0][0], 'profiles.configure')- assert.equal(routed[0][1].model, 'muse-spark-1.2-contributor')- assert.ok(!routed[0][1].confirm_expensive_model, 'first attempt must NOT pre-confirm')-- // The confirm flow was surfaced through the SHARED handler with the- // gateway's message — not swallowed, not a forked local dialog.- assert.equal(confirms.length, 1, 'confirm_required must surface the shared confirm handler')- assert.match(String(confirms[0].confirmMessage || ''), /CONTRIBUTOR TIER/)-- // Pending-confirmation is NOT a failed section: the editor must not toast- // "Some sections failed: model" while the confirm toast is up.- assert.notEqual(res?.applied?.model, false)- assert.equal(res?.ok, true)-})--test('Confirm resends ONLY the model section with confirm_expensive_model: true', async () => {- let calls = 0- const { applyAdvancedConfig, confirms, routed } = loadHarness({- request: async () => {- calls += 1-- if (calls === 1) {- return { ok: true, applied: {}, confirm_required: true, confirm_message: 'guarded' }- }-- return { ok: true, applied: { model: true } }- }- })-- await applyAdvancedConfig(bot, { ...dirtyModelState })- assert.equal(confirms.length, 1)-- // Drive the confirmed resend exactly as the shared handler's Confirm- // action does.- const confirmed = await confirms[0].requestConfirmed()-- assert.equal(routed.length, 2)- const [method, params] = routed[1]- assert.equal(method, 'profiles.configure')- assert.equal(params.confirm_expensive_model, true)- assert.equal(params.model, 'muse-spark-1.2-contributor')- assert.equal(params.provider, 'opencode-go')- assert.equal(params.name, 'zeta')- // Only the model section rides the resend — no soul/skills/toolsets replay.- assert.deepEqual(- Object.keys(params).sort(),- ['confirm_expensive_model', 'model', 'name', 'provider']- )- assert.equal(confirmed?.applied?.model, true)-})--test('unguarded saves keep the existing single-shot behavior', async () => {- const { applyAdvancedConfig, confirms, routed } = loadHarness({- request: async () => ({ ok: true, applied: { model: true } })- })-- const res = await applyAdvancedConfig(bot, { ...dirtyModelState })-- assert.equal(routed.length, 1)- assert.equal(confirms.length, 0)- assert.equal(res?.ok, true)- assert.equal(res?.applied?.model, true)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjsdeleted file mode 100644index 0d34889773d..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/multi-source-roster.test.mjs+++ /dev/null@@ -1,868 +0,0 @@-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: {- connectionId: { get: () => 'local', listen: () => undefined },- profile: { get: () => 'ops', listen: () => undefined }- },- request: () => undefined- },- sdk: new Proxy({}, { get: () => undefined })- }- const code = source- .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(- '\nglobalThis.__mergeMultiSourceRoster = mergeMultiSourceRoster;\nglobalThis.__botHandle = botHandle;\nglobalThis.__botRosterKey = botRosterKey;\nglobalThis.__botRosterMeta = botRosterMeta;\nglobalThis.__displayName = displayName;\nglobalThis.__filterBots = filterBots;\nglobalThis.__resolveRosterMentions = resolveRosterMentions;\nglobalThis.__botConnectionRoute = botConnectionRoute;\nglobalThis.__resolveBotConnectionRoute = resolveBotConnectionRoute;\nglobalThis.__preferReachableSameNameRows = preferReachableSameNameRows;'- )- vm.runInNewContext(code, context)- return context-}--test('merge: no union → local list untouched', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = { profiles: [{ name: 'default', last_session: { id: 's1' } }] }-- const out = merge(local, { agents: [] })- assert.equal(out.profiles.length, 1)- assert.equal(out.profiles[0].name, 'default')- assert.equal(out.profiles[0].last_session.id, 's1')-})--test('merge: local rows are annotated, remote rows appended with source tags', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = { profiles: [{ name: 'research', last_session: { id: 's1' } }] }- const union = {- agents: [- {- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- profile: 'research',- handle: 'research-this-device'- },- {- connectionId: 'homelab',- connectionKind: 'remote',- connectionLabel: 'Homelab',- profile: 'research',- handle: 'research-homelab'- },- {- connectionId: 'homelab',- connectionKind: 'remote',- connectionLabel: 'Homelab',- profile: 'coder',- handle: 'coder'- }- ]- }-- const out = merge(local, union, 'local')- assert.equal(out.profiles.length, 3)-- const localRow = out.profiles.find(p => p.name === 'research' && !p.remoteSource)- // Annotated in place — rich fields survive, handle attached.- assert.equal(localRow.last_session.id, 's1')- assert.equal(localRow.handle, 'research-this-device')- assert.equal(localRow.sourceScoped, true)- assert.equal(localRow.remoteSource, undefined)-- const remoteRow = out.profiles.find(p => p.name === 'research' && p.remoteSource)- assert.equal(remoteRow.handle, 'research-homelab')- assert.equal(remoteRow.connectionId, 'homelab')- assert.equal(remoteRow.connectionLabel, 'Homelab')-- const coder = out.profiles.find(p => p.name === 'coder')- assert.equal(coder.remoteSource, true)- assert.equal(coder.handle, 'coder')-})--test('merge: union-only active profiles are NOT invented as thin rows', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = { profiles: [{ name: 'default' }] }- const union = {- agents: [- {- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- profile: 'ghost',- handle: 'ghost'- }- ]- }-- const out = merge(local, union, 'local')- assert.equal(out.profiles.length, 1)- assert.equal(out.profiles[0].name, 'default')-})--test('merge: duplicate source and local identities render once', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = {- profiles: [- { name: 'default', last_session: { id: 'newest' } },- { name: 'default', last_session: { id: 'stale' } }- ]- }- const union = {- agents: [- { connectionId: 'local', connectionKind: 'local', profile: 'default', handle: 'default-this-device' },- { connectionId: 'local', connectionKind: 'local', profile: 'default', handle: 'default-this-device' },- {- connectionId: 'homelab',- connectionKind: 'remote',- connectionLabel: 'Homelab',- profile: 'default',- handle: 'default-homelab'- },- {- connectionId: 'homelab',- connectionKind: 'remote',- connectionLabel: 'Homelab',- profile: 'default',- handle: 'default-homelab'- }- ]- }-- const out = merge(local, union, 'local')-- assert.equal(out.profiles.length, 2)- assert.equal(out.profiles[0].last_session.id, 'newest')- assert.equal(out.profiles[0].handle, 'default-this-device')- assert.equal(out.profiles[1].connectionId, 'homelab')-})--test('merge: rich rows follow the active remote source, not the local source', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const active = { profiles: [{ name: 'default', last_session: { id: 'remote-session' } }] }- const union = {- agents: [- {- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- profile: 'default',- handle: 'default-this-device'- },- {- connectionId: 'work',- connectionKind: 'remote',- connectionLabel: 'Work',- profile: 'default',- handle: 'default-work'- }- ]- }-- const out = merge(active, union, 'work')- const remote = out.profiles.find(p => p.connectionId === 'work')- const local = out.profiles.find(p => p.connectionId === 'local')-- assert.equal(remote.last_session.id, 'remote-session')- assert.equal(remote.sourceScoped, true)- assert.equal(remote.remoteSource, undefined)- assert.equal(local.remoteSource, true)- assert.equal(local.sourceScoped, true)-})--test('merge: repeated refreshes stay idempotent and do not mutate gateway rows', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const rich = { name: 'default', last_session: { id: 'remote-session' } }- const local = { profiles: [rich, rich] }- const union = {- agents: [- {- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- profile: 'default',- handle: 'default-this-device'- },- {- connectionId: 'work',- connectionKind: 'remote',- connectionLabel: 'Work',- profile: 'default',- handle: 'default-work'- },- {- connectionId: 'work',- connectionKind: 'remote',- connectionLabel: 'Work',- profile: 'default',- handle: 'default-work'- }- ]- }-- const once = merge(local, union, 'work')- const twice = merge(once, union, 'work')- const identities = twice.profiles.map(row => `${row.connectionId}:${row.name}`)-- assert.equal(identities.join(','), 'work:default,local:default')- assert.equal(new Set(identities).size, identities.length)- assert.equal(rich.connectionId, undefined)-})--test('default rows use source identity without borrowing another source title', () => {- const { __botRosterKey: key, __botRosterMeta: metaFor, __displayName: name } = runtime()- const remote = {- name: 'default',- connectionId: 'other',- connectionLabel: 'Personal',- remoteSource: true,- sourceScoped: true- }- const active = { ...remote, connectionId: 'personal', remoteSource: undefined }- const metadata = {- default: { title: 'Legacy local only' },- 'personal::default': { title: 'Active workspace' }- }-- assert.equal(metaFor(remote, metadata), undefined)- assert.equal(name(remote, metaFor(remote, metadata)), 'Personal')- assert.equal(key(remote), 'other::default')-- // The ACTIVE gateway's own default is the user's main agent — annotation- // (sourceScoped + connection fields) must NOT rename it to a connection- // label. Titled: the title wins. Untitled: it stays "Hermes". Regression:- // remote-gateway desktops showed the main agent as an IP-derived label- // with no shortname (Aug 17 2026 report).- assert.equal(name(active, metadata['personal::default']), 'Active workspace')- assert.equal(name(active, undefined), 'Hermes')-})--test('botRosterMeta: a group roster row orphaned by a deleted connection does not throw', () => {- const { __botRosterMeta: metaFor } = runtime()- // Mirrors the persisted `group-chats` descriptor left behind once its- // connection is removed: remoteSource is still true, but connectionId is- // gone, so botConnectionRoute has nothing to resolve. This must not crash- // rendering the group (#93492) just because one member is unroutable.- const orphaned = { name: 'halakukhan', handle: 'halakukhan', connectionId: null, remoteSource: true }-- assert.doesNotThrow(() => metaFor(orphaned, {}))- assert.equal(metaFor(orphaned, {}), null)-})--test('resolveBotConnectionRoute: typed status for resolved / owner_removed / not_scoped, and strict botConnectionRoute still fails closed', () => {- const { __resolveBotConnectionRoute: resolve, __botConnectionRoute: strictRoute } = runtime()- const orphaned = { name: 'halakukhan', connectionId: null, remoteSource: true }- const owned = { name: 'halakukhan', connectionId: 'conn-1', remoteSource: true }- const local = { name: 'default' }-- // Passive resolver: typed status, never throws.- assert.equal(resolve(orphaned).status, 'owner_removed')- assert.equal(resolve(owned).status, 'resolved')- assert.equal(resolve(owned).route.connectionId, 'conn-1')- assert.equal(resolve(local).status, 'not_scoped')-- // Strict wrapper used by real dispatch (requestForBot, session creation)- // must still fail closed on the same orphaned row -- the split only moves- // the *passive* lookup off this throw, it does not remove it.- assert.throws(() => strictRoute(orphaned), /has no connection owner/)- assert.equal(strictRoute(owned).connectionId, 'conn-1')-})--test('botRosterMeta: an unrelated failure while resolving meta for a live route still propagates', () => {- const { __botRosterMeta: metaFor } = runtime()- const owned = { name: 'halakukhan', connectionId: 'conn-1', remoteSource: true }- // A metaByName lookup that throws for reasons that have nothing to do with- // connection ownership must not be caught by botRosterMeta -- only the- // owner_removed status is treated as "no meta for this row".- const explodingMetaByName = new Proxy({}, {- get() {- throw new Error('unrelated invariant failure')- }- })-- assert.throws(() => metaFor(owned, explodingMetaByName), /unrelated invariant failure/)-})--test('botHandle: precomputed multi-source handle wins; default stays hermes', () => {- const { __botHandle: botHandle } = runtime()-- assert.equal(botHandle('research', { handle: 'research-homelab' }), 'research-homelab')- assert.equal(botHandle('research', { handle: 'research' }), 'research')- assert.equal(botHandle('research'), 'research')- assert.equal(botHandle('default'), 'hermes')-})--test('filterBots: matches the source device name for remote rows', () => {- const { __filterBots: filterBots } = runtime()- const roster = [- { name: 'research' },- {- name: 'research',- connectionId: 'homelab',- connectionLabel: 'Homelab',- handle: 'research-homelab',- remoteSource: true,- sourceScoped: true- }- ]-- const hits = filterBots(roster, {}, 'homelab')- assert.equal(hits.length, 1)- assert.equal(hits[0].remoteSource, true)-- // Handle search still narrows to the disambiguated row.- const byHandle = filterBots(roster, {}, '@research-homelab')- assert.equal(byHandle.length, 1)- assert.equal(byHandle[0].handle, 'research-homelab')-- // Bare profile search keeps matching both rows.- assert.equal(filterBots(roster, {}, 'research').length, 2)-})--test('merge: active-gateway union agents annotate local rows, not duplicates (remote-primary desktop)', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = {- profiles: [- { name: 'default', last_session: { id: 's-default' } },- { name: 'dev', last_session: { id: 's-dev' } }- ]- }- const union = {- primaryConnectionId: '10-244-108-128-9119',- agents: [- // The ACTIVE remote gateway itself — same identities as local, must- // annotate in place rather than append phantom duplicates (#88344).- { connectionId: '10-244-108-128-9119', connectionKind: 'remote', connectionLabel: '10.244.108.128:9119', profile: 'default', handle: 'default-10-244-108-128-9119' },- { connectionId: '10-244-108-128-9119', connectionKind: 'remote', connectionLabel: '10.244.108.128:9119', profile: 'dev', handle: 'dev' },- // A genuinely separate source with a same-named profile keeps its own row.- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'default', handle: 'default-this-device' },- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'agent-mentor', handle: 'agent-mentor' }- ]- }-- const out = merge(local, union)- // 2 annotated local rows + 2 other-source rows = 4, NOT 6 (no phantom copies).- assert.equal(out.profiles.length, 4)-- const defaultRow = out.profiles.find(p => p.name === 'default' && !p.remoteSource)- // Annotated with the ACTIVE gateway's handle; rich fields survive.- assert.equal(defaultRow.last_session.id, 's-default')- assert.equal(defaultRow.handle, 'default-10-244-108-128-9119')-- // The same-named profile on the local device stays a separate tagged row.- const localDefault = out.profiles.find(p => p.name === 'default' && p.remoteSource)- assert.equal(localDefault.handle, 'default-this-device')- assert.equal(localDefault.connectionId, 'local')-- const mentor = out.profiles.find(p => p.name === 'agent-mentor')- assert.equal(mentor.remoteSource, true)-- // Exactly the two other-source rows are tagged remote; none from the active gateway.- assert.equal(out.profiles.filter(p => p.remoteSource).length, 2)-})--test('merge: primary-local desktop keeps single-source behavior (no phantom rows)', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = { profiles: [{ name: 'default' }, { name: 'dev' }] }- const union = {- primaryConnectionId: 'local',- agents: [- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'default', handle: 'default-this-device' },- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'dev', handle: 'dev' }- ]- }-- const out = merge(local, union)- assert.equal(out.profiles.length, 2)- assert.equal(out.profiles.filter(p => p.remoteSource).length, 0)- assert.equal(out.profiles[0].handle, 'default-this-device')-})--// The LIVE-active-id override: after the user activates a non-primary-// source's agent, profiles.list answers from THAT source — the merge must-// classify against the live id, not the registry primary, or the active-// source's agents duplicate all over again.-test('merge: live-null local window does not treat registry primary as active', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = { profiles: [{ name: 'default', last_session: { id: 'this-chat' } }] }- const union = {- primaryConnectionId: 'spark',- agents: [- {- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- profile: 'default',- handle: 'default-this-device'- },- { connectionId: 'spark', connectionKind: 'ssh', connectionLabel: 'Spark', profile: 'bob', handle: 'bob' },- { connectionId: 'spark', connectionKind: 'ssh', connectionLabel: 'Spark', profile: 'kai', handle: 'kai' },- { connectionId: 'spark', connectionKind: 'ssh', connectionLabel: 'Spark', profile: 'rook', handle: 'rook' }- ]- }-- // Clicking the local agent leaves host.state.connectionId null while the- // registry primary stays on Spark. That must not skip Spark bots or invent- // a second "This device" shadow of default.- const out = merge(local, union, null)-- assert.equal(out.profiles.filter(p => p.name === 'default').length, 1)- assert.equal(out.profiles.find(p => p.name === 'default').last_session.id, 'this-chat')- assert.equal(out.profiles.filter(p => p.remoteSource && p.connectionId === 'local').length, 0)- assert.equal(- out.profiles- .filter(p => p.remoteSource)- .map(p => p.name)- .sort()- .join(','),- 'bob,kai,rook'- )-})--test('merge: legacy remote descriptor infers a matching remote primary when local inventory differs', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = { profiles: [{ name: 'default', last_session: { id: 'noah-chat' } }] }- const union = {- primaryConnectionId: 'noah',- agents: [- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'archie', handle: 'archie' },- { connectionId: 'noah', connectionKind: 'remote', connectionLabel: 'Noah', profile: 'default', handle: 'default' }- ]- }-- // Legacy remote descriptors have mode:'remote' but no connectionId, so the- // host state is null. The matching primary row must annotate the rich row,- // while Archie remains a selectable other-source agent.- const out = merge(local, union, null)-- assert.equal(out.profiles.length, 2)- assert.equal(out.profiles.find(p => p.name === 'default').connectionId, 'noah')- assert.equal(out.profiles.find(p => p.name === 'default').remoteSource, undefined)- assert.equal(out.profiles.find(p => p.name === 'archie').connectionId, 'local')- assert.equal(out.profiles.find(p => p.name === 'archie').remoteSource, true)-})--test('merge: previously seen remotes survive a connect-on-demand empty union', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const previous = [- { name: 'default', last_session: { id: 'this-chat' } },- {- name: 'bob',- remoteSource: true,- sourceScoped: true,- connectionId: 'spark',- connectionKind: 'ssh',- connectionLabel: 'Spark',- handle: 'bob'- }- ]- const local = { profiles: [{ name: 'default', last_session: { id: 'this-chat' } }] }- const union = {- primaryConnectionId: 'local',- agents: [- {- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- profile: 'default',- handle: 'default'- }- ],- sources: [{ connectionId: 'spark', kind: 'ssh', error: 'connect-on-demand' }]- }-- const out = merge(local, union, 'local', previous)- const bob = out.profiles.find(p => p.name === 'bob' && p.connectionId === 'spark')-- assert.ok(bob)- assert.equal(bob.remoteSource, true)- assert.equal(out.profiles.filter(p => p.name === 'default').length, 1)-})--test('merge: previous remotes from a removed connection do not resurrect', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const previous = [- { name: 'default', last_session: { id: 'this-chat' } },- {- name: 'bob',- remoteSource: true,- sourceScoped: true,- connectionId: 'gone',- connectionKind: 'ssh',- connectionLabel: 'Gone',- handle: 'bob'- }- ]- const local = { profiles: [{ name: 'default', last_session: { id: 'this-chat' } }] }- const union = {- primaryConnectionId: 'local',- agents: [- {- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- profile: 'default',- handle: 'default'- }- ],- sources: [{ connectionId: 'local', kind: 'local' }]- }-- const out = merge(local, union, 'local', previous)- assert.equal(out.profiles.find(p => p.connectionId === 'gone'), undefined)-})--test('displayName: local default stays Hermes; remote default uses the device label', () => {- const { __displayName: name } = runtime()-- assert.equal(- name(- {- name: 'default',- sourceScoped: true,- connectionKind: 'local',- connectionLabel: 'This device'- },- null- ),- 'Hermes'- )- assert.equal(- name(- {- name: 'default',- sourceScoped: true,- remoteSource: true,- connectionKind: 'ssh',- connectionLabel: 'Spark'- },- null- ),- 'Spark'- )-})--test('merge: live active id beats primaryConnectionId for active-source matching', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = { profiles: [{ name: 'default', last_session: { id: 's1' } }] }- const union = {- primaryConnectionId: 'local',- agents: [- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'default', handle: 'default-this-device' },- { connectionId: 'vps', connectionKind: 'remote', connectionLabel: 'VPS', profile: 'default', handle: 'default-vps' }- ]- }-- // Live gateway = vps: its union row annotates the rich row; the primary- // (local) row appends as the genuinely-other source.- const out = merge(local, union, 'vps')- assert.equal(out.profiles.length, 2)-- const rich = out.profiles.find(p => p.last_session)- assert.equal(rich.handle, 'default-vps')- assert.equal(out.profiles.filter(p => p.remoteSource).length, 1)- assert.equal(out.profiles.find(p => p.remoteSource).connectionId, 'local')-})--// Composition of the two dedup layers (#88828 install_id collapse + #88697-// boot-descriptor connectionId): when the remote PRIMARY is registered under-// two addresses, buildAgentRoster collapses the twin to ONE union row that-// carries the PRIMARY's connectionId (collapse prefers the active/primary-// connection). The boot descriptor now reports that same id as the live id,-// so the merge must classify those collapsed rows as active-source-// annotations — collapse first, then merge, with no re-append and no-// double-collapse of a genuinely distinct source.-test('merge: install_id-collapsed twin-address primary composes with the live id (no re-append)', () => {- const { __mergeMultiSourceRoster: merge } = runtime()- const local = {- profiles: [- { name: 'default', last_session: { id: 's-default' } },- { name: 'dev', last_session: { id: 's-dev' } }- ]- }- const union = {- primaryConnectionId: 'spark-lan',- agents: [- // Post-#88828 union: the tailscale twin of the primary collapsed into- // these rows — one per profile, keyed to the PRIMARY connection id.- { connectionId: 'spark-lan', connectionKind: 'remote', connectionLabel: 'Spark', profile: 'default', handle: 'default-spark' },- { connectionId: 'spark-lan', connectionKind: 'remote', connectionLabel: 'Spark', profile: 'dev', handle: 'dev' },- // A real second backend survives the collapse and stays its own row.- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', profile: 'default', handle: 'default-this-device' }- ]- }-- // Live id from the fixed boot descriptor === the collapsed rows' id.- const out = merge(local, union, 'spark-lan')-- // 2 annotated primary rows + 1 distinct local row = 3. Pre-fix (live id- // null) this was 5: both primary rows re-appended as phantom sources.- assert.equal(out.profiles.length, 3)- assert.equal(out.profiles.filter(p => p.remoteSource).length, 1)-- const defaultRow = out.profiles.find(p => p.name === 'default' && !p.remoteSource)- assert.equal(defaultRow.last_session.id, 's-default')- assert.equal(defaultRow.handle, 'default-spark')- assert.equal(defaultRow.connectionId, 'spark-lan')-- const localTwin = out.profiles.find(p => p.name === 'default' && p.remoteSource)- assert.equal(localTwin.connectionId, 'local')-})--test('botRosterKey: same name on two sources yields distinct React keys', () => {- const { __botRosterKey: botRosterKey } = runtime()-- const legacyRow = botRosterKey({ name: 'default' })- const remoteRow = botRosterKey({ name: 'default', remoteSource: true, connectionId: 'homelab' })- const activeRow = botRosterKey({ name: 'default', connectionId: 'vps' })-- assert.notEqual(legacyRow, remoteRow)- assert.notEqual(activeRow, remoteRow)- // Single-source desktops (no connection ids anywhere) keep a stable key.- assert.equal(legacyRow, 'legacy::default')-})--test('resolveRosterMentions: @dixie and @bob-mac-mini hit Connections bots, not this chat', () => {- const { __resolveRosterMentions: resolve } = runtime()- const roster = [- { name: 'default', connectionId: 'local', connectionKind: 'local', handle: 'default-this-device' },- {- name: 'dixie',- connectionId: 'mac-mini',- connectionKind: 'ssh',- connectionLabel: 'Mac Mini',- handle: 'dixie',- remoteSource: true,- sourceScoped: true- },- {- name: 'bob',- connectionId: 'mac-mini',- connectionKind: 'ssh',- connectionLabel: 'Mac Mini',- handle: 'bob-mac-mini',- remoteSource: true,- sourceScoped: true- },- {- name: 'bob',- connectionId: 'spark',- connectionKind: 'ssh',- connectionLabel: 'Spark',- handle: 'bob-spark',- remoteSource: true,- sourceScoped: true- }- ]-- const hits = resolve('hey @dixie and @bob-spark, ping @bob-mac-mini', roster, {- name: 'default',- connectionId: 'local'- })-- assert.equal(- hits- .map(bot => `${bot.connectionId}::${bot.name}`)- .sort()- .join(','),- 'mac-mini::bob,mac-mini::dixie,spark::bob'- )-})--test('resolveRosterMentions: @hermes in this chat is not a handoff to yourself', () => {- const { __resolveRosterMentions: resolve } = runtime()- const roster = [- { name: 'default', connectionId: 'local', handle: 'hermes' },- {- name: 'default',- connectionId: 'mac-mini',- connectionLabel: 'Mac Mini',- handle: 'default-mac-mini',- remoteSource: true- }- ]-- const hits = resolve('ask @hermes and @default-mac-mini', roster, {- name: 'default',- connectionId: 'local'- })-- assert.equal(hits.length, 1)- assert.equal(hits[0].connectionId, 'mac-mini')-})--test('source contract: active roster queries use the SDK ambient owner route', () => {- assert.doesNotMatch(source, /activeBotRoute/)- assert.equal(- source.match(/requestForBot\(activeBot, 'profiles\.list', \{\}\)/g)?.length,- 2,- 'roster hydration and the session sweep must both use the upstream ambient-owner route'- )-})--test('preferReachableSameNameRows: drops a dead loopback twin when This device is live', () => {- const { __preferReachableSameNameRows: prefer } = runtime()- const live = {- name: 'profile-a',- handle: 'profile-a-this-device',- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- sourceReachable: true- }- const dead = {- name: 'profile-a',- handle: 'profile-a-127-0-0-1-19119',- connectionId: 'loopback-19119',- connectionKind: 'remote',- connectionLabel: '127.0.0.1:19119',- remoteSource: true,- sourceScoped: true,- sourceReachable: false- }- const other = {- name: 'profile-b',- handle: 'profile-b-127-0-0-1-19119',- connectionId: 'loopback-19119',- connectionKind: 'remote',- connectionLabel: '127.0.0.1:19119',- remoteSource: true,- sourceScoped: true,- sourceReachable: false- }-- const out = prefer([dead, live, other])-- assert.equal(out.length, 2)- assert.equal(out[0], live)- assert.equal(out[1], other)-})--test('preferReachableSameNameRows: keeps two live sources with the same profile name', () => {- const { __preferReachableSameNameRows: prefer } = runtime()- const local = {- name: 'research',- connectionId: 'local',- connectionLabel: 'This device',- sourceReachable: true- }- const homelab = {- name: 'research',- connectionId: 'homelab',- connectionLabel: 'Homelab',- remoteSource: true,- sourceReachable: true- }-- const out = prefer([local, homelab])-- assert.equal(out.length, 2)- assert.equal(out[0], local)- assert.equal(out[1], homelab)-})--test('preferReachableSameNameRows: keeps an unreachable row when no live twin exists', () => {- const { __preferReachableSameNameRows: prefer } = runtime()- const dead = {- name: 'research',- connectionId: 'loopback-19119',- sourceReachable: false- }-- const out = prefer([dead])-- assert.equal(out.length, 1)- assert.equal(out[0], dead)-})--test('preferReachableSameNameRows: connect-on-demand counts as reachable', () => {- const { __preferReachableSameNameRows: prefer } = runtime()- const onDemand = {- name: 'research',- connectionId: 'mac-mini',- sourceError: 'connect-on-demand',- sourceReachable: false- }- const dead = {- name: 'research',- connectionId: 'loopback-19119',- sourceReachable: false- }-- const out = prefer([onDemand, dead])-- assert.equal(out.length, 1)- assert.equal(out[0], onDemand)-})--test('preferReachableSameNameRows: sourceMissing drops when a live same-name row exists', () => {- const { __preferReachableSameNameRows: prefer } = runtime()- const live = { name: 'research', connectionId: 'local', sourceReachable: true }- const missing = {- name: 'research',- connectionId: 'gone',- sourceMissing: true,- sourceReachable: false- }-- const out = prefer([missing, live])-- assert.equal(out.length, 1)- assert.equal(out[0], live)-})--test('preferReachableSameNameRows: ghosts stay so a selected offline owner is not replaced', () => {- const { __preferReachableSameNameRows: prefer } = runtime()- const live = { name: 'research', connectionId: 'local', sourceReachable: true }- const ghost = {- name: 'research',- connectionId: 'loopback-19119',- ghost: true,- sourceReachable: false- }-- const out = prefer([ghost, live])-- assert.equal(out.length, 2)- assert.equal(out[0], ghost)- assert.equal(out[1], live)-})--test('preferReachableSameNameRows: does not mutate the input list', () => {- const { __preferReachableSameNameRows: prefer } = runtime()- const rows = [- { name: 'research', connectionId: 'loopback-19119', sourceReachable: false },- { name: 'research', connectionId: 'local', sourceReachable: true }- ]-- prefer(rows)-- assert.equal(rows.length, 2)- assert.equal(rows[0].connectionId, 'loopback-19119')-})--test('source contract: presentation collapses unreachable twins; shared roster does not', () => {- assert.match(source, /preferReachableSameNameRows\(filteredRoster\)/)- assert.match(source, /\$lastRoster\.set\(roster\.filter\(row => !row\?\.ghost\)\)/)- assert.doesNotMatch(- source.slice(source.indexOf('function groupChatMemberBots'), source.indexOf('function durableGroupChatMembers')),- /preferReachableSameNameRows/- )-})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.mjsdeleted file mode 100644index d6a18bee1cd..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/new-compact-guard.test.mjs+++ /dev/null@@ -1,28 +0,0 @@-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. Canonical identity is the NAME — the profile's session titled-// "Bot Chat" — reported by the gateway as canonical_session on every roster row.-// The guard compares the on-screen session id against that registry row (durable-// id OR compression-lineage tip). No stored meta.chat pointer is consulted:-// pointers dangle; the registry row cannot.--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 + 900)--test('the /new guard reads the canonical registry row, never a stored pointer', () => {- assert.match(guardBlock, /canonical_session/)- assert.doesNotMatch(guardBlock, /meta\?\.chat/)- assert.doesNotMatch(guardBlock, /chat_pin/)-})--test('the guard matches both the durable registry id and the lineage tip', () => {- assert.match(guardBlock, /canonical\?\.id/)- assert.match(guardBlock, /canonical\?\.resolved_id/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/orphaned-connection-members.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/orphaned-connection-members.test.mjsdeleted file mode 100644index e5ccbcd2879..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/orphaned-connection-members.test.mjs+++ /dev/null@@ -1,182 +0,0 @@-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')--// #93492 root fix: deleting a connection sweeps/annotates the persisted-// group-chat member rows that referenced it (registry 'removed' push), and a-// hydrate-time pass annotates rows orphaned before the sweep existed. Rows-// are marked (sourceMissing → the existing 'Gateway removed' degraded state),-// never silently deleted.--function runtime() {- const atom = initial => {- let value = initial- return { get: () => value, set: next => { value = next }, listen: () => () => undefined }- }- const jsx = (type, props = {}) => ({ type, props })- const storageWrites = []- 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: {- connectionId: { get: () => 'local', listen: () => undefined },- profile: { get: () => 'ops', listen: () => undefined }- },- request: () => undefined- },- sdk: new Proxy({}, { get: () => undefined })- }- const code = source- .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(- '\nglobalThis.__orphan = { $groupChats, sweepGroupChatMembersForRemovedConnection, annotateOrphanedGroupChatMembers, markOrphanedGroupMemberDescriptor, groupMemberReferencesConnection, botSourceStatus, durableGroupChatMembers, botWorkspaceOwnerKey, setBotsWorkspaceOwner, useModelOptions, pluginCtxRef: () => pluginCtx, setPluginCtx: value => { pluginCtx = value } };'- )- vm.runInNewContext(code, context)- context.__storageWrites = storageWrites- return context-}--function member(overrides = {}) {- return {- name: 'dixie',- handle: 'dixie',- connectionId: 'conn-gone',- remoteSource: true,- sourceScoped: true,- route: { connectionId: 'conn-gone', mode: 'remote', profile: 'dixie', targetProfile: 'dixie' },- ...overrides- }-}--test('removed-connection sweep annotates matching members and persists; other rows untouched', () => {- const { __orphan: o } = runtime()- const writes = []- o.setPluginCtx({ storage: { set: (key, value) => { writes.push([key, value]); return Promise.resolve() } } })-- o.$groupChats.set({- Crew: {- log: [{ id: '1', at: 1 }],- watermarks: {},- members: [member(), member({ name: 'bob', connectionId: 'conn-live', route: { connectionId: 'conn-live', mode: 'remote', profile: 'bob', targetProfile: 'bob' } })]- }- })-- assert.equal(o.sweepGroupChatMembersForRemovedConnection('conn-gone'), true)-- const room = o.$groupChats.get().Crew- const swept = room.members.find(m => m.name === 'dixie')- const kept = room.members.find(m => m.name === 'bob')-- // Annotated, not deleted: identity survives, marked degraded.- assert.equal(room.members.length, 2)- assert.equal(swept.sourceMissing, true)- assert.equal(swept.sourceReachable, false)- assert.equal(kept.sourceMissing, undefined)- // The degraded mark renders as the existing 'Gateway removed' state.- assert.equal(o.botSourceStatus(swept).label, 'Gateway removed')- // Persisted so the fix survives restarts (the poisoned row lived in storage).- assert.ok(writes.some(([key]) => key === 'group-chats'))-})--test('removed-connection sweep is idempotent and ignores blank ids', () => {- const { __orphan: o } = runtime()- o.setPluginCtx({ storage: { set: () => Promise.resolve() } })- o.$groupChats.set({ Crew: { log: [], watermarks: {}, members: [member()] } })-- assert.equal(o.sweepGroupChatMembersForRemovedConnection(''), false)- assert.equal(o.sweepGroupChatMembersForRemovedConnection('conn-gone'), true)- // Already annotated: nothing left to change.- assert.equal(o.sweepGroupChatMembersForRemovedConnection('conn-gone'), false)-})--test('hydrate annotate: lost-connectionId rows are marked even without a registry', () => {- const { __orphan: o } = runtime()- const rooms = {- Crew: {- log: [],- watermarks: {},- // The exact persisted shape from #93492: remoteSource kept, connectionId gone.- members: [{ name: 'halakukhan', handle: 'halakukhan', connectionId: null, remoteSource: true }]- }- }-- const { rooms: next, changed } = o.annotateOrphanedGroupChatMembers(rooms, null)-- assert.equal(changed, true)- assert.equal(next.Crew.members[0].sourceMissing, true)- assert.equal(o.botSourceStatus(next.Crew.members[0]).label, 'Gateway removed')-})--test('hydrate annotate: with a live registry, members on dead connections are marked, live and local kept', () => {- const { __orphan: o } = runtime()- const rooms = {- Crew: {- log: [],- watermarks: {},- members: [- member(),- member({ name: 'bob', connectionId: 'conn-live', route: { connectionId: 'conn-live', mode: 'remote', profile: 'bob', targetProfile: 'bob' } }),- { name: 'local-pal' }- ]- }- }-- const { rooms: next, changed } = o.annotateOrphanedGroupChatMembers(rooms, new Set(['conn-live']))-- assert.equal(changed, true)- assert.equal(next.Crew.members.find(m => m.name === 'dixie').sourceMissing, true)- assert.equal(next.Crew.members.find(m => m.name === 'bob').sourceMissing, undefined)- assert.equal(next.Crew.members.find(m => m.name === 'local-pal').sourceMissing, undefined)-})--test('hydrate annotate: no registry means only the unresolvable-route shape is touched', () => {- const { __orphan: o } = runtime()- const rooms = { Crew: { log: [], watermarks: {}, members: [member()] } }-- // conn-gone still has an id; without a registry we cannot prove it dead.- const { changed } = o.annotateOrphanedGroupChatMembers(rooms, null)-- assert.equal(changed, false)-})--test('render-reachable route callers degrade on an orphaned row instead of throwing', () => {- const { __orphan: o } = runtime()- const orphaned = { name: 'halakukhan', handle: 'halakukhan', connectionId: null, remoteSource: true }-- // botWorkspaceOwnerKey (sidebar sync / Bots home / context menus)- assert.doesNotThrow(() => o.botWorkspaceOwnerKey(orphaned))- assert.equal(o.botWorkspaceOwnerKey(orphaned), 'bot:halakukhan')- // setBotsWorkspaceOwner (sidebar visibility listener)- assert.doesNotThrow(() => o.setBotsWorkspaceOwner('bot:halakukhan', orphaned))- // durableGroupChatMembers (every group send / roster refresh)- assert.doesNotThrow(() => o.durableGroupChatMembers([orphaned]))- const durable = o.durableGroupChatMembers([{ ...orphaned, sourceMissing: true, sourceReachable: false }])[0]- // The degraded mark survives the durable rebuild.- assert.equal(durable.sourceMissing, true)- // useModelOptions (hook body — runs during pane render)- assert.doesNotThrow(() => o.useModelOptions(orphaned))-})--test('source contract: the sweep is wired to the registry removed push and unbound on dispose', () => {- assert.match(source, /connections\?\.onChanged\?\.\(/)- assert.match(source, /payload\?\.reason === 'removed'/)- assert.match(source, /sweepGroupChatMembersForRemovedConnection\(payload\.connectionId\)/)- assert.match(source, /unbindConnectionsChanged\(\)/)-})--test('source contract: hydrate runs the orphan annotate over persisted rooms', () => {- assert.match(source, /annotateOrphanedGroupChatMembers\(\$groupChats\.get\(\), liveIds\)/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/pane-dock-layout.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/pane-dock-layout.test.mjsdeleted file mode 100644index e800f6867a8..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/pane-dock-layout.test.mjs+++ /dev/null@@ -1,49 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--// Bot Mode layout contract:-// - the Bots pane center-stacks into the sessions zone (SESSIONS | BOTS tab-// strip), never splits below it, and carries the ENFORCED dock invariant-// so every boot re-homes a stacked install — no heal token, no-// user-placed exemption (the retired one-shot heal left users who had-// dragged panes stuck stacked forever);-// - the Cronjobs (routines) pane only exists while a BOT CHAT owns the main-// workspace and the Bots pane is on screen — registered/unregistered-// through the contribution disposer, driven by the feature-detected-// host.paneVisibility SDK export, with the always-registered fallback kept-// for older desktops. Cronjobs are bot-scoped, so the tile must not sit-// beside a group chat.--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--test('the Bots pane center-docks into the sessions zone as an enforced invariant', () => {- assert.match(source, /dock: \{ pane: 'sessions', pos: 'center', enforce: true \}/)- // The old workaround split must not come back.- assert.doesNotMatch(source, /pane: 'sessions', pos: 'bottom'/)- // Neither may the retired one-shot heal token.- assert.doesNotMatch(source, /heal: 'sessions-tab-v1'/)-})--test('routines registration is a reusable disposer-returning function', () => {- assert.match(source, /const registerRoutinesPane = \(\) =>\s*\n\s*ctx\.register\(\{\s*\n\s*id: 'routines'/)- assert.match(source, /dock: \{ pane: 'workspace', pos: 'right', enforce: true \}/)-})--test('routines pane rides Bots visibility via feature-detected host.paneVisibility', () => {- assert.match(source, /typeof host\.paneVisibility === 'function'/)- assert.match(source, /host\.paneVisibility\(`\$\{ID\}:pane`\)/)- // Transitions register/unregister through the tracked disposer.- assert.match(source, /unregisterRoutines \?\?= registerRoutinesPane\(\)/)- assert.match(source, /unregisterRoutines\(\)\s*\n\s*unregisterRoutines = null/)- // Ownership, not mere visibility: an actual bot chat must own the center.- assert.match(source, /if \(botChatOwnsWorkspace\(\)\) \{/)- // None of the lifecycle listeners may survive plugin disable.- assert.match(source, /ctx\.onDispose\(\(\) => \{\s*\n\s*stopSidebarSync\(\)/)- assert.match(source, /stopGroupSync\(\)/)- assert.match(source, /stopFocusSync\?\.\(\)/)-})--test('older desktops without the SDK export keep the always-registered pane', () => {- assert.match(source, /\} else \{\s*\n\s*registerRoutinesPane\(\)\s*\n\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.mjsdeleted file mode 100644index 1d818ba9364..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/pet-fetch.test.mjs+++ /dev/null@@ -1,76 +0,0 @@-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.mjsdeleted file mode 100644index b1100bd1775..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs+++ /dev/null@@ -1,331 +0,0 @@-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)-}--// BotRow's activity resolver — extract the REAL helper so the harness can't-// drift from production behavior.-function activitySessionSource() {- return sourceBetween('function botActivitySession(', '/** Bots that are working')-}--function renderBotRow(input = 'alpha') {- const bot = typeof input === 'string' ? { name: input } : input- const name = bot.name- const botRowSource = sourceBetween('function BotRow(', '// ── model picker')- // REAL owner-route resolver — the derivation from bare connectionId rows is- // exactly what these tests exercise, so a hand stub would drift.- const routeSource = sourceBetween('function botConnectionRoute(', 'function rewriteCliProfileOperands(')- const ensured = []- const opened = []- const saved = []- const warmed = []- let liveConnectionId = 'local'- 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',- Codicon: 'Codicon',- Tip: 'Tip',- ROSTER_KEY: ['hermes-bots', 'roster'],- $botMeta: atom({}),- $botUnread: atom({}),- $botAttention: atom({}),- BOT_ATTENTION_HINTS: {},- $botChatFocused: atom(false),- $focusedBotOwner: atom({ connectionId: 'local', profile: 'default' }),- $focusedBotProfile: atom('default'),- $groupChatWorkspace: atom(null),- $lastRoster: atom([]),- $selectedBot: atom('default'),- $selectedRosterKey: atom(''),- botAppearance: () => ({ shape: 'round', color: '#000', image: null }),- botMetaKey: value => value.sourceScoped- ? `${value.route?.connectionId || value.connectionId}::${value.name}`- : value.name,- botGroups: () => [],- botHandle: value => value,- botRosterKey: value => `${value.connectionId || 'legacy'}::${value.name}`,- botRowOwnsWorkspace: () => false,- botSourceStatus: () => ({ available: true, label: 'Ready' }),- botOpenGeneration: 0,- botRosterMeta: (_bot, metaByName) => {- const key = _bot.sourceScoped- ? `${_bot.route?.connectionId || _bot.connectionId}::${_bot.name}`- : _bot.name- return metaByName?.[key] ?? null- },- cn: (...values) => values.filter(Boolean).join(' '),- createCanonicalChat: async () => null,- displayName: bot => bot.name,- duplicateBot: async () => `${name}-copy`,- ensureBotMetadata: async () => ({ pinned: true }),- haptic: () => undefined,- // #49 session-aware-row helpers referenced inside BotRow.- previewKind: () => ({ fromBot: false, sender: null }),- generatedSessionTitle: () => null,- focusedRosterOwner: owner => ({ connectionId: owner.connectionId, name: owner.profile }),- isActiveRosterBot: () => false,- isBackfilledFacePng: () => false,- isBotHidden: () => false,- isBotPinned: () => false,- botSelectionKey: value => value.sourceScoped ? `${value.connectionId}::${value.name}` : value.name,- isDefaultBot: value => value.name === 'default',- newBotChat: () => undefined,- openBotCanonicalChat: async (...args) => {- opened.push(args)- return 'stored-chat'- },- openRosterBot: async value => {- opened.push([value])- return true- },- workerActiveAt: () => false,- 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') },- ensureAgent: async (connectionId, profile) => {- ensured.push([connectionId, profile])- liveConnectionId = connectionId- },- activeConnectionId: () => liveConnectionId,- requestProfile: async (_route, method) =>- method === 'profiles.list'- ? { profiles: [{ name, ui_meta: { 'hermes-bots': { chat: 'owner-chat' } } }] }- : { sessions: [] },- warmAgent: (connectionId, profile) => warmed.push([connectionId, profile]),- warmProfile: profile => warmed.push(profile),- request: async method =>- method === 'profiles.list'- ? { profiles: [{ name, ui_meta: { 'hermes-bots': { chat: 'owner-chat' } } }] }- : { sessions: [] },- notify: () => undefined,- notifyError: () => undefined- },- jsx: node,- jsxs: node,- onEdit: () => undefined,- persistBotMetaSnapshot: () => Promise.resolve(),- queryClient: { invalidateQueries: () => undefined },- relativeTime: () => 'now',- requestForBot: async (_bot, method) => method === 'profiles.list'- ? {- profiles: [{- name: _bot.route?.targetProfile || _bot.name,- ui_meta: { 'hermes-bots': { pinned: true } }- }]- }- : {},- saveBotMeta: (_bot, patch) => saved.push([_bot, patch]),- showsHandle: () => false,- stripPreviewMarkdown: text => String(text || ''),- useValue: store => store.get()- }-- vm.runInNewContext(`${activitySessionSource()}\n${routeSource}\n${botRowSource}\nglobalThis.BotRow = BotRow`, context)-- const tree = context.BotRow({ bot, onEdit: context.onEdit })- const row = tree.type === 'button' ? tree : tree.props.children[0].props.children-- return { ensured, opened, row, saved, tree, warmed }-}--test('regression: rendering BotsPane does not prewarm the entire roster', () => {- const botsPaneSource = sourceBetween('function BotsPane(', '// ── plugin')-- assert.doesNotMatch(botsPaneSource, /host\.warmProfile/)-})--test('regression: source transitions keep BotRow hook order stable', () => {- const botRowSource = sourceBetween('function BotRow(', '// ── model picker')-- assert.match(botRowSource, /const unreadByName = useValue\(\$botUnread\)/)- assert.doesNotMatch(botRowSource, /remoteSource && Boolean\(useValue/)-})--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'])-})--test('behavior: context-menu pin mutation hydrates a non-identity alias before toggling', async () => {- const bot = {- connectionId: 'remote-a',- name: 'worker',- remoteSource: true,- sourceScoped: true,- route: {- connectionId: 'remote-a',- mode: 'remote',- profile: 'worker',- targetProfile: 'backend-worker'- }- }- const { saved, tree } = renderBotRow(bot)- const menuItems = tree.props.children[1].props.children-- menuItems[0].props.onSelect()- await new Promise(resolve => setTimeout(resolve, 0))-- assert.equal(saved.length, 1)- assert.equal(saved[0][0], bot)- assert.deepEqual(JSON.parse(JSON.stringify(saved[0][1])), { pinned: false })-})--test('behavior: a remote Connections row opens through its captured route without activation authority', async () => {- const { ensured, opened, row, warmed } = renderBotRow({- connectionId: 'work',- connectionLabel: 'Work',- name: 'research',- remoteSource: true,- sourceScoped: true- })-- row.props.onPointerEnter()- assert.deepEqual(warmed, [['work', 'research']])-- await row.props.onClick()- assert.deepEqual(ensured, [])- assert.equal(opened.length, 1)- assert.equal(opened[0][0].connectionId, 'work')-})--test('behavior: remote default never opens the same-name local chat', async () => {- const bot = {- connectionId: 'mac-mini',- connectionLabel: 'Mac Mini',- name: 'default',- remoteSource: true,- sourceScoped: true- }- const botRowSource = sourceBetween('function BotRow(', '// ── model picker')- const ensured = []- const opened = []- const errors = []- 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',- Codicon: 'Codicon',- Tip: 'Tip',- ROSTER_KEY: ['hermes-bots', 'roster'],- $botMeta: atom({ default: { chat: 'this-device-chat' } }),- $botUnread: atom({}),- $botAttention: atom({}),- BOT_ATTENTION_HINTS: {},- $botChatFocused: atom(false),- $focusedBotOwner: atom({ connectionId: 'mac-mini', profile: 'default' }),- $focusedBotProfile: atom('default'),- $groupChatWorkspace: atom(null),- $lastRoster: atom([]),- $selectedBot: atom('default'),- $selectedRosterKey: atom(''),- botAppearance: () => ({ shape: 'round', color: '#000', image: null }),- botGroups: () => [],- botHandle: value => value,- botRosterKey: value => `${value.connectionId || 'legacy'}::${value.name}`,- botRowOwnsWorkspace: () => false,- botSourceStatus: () => ({ available: true, label: 'Ready' }),- botOpenGeneration: 0,- botRosterMeta: () => null,- cn: (...values) => values.filter(Boolean).join(' '),- createCanonicalChat: async () => null,- displayName: bot => bot.connectionLabel || bot.name,- duplicateBot: async () => 'copy',- ensureBotMetadata: async () => ({ pinned: true }),- haptic: () => undefined,- previewKind: () => ({ fromBot: false, sender: null }),- generatedSessionTitle: () => null,- focusedRosterOwner: owner => ({ connectionId: owner.connectionId, name: owner.profile }),- isActiveRosterBot: () => false,- isBackfilledFacePng: () => false,- isBotHidden: () => false,- isBotPinned: () => false,- botSelectionKey: value => value.sourceScoped ? `${value.connectionId}::${value.name}` : value.name,- isDefaultBot: value => value.name === 'default',- newBotChat: () => undefined,- openBotCanonicalChat: async (...args) => {- opened.push(args)- return 'this-device-chat'- },- openRosterBot: async value => {- opened.push([value])- return true- },- workerActiveAt: () => false,- 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') },- ensureAgent: async (connectionId, profile) => ensured.push([connectionId, profile]),- requestProfile: async () => ({}),- activeConnectionId: () => 'local',- warmAgent: () => undefined,- warmProfile: () => undefined,- request: async () => ({ profiles: [{ name: 'default', ui_meta: { 'hermes-bots': { chat: 'this-device-chat' } } }] }),- notify: () => undefined,- notifyError: (_err, msg) => errors.push(msg)- },- jsx: node,- jsxs: node,- onEdit: () => undefined,- queryClient: { invalidateQueries: () => undefined },- relativeTime: () => 'now',- saveBotMeta: () => undefined,- showsHandle: () => false,- stripPreviewMarkdown: text => String(text || ''),- useValue: store => store.get()- }-- const routeSource = sourceBetween('function botConnectionRoute(', 'function rewriteCliProfileOperands(')- vm.runInNewContext(`${activitySessionSource()}\n${routeSource}\n${botRowSource}\nglobalThis.BotRow = BotRow`, context)- const tree = context.BotRow({ bot, onEdit: context.onEdit })- const row = tree.type === 'button' ? tree : tree.props.children[0].props.children-- await row.props.onClick()- assert.deepEqual(ensured, [])- assert.equal(opened.length, 1)- assert.equal(opened[0][0].connectionId, 'mac-mini')- assert.equal(errors.length, 0)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/reclaim-proactive-refresh.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/reclaim-proactive-refresh.test.mjsdeleted file mode 100644index 2629724f0b2..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/reclaim-proactive-refresh.test.mjs+++ /dev/null@@ -1,51 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--// Proactive reclaim refresh (polish on top of #92928/#92901): when the-// gateway reaps the runtime behind the OPEN bot chat (session.reclaimed —-// idle TTL, LRU, or the mass WS-orphan reap that killed every background-// bot's handle at once in the Aug 23 incident), the plugin re-resumes the-// canonical chat immediately instead of letting the user's next send eat a-// stale-id error + recovery round-trip.-//-// Source-shape contracts:-// - the listener subscribes via host.onEvent('session.reclaimed'), feature--// detected, and is disposed with the other listeners;-// - the match is on the STORED id against BOTH claim identities;-// - a stale generation or missing claim/bot is a no-op;-// - a failed re-resume is swallowed (next-send recovery ladder remains).--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function reclaimBlock() {- const start = pluginSource.indexOf("host.onEvent('session.reclaimed'")- assert.ok(start > 0, 'reclaim listener exists')- return pluginSource.slice(start - 400, start + 1800)-}--test('listener is feature-detected and disposed', () => {- const block = reclaimBlock()- assert.match(block, /typeof host\.onEvent === 'function'/)- assert.match(pluginSource, /stopReclaimSync\?\.\(\)/)-})--test('match is stored-id against both claim identities', () => {- const block = reclaimBlock()- assert.match(block, /payload\.stored_session_id/)- assert.match(block, /\[claim\.openedSessionId, claim\.openedRegistryId\]\.filter\(Boolean\)/)- assert.match(block, /owned\.includes\(stored\)/)-})--test('re-resume guards the open generation and refreshes both claim ids', () => {- const block = reclaimBlock()- assert.match(block, /generation !== botOpenGeneration/)- assert.match(block, /openedRegistryId: opened\.registryId/)- assert.match(block, /openedSessionId: opened\.openedId/)-})--test('failed re-resume is swallowed — next-send recovery stays the backstop', () => {- const block = reclaimBlock()- assert.match(block, /\.catch\(\(\) => \{/)- assert.match(block, /next send recovers via the ladder/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/relay-push-drain.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/relay-push-drain.test.mjsdeleted file mode 100644index fb429b51eb9..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/relay-push-drain.test.mjs+++ /dev/null@@ -1,105 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Push-notified relay drain (#93091, motivated by #92760 slow replies): the-// gateway broadcasts `bot_relay.outbox.pending` when an envelope lands in the-// outbox; the plugin drains immediately instead of waiting out the 4s poll.-// Contracts:-// - a burst of signals inside RELAY_PUSH_DEBOUNCE_MS collapses to ONE drain;-// - after the debounce fires, a later signal schedules a fresh drain;-// - the subscription is feature-detected (host.onEvent) and disposed, and the-// 4s interval poll remains untouched as the backstop.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadScheduler() {- const start = pluginSource.indexOf('function scheduleRelayPushDrain(')- const end = pluginSource.indexOf('function startBotRelay(', start)- assert.ok(start > 0, 'plugin defines scheduleRelayPushDrain')- assert.ok(end > start, 'scheduler has a stable source boundary')-- const context = {- setTimeout,- clearTimeout,- relayDisposed: false,- relayPushDebounceTimer: null,- RELAY_PUSH_DEBOUNCE_MS: 50, // shrunk from 250ms to keep the test fast- drainCalls: 0- }- vm.createContext(context)- vm.runInContext(- `async function drainRelayOutboxes() { drainCalls += 1 }\n${pluginSource.slice(start, end)}\nglobalThis.scheduleRelayPushDrain = scheduleRelayPushDrain`,- context- )- return context-}--const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))--test('a burst of pending signals collapses to one drain', async () => {- const ctx = loadScheduler()-- for (let i = 0; i < 6; i += 1) {- ctx.scheduleRelayPushDrain()- }-- assert.equal(ctx.drainCalls, 0, 'drain waits for the debounce window')- await sleep(120)- assert.equal(ctx.drainCalls, 1, 'six signals inside the window → one drain')-})--test('a signal after the window fires a fresh drain', async () => {- const ctx = loadScheduler()-- ctx.scheduleRelayPushDrain()- await sleep(120)- assert.equal(ctx.drainCalls, 1)-- ctx.scheduleRelayPushDrain()- ctx.scheduleRelayPushDrain()- await sleep(120)- assert.equal(ctx.drainCalls, 2)-})--test('a disposed relay never schedules a drain', async () => {- const ctx = loadScheduler()- ctx.relayDisposed = true-- ctx.scheduleRelayPushDrain()- await sleep(120)- assert.equal(ctx.drainCalls, 0)-})--test('subscription is feature-detected, disposed, and the poll backstop stays', () => {- const start = pluginSource.indexOf("host.onEvent('bot_relay.outbox.pending'")- assert.ok(start > 0, 'plugin subscribes to bot_relay.outbox.pending')- const block = pluginSource.slice(start - 400, start + 400)- assert.match(block, /typeof host\.onEvent === 'function'/)- assert.match(pluginSource, /relayPushUnsub\(\)/)- // The interval poll survives as a BACKSTOP — push is the delivery path,- // the poll covers older backends that never emit the event and connections- // whose events don't reach the tap. #93594 moved it from 4s (its cadence- // when the poll WAS the delivery path) to 30s backstop cadence, matching- // the live-session status backstop.- assert.match(pluginSource, /RELAY_DRAIN_INTERVAL_MS = 30_000/)- assert.match(pluginSource, /setInterval\(\(\) => void drainRelayOutboxes\(\), RELAY_DRAIN_INTERVAL_MS\)/)-})--test('a push racing an in-flight drain schedules a follow-up pass instead of dropping', () => {- // The gateway signature is monotone — one event per new envelope, never- // re-broadcast — so a push swallowed by the relayDrainBusy early-return- // would strand its envelope until the poll. The rerun flag re-schedules.- const drain = pluginSource.slice(- pluginSource.indexOf('async function drainRelayOutboxes'),- pluginSource.indexOf('function scheduleRelayPushDrain')- )- assert.match(drain, /if \(relayDrainBusy\) \{/)- assert.match(drain, /relayDrainRerun = true/)- // finally block: after busy clears, a remembered push re-schedules once.- const finallyBlock = drain.slice(drain.indexOf('} finally {'))- assert.match(finallyBlock, /relayDrainBusy = false/)- assert.match(finallyBlock, /relayDrainRerun && !relayDisposed/)- assert.match(finallyBlock, /scheduleRelayPushDrain\(\)/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/relay-socket-retention.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/relay-socket-retention.test.mjsdeleted file mode 100644index 3f05db32919..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/relay-socket-retention.test.mjs+++ /dev/null@@ -1,130 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Relay-route socket retention (#93594): while the bot relay is active, each-// registered connection's pooled socket is pinned open via-// host.retainProfileSocket so the drain loop reuses ONE persistent WebSocket-// instead of dialing and tearing down a fresh one per tick. Contracts:-// - retention is feature-detected (host.retainProfileSocket) — older shells-// simply keep the per-call lease behavior;-// - a connection is pinned once, not once per drain tick;-// - a connection leaving the registry releases exactly its own pin;-// - releaseRelayRetention drops every pin, and stopBotRelay calls it.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadRetention({ retainProfileSocket } = {}) {- const start = pluginSource.indexOf('const relayRouteRetentions = new Map()')- const end = pluginSource.indexOf('/** One representative route per reachable connection id. */', start)- assert.ok(start > 0, 'plugin defines relayRouteRetentions')- assert.ok(end > start, 'retention block has a stable source boundary')-- const releases = []- const context = {- relayDisposed: false,- retainCalls: [],- releases,- host: {- retainProfileSocket:- retainProfileSocket === null- ? undefined- : route => {- context.retainCalls.push(route)- let released = false- const release = () => {- if (!released) {- released = true- releases.push(route)- }- }- return release- }- }- }- vm.createContext(context)- vm.runInContext(- `${pluginSource.slice(start, end)}-globalThis.syncRelayRetention = syncRelayRetention-globalThis.releaseRelayRetention = releaseRelayRetention-globalThis.relayRouteRetentions = relayRouteRetentions`,- context- )- return context-}--const conn = id => ({ id, route: { connectionId: id, profile: 'default', targetProfile: 'default' } })--test('each connection is pinned ONCE across multiple drain ticks', () => {- const ctx = loadRetention()- const connections = [conn('a'), conn('b')]-- for (let tick = 0; tick < 4; tick += 1) {- ctx.syncRelayRetention(connections)- }-- assert.equal(ctx.retainCalls.length, 2, 'one pin per connection, not per tick')- assert.equal(ctx.relayRouteRetentions.size, 2)- assert.equal(ctx.releases.length, 0, 'nothing released while connections stay registered')-})--test('a connection leaving the registry releases exactly its own pin', () => {- const ctx = loadRetention()-- ctx.syncRelayRetention([conn('a'), conn('b')])- ctx.syncRelayRetention([conn('a')])-- assert.equal(ctx.releases.length, 1)- assert.equal(ctx.releases[0].connectionId, 'b')- assert.equal(ctx.relayRouteRetentions.size, 1)-})--test('releaseRelayRetention drops every pin (stop/dispose path)', () => {- const ctx = loadRetention()-- ctx.syncRelayRetention([conn('a'), conn('b'), conn('c')])- ctx.releaseRelayRetention()-- assert.equal(ctx.releases.length, 3)- assert.equal(ctx.relayRouteRetentions.size, 0)-- // Idempotent — a second stop releases nothing new.- ctx.releaseRelayRetention()- assert.equal(ctx.releases.length, 3)-})--test('a disposed relay never pins new connections but still releases stale ones', () => {- const ctx = loadRetention()-- ctx.syncRelayRetention([conn('a')])- ctx.relayDisposed = true- ctx.syncRelayRetention([conn('b')])-- assert.equal(ctx.retainCalls.length, 1, 'no new pin after dispose')- assert.equal(ctx.releases.length, 1, "the departed connection's pin was released")-})--test('retention is feature-detected: an older shell without the door is a no-op', () => {- const ctx = loadRetention({ retainProfileSocket: null })-- ctx.syncRelayRetention([conn('a'), conn('b')])-- assert.equal(ctx.relayRouteRetentions.size, 0)-})--test('stopBotRelay releases retention (source contract)', () => {- const stop = pluginSource.slice(- pluginSource.indexOf('function stopBotRelay('),- pluginSource.indexOf('/** Per-bot appearance')- )- assert.match(stop, /releaseRelayRetention\(\)/)-- // And the drain loop reconciles retention with the CURRENT connection set- // before deciding whether there is anything to relay.- const drain = pluginSource.slice(- pluginSource.indexOf('async function drainRelayOutboxes'),- pluginSource.indexOf('function scheduleRelayPushDrain')- )- assert.match(drain, /syncRelayRetention\(/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjsdeleted file mode 100644index dae14aa079a..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjs+++ /dev/null@@ -1,683 +0,0 @@-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 deferred() {- let resolve- let reject- const promise = new Promise((res, rej) => {- resolve = res- reject = rej- })-- return { promise, resolve, reject }-}--function load({ requestProfile, agents, profileRoutes } = {}) {- 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),- listen: () => undefined- }- values.set(slot, initial)- return slot- }- const calls = []- let activeConnectionId = 'remote-a'- const host = {- activeConnectionId: () => activeConnectionId,- agents: agents || (async () => ({ agents: [], sources: [] })),- deleteProfile: async route => calls.push(['deleteProfile', route]),- ensureAgent: async (connectionId, profile) => {- activeConnectionId = connectionId- calls.push(['ensureAgent', connectionId, profile])- },- newChat: (route, options) => calls.push(['newChat', route, options]),- notify: () => undefined,- notifyError: () => undefined,- profileRoutes: profileRoutes || (async () => []),- openSession: async (...args) => calls.push(['openSession', ...args]),- request: async (method, params) => {- calls.push(['ambient', method, params])- return {}- },- requestProfile: requestProfile || (async (route, method, params) => {- calls.push(['profile', route, method, params])- return {}- }),- setWorkspaceScope: (mode, ownerKey, target) => calls.push(['workspaceScope', mode, ownerKey, target]),- state: {- connectionId: { get: () => activeConnectionId, listen: () => undefined },- gateway: { get: () => 'open', listen: () => undefined },- profile: { get: () => 'default', listen: () => undefined }- }- }- const context = {- atom,- clearTimeout,- console,- Date,- document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- queryClient: { invalidateQueries: () => undefined },- setTimeout,- host,- window: { setTimeout, clearTimeout }- }- 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(`- globalThis.__race = {- $botMeta,- botActivitySession,- botConnectionRoute,- botRosterKey,- botSelectionKey,- deleteBot,- duplicateBot,- ensureBotMetadata,- groupMemberKey,- migrateBotMeta,- migratedLocalRoutes,- newBotChat,- openBotCanonicalChat,- persistBotMetaSnapshot,- prepareBotSource,- requestForBot,- saveBotMeta,- setPluginStorage: storage => { pluginCtx = { storage } }- }- `)- vm.runInNewContext(code, context, { filename: 'plugin.js' })- return {- context,- calls,- host,- setActiveConnection: value => {- activeConnectionId = value- }- }-}--const remoteBot = {- connectionId: 'remote-a',- connectionLabel: 'Remote A',- name: 'default',- remoteSource: true,- route: { connectionId: 'remote-a', mode: 'remote', profile: 'default', targetProfile: 'remote-default' },- sourceScoped: true,- targetProfile: 'remote-default'-}--function recordingStorage(- initial,- failSetKey = null,- failRemoveKeys = [],- failSetTimes = Number.POSITIVE_INFINITY-) {- const values = new Map(Object.entries(initial))- const operations = []- const failedRemovals = new Set(failRemoveKeys)- let failedSets = 0-- return {- operations,- get: async key => values.get(key) ?? null,- set: async (key, value) => {- operations.push(['set', key, value])- if (key === failSetKey && failedSets < failSetTimes) {- failedSets += 1- throw new Error('disk full')- }- values.set(key, value)- },- remove: async key => {- operations.push(['remove', key])- if (failedRemovals.has(key)) {- throw new Error('remove failed')- }- values.delete(key)- }- }-}--test('same-name bots remain pinned to their own connection under concurrent requests', async () => {- const pendingA = deferred()- const pendingB = deferred()- const seen = []- const runtime = load({- requestProfile: (route, method) => {- seen.push([route, method])- return route.connectionId === 'remote-a' ? pendingA.promise : pendingB.promise- }- })- const botB = { ...remoteBot, connectionId: 'remote-b', route: { ...remoteBot.route, connectionId: 'remote-b', targetProfile: 'remote-default-b' } }-- const first = runtime.context.__race.requestForBot(remoteBot, 'profiles.describe')- const second = runtime.context.__race.requestForBot(botB, 'profiles.describe')- await runtime.host.ensureAgent('remote-b', 'default')- pendingB.resolve({ ok: true })- pendingA.resolve({ ok: true })- await Promise.all([first, second])-- assert.deepEqual(seen.map(([route]) => route.connectionId), ['remote-a', 'remote-b'])- assert.deepEqual(seen.map(([route]) => route.targetProfile), ['remote-default', 'remote-default-b'])-})--test('source-scoped routing fails closed instead of falling back to ambient host.request', async () => {- const runtime = load()- const ambient = []- runtime.host.request = async (...args) => ambient.push(args)- runtime.host.requestProfile = undefined-- await assert.rejects(- runtime.context.__race.requestForBot(remoteBot, 'profiles.configure'),- /Cannot route profiles\.configure/- )- assert.deepEqual(ambient, [])-})--test('source-scoped routing rejects a missing connection id before dispatch', async () => {- const runtime = load()- const incomplete = {- ...remoteBot,- connectionId: '',- route: { ...remoteBot.route, connectionId: '' }- }-- await assert.rejects(- runtime.context.__race.requestForBot(incomplete, 'profiles.configure'),- /no connection owner/i- )- assert.equal(runtime.calls.some(call => call[0] === 'ambient' || call[0] === 'profile'), false)-})--test('non-identity alias hydrates metadata from the backend row before Edit saves it', async () => {- const calls = []- const workerBot = {- ...remoteBot,- name: 'worker',- route: { ...remoteBot.route, profile: 'worker', targetProfile: 'backend-worker' },- targetProfile: 'backend-worker'- }- const runtime = load({- requestProfile: async (_route, method, params) => {- calls.push([method, params])- if (method === 'profiles.list') {- return {- profiles: [{- name: 'backend-worker',- ui_meta: {- 'hermes-bots': { title: 'Hydrated', pinned: true, chat: 'worker-chat' }- }- }]- }- }- return { applied: { ui_meta: true } }- }- })-- // prepareBotSource is a capability gate under name-identity — no pin returns.- await runtime.context.__race.prepareBotSource(workerBot)-- const hydrated = await runtime.context.__race.ensureBotMetadata(workerBot)- assert.deepEqual(JSON.parse(JSON.stringify(hydrated)), {- title: 'Hydrated',- pinned: true,- chat: 'worker-chat'- })-- await runtime.context.__race.saveBotMeta(workerBot, { title: 'Edited' })- const edit = calls.find(([method]) => method === 'profiles.configure')- assert.deepEqual(JSON.parse(JSON.stringify(edit[1])), {- name: 'backend-worker',- ui_meta: {- 'hermes-bots': { title: 'Edited', pinned: true, chat: 'worker-chat' }- }- })-})--test('non-identity alias resolves the canonical chat by NAME on the backend profile', async () => {- const requests = []- const workerBot = {- ...remoteBot,- name: 'worker',- route: { ...remoteBot.route, profile: 'worker', targetProfile: 'backend-worker' },- targetProfile: 'backend-worker'- }- const runtime = load({- requestProfile: async (_route, method, params) => {- requests.push([method, params])- if (method === 'session.list') {- return {- sessions: [{ id: 'worker-chat', resolved_id: 'worker-chat-tip', title: 'Bot Chat', message_count: 3 }]- }- }- if (method === 'session.create') {- throw new Error('must not create: the registry row exists on the alias profile')- }- return {}- }- })-- const result = await runtime.context.__race.openBotCanonicalChat(workerBot)-- assert.equal(result.registryId, 'worker-chat')- assert.equal(result.openedId, 'worker-chat-tip')- const lookup = requests.find(([method]) => method === 'session.list')- assert.equal(lookup[1].profile, 'backend-worker', 'lookup uses the backend alias, not the logical name')- assert.equal(lookup[1].title, 'Bot Chat')- assert.equal(lookup[1].include_hidden, true)- const opened = runtime.calls.find(call => call[0] === 'openSession')- assert.equal(opened[1], 'worker-chat-tip', 'the lineage tip opens; the registry row stays the identity')-})--test('canonical sidebar activity and an explicit bot switch converge on a forced-resume open', async () => {- const bot = {- ...remoteBot,- canonical_session: { id: 'bot-chat', last_active: 20, preview: 'new canonical activity' },- last_session: { id: 'old-visible-chat', last_active: 10, preview: 'stale visible activity' }- }- const runtime = load({- requestProfile: async (_route, method) => {- if (method === 'session.list') {- return {- sessions: [{ id: 'bot-chat', resolved_id: 'bot-chat-tip', title: 'Bot Chat', message_count: 4 }]- }- }-- return {}- }- })-- assert.equal(- runtime.context.__race.botActivitySession(bot).id,- 'bot-chat',- 'the sidebar activity tile follows the hidden canonical chat'- )-- const result = await runtime.context.__race.openBotCanonicalChat(bot)- const opened = runtime.calls.find(call => call[0] === 'openSession')-- assert.deepEqual(JSON.parse(JSON.stringify(result)), { registryId: 'bot-chat', openedId: 'bot-chat-tip' })- assert.equal(opened[1], 'bot-chat-tip', 'the explicit switch opens the canonical lineage tip')- assert.equal(opened[2].awaitHydration, true)- assert.equal(opened[2].expectHistory, true)- assert.equal(opened[2].forceResume, true, 'a cached stale runtime must never suppress session.resume')- assert.equal(opened[2].route.connectionId, 'remote-a', 'resume stays on the canonical chat owner')-})--test('remote canonical lookup failure rejects instead of minting on the remote source', async () => {- const runtime = load({- requestProfile: async (_route, method) => {- if (method === 'session.list') {- throw new Error('remote gateway not ready')- }- if (method === 'session.create') {- throw new Error('must not create: a failed remote lookup is not "no chat exists"')- }- return {}- }- })-- await assert.rejects(() => runtime.context.__race.openBotCanonicalChat(remoteBot), /Bot Chat registry/)- assert.equal(runtime.calls.some(call => call[0] === 'openSession'), false)-})--test('delayed edit, group mutation, and canonical session RPCs retain the route', async () => {- const pending = deferred()- const seen = []- const runtime = load({- requestProfile: (route, method, params) => {- seen.push([route, method, params])- return pending.promise- }- })-- const edit = runtime.context.__race.saveBotMeta(remoteBot, { title: 'Remote title' })- const group = runtime.context.__race.requestForBot(remoteBot, 'profiles.configure', { name: 'default' })- const open = runtime.context.__race.openBotCanonicalChat(remoteBot)- await runtime.host.ensureAgent('remote-b', 'default')- pending.resolve({ applied: { ui_meta: true }, profiles: [{ name: 'default', preferred_session: { id: 'stored-remote' } }] })- await Promise.all([edit, group, open])-- assert.ok(seen.length >= 3)- assert.ok(seen.every(([route]) => route.connectionId === 'remote-a'))- assert.ok(seen.every(([route]) => Object.isFrozen(route)))-})--test('delayed duplicate, delete, and new chat keep source ownership', async () => {- const pending = deferred()- const runtime = load({- requestProfile: (route, method) => {- runtime.calls.push(['profile', route, method])- return pending.promise- }- })- const workerBot = {- ...remoteBot,- name: 'worker',- route: { ...remoteBot.route, profile: 'worker', targetProfile: 'backend-worker' },- targetProfile: 'backend-worker'- }- runtime.context.__race.$botMeta.set({ 'remote-a::worker': { title: 'Original' } })-- const duplicate = runtime.context.__race.duplicateBot(workerBot, [workerBot])- const edit = runtime.context.__race.saveBotMeta(workerBot, { pinned: true })- await runtime.host.ensureAgent('remote-b', 'default')- pending.resolve({ profiles: [{ name: 'default' }], applied: { ui_meta: true } })- await Promise.all([duplicate, edit])-- runtime.context.__race.newBotChat(workerBot)- const deletePromise = runtime.context.__race.deleteBot(workerBot)- await deletePromise-- const routes = runtime.calls- .filter(call => call[0] === 'profile' || call[0] === 'deleteProfile' || call[0] === 'newChat')- .map(call => call[1])- .filter(value => value && typeof value === 'object')- assert.ok(routes.length >= 3)- assert.ok(routes.every(route => route.connectionId === 'remote-a'))-- const newChat = runtime.calls.find(call => call[0] === 'newChat')- assert.equal(newChat[2].workspaceMode, 'bots')- assert.equal(newChat[2].workspaceOwnerKey, 'bot:remote-a::worker')- assert.equal(newChat[1].targetProfile, 'backend-worker')-- const scope = runtime.calls.find(call => call[0] === 'workspaceScope')- assert.equal(scope[1], 'bots')- assert.equal(scope[2], 'bot:remote-a::worker')- assert.equal(scope[3].kind, 'route')- assert.equal(scope[3].route.connectionId, 'remote-a')-})---test('default deletion is rejected in the executable mutation layer', async () => {- const runtime = load()- await assert.rejects(runtime.context.__race.deleteBot(remoteBot), /default profile cannot be deleted/i)- assert.equal(runtime.calls.some(call => call[0] === 'deleteProfile'), false)-})--test('source-scoped bot metadata save commits v2 marker after its data', async () => {- const storage = recordingStorage({ 'bot-meta-v2-migrated': true })- const runtime = load({- requestProfile: async () => ({ applied: { ui_meta: true } })- })- runtime.context.__race.setPluginStorage(storage)-- await runtime.context.__race.saveBotMeta(remoteBot, { title: 'Remote' })-- assert.deepEqual(storage.operations.map(operation => operation.slice(0, 2)), [- ['remove', 'bot-meta-v2-migrated'],- ['set', 'bot-meta-v2'],- ['set', 'bot-meta-v2-migrated']- ])-})--test('scoped metadata reconciliation commits v2 marker after its data', async () => {- const storage = recordingStorage({ 'bot-meta-v2-migrated': true })- const runtime = load()- runtime.context.__race.setPluginStorage(storage)-- await runtime.context.__race.persistBotMetaSnapshot({- 'remote-a::default': { hidden: true }- }, true)-- assert.deepEqual(storage.operations.map(operation => operation.slice(0, 2)), [- ['remove', 'bot-meta-v2-migrated'],- ['set', 'bot-meta-v2'],- ['set', 'bot-meta-v2-migrated']- ])-})--test('v1 metadata migrates only for a provable sole-local topology and keeps rollback data', async () => {- const writes = []- const runtime = load({- agents: async () => ({- agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'default' }],- sources: [{ connectionId: 'local', kind: 'local' }]- }),- profileRoutes: async () => [{ connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' }],- storage: {- get: async key => key === 'bot-meta' ? { default: { title: 'Local' } } : null,- set: async (key, value) => writes.push([key, value])- }- })-- const migrated = await runtime.context.__race.migrateBotMeta({- get: async key => key === 'bot-meta' ? { default: { title: 'Local' } } : null,- remove: async () => undefined,- set: async (key, value) => writes.push([key, value])- })- assert.equal(migrated, true)- assert.deepEqual(Object.keys(runtime.context.__race.$botMeta.get()), ['local::default'])- assert.deepEqual(writes.map(([key]) => key), ['bot-meta-v2', 'bot-meta-v2-migrated'])-})--test('migration rolls back routes when a later v1 profile has no local route', async () => {- const runtime = load({- agents: async () => ({- agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'first' }],- sources: [{ connectionId: 'local', kind: 'local' }]- }),- profileRoutes: async () => [- { connectionId: 'local', mode: 'local', profile: 'first', targetProfile: 'backend-first' }- ]- })--- const migrated = await runtime.context.__race.migrateBotMeta({- get: async key => key === 'bot-meta'- ? { first: { title: 'First' }, missing: { title: 'Missing' } }- : null,- set: async () => assert.fail('storage must not be written before every route is proven')- })-- assert.equal(migrated, false)- assert.equal(runtime.context.__race.migratedLocalRoutes.size, 0)- assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {- first: { title: 'First' },- missing: { title: 'Missing' }- })-})--test('failed normal v2 successor commit preserves the last committed generation on reload', async () => {- const committed = {- 'remote-a::default': { title: 'B' }- }- const storage = recordingStorage(- {- 'bot-meta-v2': committed,- 'bot-meta-v2-migrated': true- },- 'bot-meta-v2-migrated',- [],- 1- )- const runtime = load({- requestProfile: async () => ({ applied: { ui_meta: true } }),- storage- })- runtime.context.__race.setPluginStorage(storage)- assert.equal(await runtime.context.__race.migrateBotMeta(storage), true)-- await runtime.context.__race.saveBotMeta(remoteBot, { title: 'D' })-- const reloaded = load({ storage })- assert.equal(await reloaded.context.__race.migrateBotMeta(storage), true)- assert.deepEqual(- JSON.parse(JSON.stringify(reloaded.context.__race.$botMeta.get())),- committed- )-})--test('failed marker commit rolls persisted v2 back and reload keeps v1 authoritative', async () => {- const storage = recordingStorage(- { 'bot-meta': { first: { title: 'First' } } },- 'bot-meta-v2-migrated'- )- const options = {- agents: async () => ({- agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'first' }],- sources: [{ connectionId: 'local', kind: 'local' }]- }),- profileRoutes: async () => [- { connectionId: 'local', mode: 'local', profile: 'first', targetProfile: 'backend-first' }- ],- storage- }- const runtime = load(options)-- const migrated = await runtime.context.__race.migrateBotMeta(storage)-- assert.equal(migrated, false)- assert.equal(runtime.context.__race.migratedLocalRoutes.size, 0)- assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {- first: { title: 'First' }- })- assert.deepEqual(storage.operations.map(operation => operation.slice(0, 2)), [- ['remove', 'bot-meta-v2-migrated'],- ['set', 'bot-meta-v2'],- ['set', 'bot-meta-v2-migrated'],- ['remove', 'bot-meta-v2-migrated'],- ['remove', 'bot-meta-v2']- ])-- const reloaded = load(options)- const acceptedAfterReload = await reloaded.context.__race.migrateBotMeta(storage)-- assert.equal(acceptedAfterReload, false)- assert.deepEqual(JSON.parse(JSON.stringify(reloaded.context.__race.$botMeta.get())), {- first: { title: 'First' }- })-})--test('failed marker and failed v2 cleanup still reload v1 instead of markerless v2', async () => {- const storage = recordingStorage(- { 'bot-meta': { first: { title: 'Rollback' } } },- 'bot-meta-v2-migrated',- ['bot-meta-v2']- )- const options = {- agents: async () => ({- agents: [{ connectionId: 'local', connectionKind: 'local', profile: 'first' }],- sources: [{ connectionId: 'local', kind: 'local' }]- }),- profileRoutes: async () => [- { connectionId: 'local', mode: 'local', profile: 'first', targetProfile: 'backend-first' }- ],- storage- }- const runtime = load(options)-- assert.equal(await runtime.context.__race.migrateBotMeta(storage), false)-- const reloaded = load(options)- assert.equal(await reloaded.context.__race.migrateBotMeta(storage), false)- assert.deepEqual(JSON.parse(JSON.stringify(reloaded.context.__race.$botMeta.get())), {- first: { title: 'Rollback' }- })-})--test('crash-window v2 write without a marker reloads v1 rollback data', async () => {- const storage = recordingStorage({- 'bot-meta': { first: { title: 'Rollback' } },- 'bot-meta-v2': { 'local::first': { title: 'Crash window' } }- })- const runtime = load({ storage })-- assert.equal(await runtime.context.__race.migrateBotMeta(storage), false)- assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {- first: { title: 'Rollback' }- })-})--test('v1 metadata is not projected onto same-name bots in a multi-source topology', async () => {- const writes = []- const runtime = load({- agents: async () => ({- agents: [- { connectionId: 'local', connectionKind: 'local', profile: 'default' },- { connectionId: 'remote-a', connectionKind: 'remote', profile: 'default' }- ],- sources: [- { connectionId: 'local', kind: 'local' },- { connectionId: 'remote-a', kind: 'remote' }- ]- }),- profileRoutes: async () => [- { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },- remoteBot.route- ]- })-- const migrated = await runtime.context.__race.migrateBotMeta({- get: async key => key === 'bot-meta' ? { default: { title: 'Legacy local' } } : null,- set: async (key, value) => writes.push([key, value])- })-- assert.equal(migrated, false)- assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {- default: { title: 'Legacy local' }- })- assert.deepEqual(writes, [])-})--test('bot-meta-v2 is authoritative only with its persisted commit marker', async () => {- const runtime = load()- const v2 = {- 'remote-a::default': { title: 'A' },- 'remote-b::default': { title: 'B' }- }-- const migrated = await runtime.context.__race.migrateBotMeta({- get: async key => key === 'bot-meta-v2'- ? v2- : key === 'bot-meta-v2-migrated'- ? true- : null,- set: async () => assert.fail('existing v2 must not be rewritten during hydration')- })-- assert.equal(migrated, true)- assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), v2)-})--test('markerless bot-meta-v2 is ignored on reload', async () => {- const runtime = load()- const markerlessV2 = { 'remote-a::default': { title: 'Uncommitted' } }-- const migrated = await runtime.context.__race.migrateBotMeta({- get: async key => key === 'bot-meta-v2' ? markerlessV2 : null,- set: async () => assert.fail('markerless v2 must not be committed implicitly')- })-- assert.equal(migrated, false)- assert.deepEqual(JSON.parse(JSON.stringify(runtime.context.__race.$botMeta.get())), {})-})--test('selection and metadata keys do not collide for same-name connections', () => {- const runtime = load()- const { botRosterKey, botSelectionKey, botConnectionRoute } = runtime.context.__race- const botB = {- ...remoteBot,- connectionId: 'remote-b',- route: { ...remoteBot.route, connectionId: 'remote-b' }- }- const a = botConnectionRoute(remoteBot)- const b = botConnectionRoute(botB)-- assert.notEqual(botRosterKey({ ...remoteBot, route: a }), botRosterKey({ ...botB, route: b }))- assert.notEqual(botSelectionKey({ ...remoteBot, route: a }), botSelectionKey({ ...botB, route: b }))-})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.mjsdeleted file mode 100644index 27467a3f1c6..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/roster-groups.test.mjs+++ /dev/null@@ -1,276 +0,0 @@-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 = { botGroups, groupMembershipPatch, groupChatNames, groupLastActivity, groupChatMemberBots, durableGroupChatMembers, knownGroups, stripPreviewMarkdown, $groupChats };\n'- )- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return context.__groups-}--test('botGroups: normalizes canonical and legacy membership without duplicates', () => {- const { botGroups } = load()-- assert.equal(- JSON.stringify(- botGroups({ groups: [' Engineering ', '', 'Research', 'Engineering', null, 7, { name: 'Nope' }], group: 'Operations' })- ),- JSON.stringify(['Engineering', 'Research'])- )- assert.equal(JSON.stringify(botGroups({ group: 'Legacy' })), JSON.stringify(['Legacy']))- assert.equal(JSON.stringify(botGroups({ groups: [] })), JSON.stringify([]))-})--test('groupMembershipPatch: toggles one membership and keeps the legacy projection compatible', () => {- const { groupMembershipPatch } = load()- const meta = { groups: ['Engineering', 'Research'], group: 'Engineering' }-- assert.equal(- JSON.stringify(groupMembershipPatch(meta, 'Engineering', true)),- JSON.stringify({ groups: ['Engineering', 'Research'], group: 'Engineering' })- )- assert.equal(- JSON.stringify(groupMembershipPatch(meta, 'Operations', true)),- JSON.stringify({ groups: ['Engineering', 'Research', 'Operations'], group: 'Engineering' })- )- assert.equal(- JSON.stringify(groupMembershipPatch(meta, 'Engineering', false)),- JSON.stringify({ groups: ['Research'], group: 'Research' })- )- assert.equal(- JSON.stringify(groupMembershipPatch({ group: 'Legacy' }, 'Legacy', false)),- JSON.stringify({ groups: [], group: null })- )-})--test('groupChatNames: unions bot-meta groups with room records that carry members or log', () => {- const { groupChatNames } = load()- const meta = {- researcher: { group: 'Research' },- pm: { groups: ['Ops', 'Research'], group: 'Ops' },- scout: { groups: ['External'], group: 'Stale' }- }- const rooms = {- Research: { log: [], members: [] }, // already known via meta- Remote: { log: [], members: [{ name: 'spark', remoteSource: true }] },- Chatty: { log: [{ from: { kind: 'user' }, text: 'hi', at: 5 }] },- Empty: { log: [], members: [] } // nothing behind it — no row- }-- const names = groupChatNames(meta, rooms)-- assert.equal(- JSON.stringify([...names].sort()),- JSON.stringify(['Chatty', 'External', 'Ops', 'Remote', 'Research'])- )-})--test('groupLastActivity: newest room-log timestamp, 0 for silence', () => {- const { groupLastActivity } = load()-- assert.equal(groupLastActivity({ log: [{ at: 3 }, { at: 9 }] }), 9)- assert.equal(groupLastActivity({ log: [] }), 0)- assert.equal(groupLastActivity(undefined), 0)-})--test('groupChatMemberBots: seats local meta members plus stored remote descriptors, preferring live rows', () => {- const { groupChatMemberBots, $groupChats } = load()- const roster = [- { name: 'researcher' },- { name: 'builder' },- { name: 'spark', remoteSource: true, connectionId: 'c1', sourceScoped: true }- ]- $groupChats.set({- Research: {- log: [],- members: [{ name: 'spark', remoteSource: true, connectionId: 'c1', sourceScoped: true }]- }- })-- const members = groupChatMemberBots('Research', roster, {- researcher: { group: 'Research' },- builder: { groups: ['Ops', 'Research'], group: 'Ops' }- })-- assert.equal(JSON.stringify(members.map(m => m.name)), JSON.stringify(['researcher', 'builder', 'spark']))- // The LIVE roster row was preferred over the stored descriptor.- assert.equal(members[2], roster[2])-})--test('groupChatMemberBots: persisted unreachable source members stay seated next to a live same-name twin', () => {- const { groupChatMemberBots, $groupChats } = load()- const live = {- name: 'profile-a',- handle: 'profile-a-this-device',- connectionId: 'local',- connectionKind: 'local',- connectionLabel: 'This device',- sourceReachable: true- }- const stored = {- name: 'profile-a',- handle: 'profile-a-127-0-0-1-19119',- connectionId: 'loopback-19119',- connectionKind: 'remote',- connectionLabel: '127.0.0.1:19119',- remoteSource: true,- sourceScoped: true,- sourceReachable: false- }- $groupChats.set({ Research: { log: [], members: [stored] } })-- const members = groupChatMemberBots('Research', [live, stored], {- 'profile-a': { group: 'Research' }- })-- assert.equal(members.length, 2)- assert.equal(members[0], live)- assert.equal(members[1], stored)- assert.equal(members[1].handle, 'profile-a-127-0-0-1-19119')-})--test('groupChatMemberBots: stored descriptors beat presentation-only ghosts', () => {- const { groupChatMemberBots, $groupChats } = load()- const ghost = {- name: 'spark',- remoteSource: true,- sourceScoped: true,- ghost: true,- connectionId: 'c1',- connectionLabel: 'Workshop'- }- const stored = {- name: 'spark',- handle: 'spark-work',- title: 'Spark',- remoteSource: true,- sourceScoped: true,- connectionId: 'c1',- connectionLabel: 'Workshop'- }- $groupChats.set({ Research: { log: [], members: [stored] } })-- const members = groupChatMemberBots('Research', [ghost], {})-- assert.equal(members.length, 1)- assert.equal(members[0], stored)- assert.equal(members[0].handle, 'spark-work')-})--test('durableGroupChatMembers: retains active and remote source identities', () => {- const { durableGroupChatMembers } = load()- const members = durableGroupChatMembers([- {- name: 'default',- handle: 'noah',- connectionId: 'noah',- connectionKind: 'remote',- connectionLabel: 'Noah',- sourceScoped: true- },- {- name: 'default',- handle: 'maya',- connectionId: 'maya',- connectionKind: 'remote',- connectionLabel: 'Maya',- remoteSource: true,- sourceScoped: true- }- ])-- assert.equal(members.length, 2)- assert.deepEqual(- JSON.parse(JSON.stringify(members)),- [- {- name: 'default',- handle: 'noah',- connectionId: 'noah',- connectionKind: 'remote',- connectionLabel: 'Noah',- route: { connectionId: 'noah', mode: 'remote', profile: 'default', targetProfile: 'default' },- targetProfile: 'default',- remoteSource: true,- sourceScoped: true- },- {- name: 'default',- handle: 'maya',- connectionId: 'maya',- connectionKind: 'remote',- connectionLabel: 'Maya',- route: { connectionId: 'maya', mode: 'remote', profile: 'default', targetProfile: 'default' },- targetProfile: 'default',- remoteSource: true,- sourceScoped: true- }- ]- )-})--test('knownGroups: unique, trimmed, alphabetical', () => {- const { knownGroups } = load()-- const groups = knownGroups({- a: { group: 'research' },- b: { groups: ['Ops', 'research'], group: 'Ops' },- c: { groups: ['Design'] },- d: { group: '' },- e: {}- })-- assert.equal(JSON.stringify(groups), JSON.stringify(['Design', 'Ops', 'research']))-})--test('stripPreviewMarkdown: flattens bold, quotes, code, and links out of previews', () => {- const { stripPreviewMarkdown } = load()-- assert.equal(stripPreviewMarkdown('**Plan**: ship the `thing`'), 'Plan: ship the thing')- assert.equal(stripPreviewMarkdown('> quoted wisdom'), 'quoted wisdom')- assert.equal(stripPreviewMarkdown('see [the doc](https://x.y/z) now'), 'see the doc now')- assert.equal(stripPreviewMarkdown('## Heading\nbody'), 'Heading body')- assert.equal(stripPreviewMarkdown(''), '')-})--test('source contract: the roster progressively groups multiple gateways and keeps group chats distinct', () => {- assert.match(pluginSource, /function rosterGatewaySections\(/)- assert.match(pluginSource, /options\.length <= 1/)- assert.match(pluginSource, /gatewayFilter !== 'all'/)- assert.match(pluginSource, /label: 'Group chats'/)- assert.match(pluginSource, /function GroupRow\(/)- assert.match(pluginSource, /onGroup: setGrouping/)-})--test('source contract: group rows carry the needs-you badge and open via openGroupChat', () => {- assert.match(pluginSource, /needsYou: Boolean\(groupNeedsYou\[row\.name\]\)/)- assert.match(pluginSource, /onOpen: openGroupChat/)-})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.mjsdeleted file mode 100644index 989767e97a0..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/roster-preview.test.mjs+++ /dev/null@@ -1,257 +0,0 @@-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',- Tip: 'Tip',- 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 ''-}--function findNode(node, predicate) {- if (node == null || typeof node !== 'object') return null- if (Array.isArray(node)) {- for (const child of node) {- const found = findNode(child, predicate)- if (found) return found- }- return null- }- if (predicate(node)) return node- return findNode(node.props?.children, predicate)-}--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 a clean stripped DM preview without delivery furniture', () => {- const r = renderRuntime()- const tree = r.__BotRow({ bot: DM_BOT, onEdit: () => undefined })- const text = textOf(tree)- assert.match(text, /Learn-share/)- assert.doesNotMatch(text, /@manager/)- 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 — the conversation lives in the- // bot's one canonical chat, 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, /Newbie/)- assert.doesNotMatch(text, /No conversations yet/)-})--test('render: a remote default uses its gateway identity without repeating it', () => {- const r = renderRuntime()- const tree = r.__BotRow({- bot: {- connectionId: 'studio-over-ssh',- connectionLabel: 'Studio over SSH',- handle: 'default-studio-over-ssh',- name: 'default',- remoteSource: true- },- onEdit: () => undefined- })- const name = findNode(tree, node => node.type === 'span' && textOf(node) === 'Studio over SSH')- const button = findNode(tree, node => node.type === 'button' && node.props?.['aria-label'])-- assert.ok(name)- assert.ok(button)- assert.match(button.props['aria-label'], /Studio over SSH/)- assert.equal((textOf(button).match(/Studio over SSH/g) || []).length, 1)-})--test('render: BotRow previews the pinned canonical chat, not an unrelated latest session', () => {- // hermes-agent#88200: the row opens the pinned chat on click, so the- // preview must describe that same session — not the profile's most recent- // (but unrelated) activity.- const r = renderRuntime()- const tree = r.__BotRow({- bot: {- name: 'ops',- title: 'Ops',- description: '',- last_session: { id: 'scratch9', title: 'Scratch', preview: 'unrelated scratch content', last_active: 1_800_000_000 },- canonical_session: { id: 'pinned1', resolved_id: 'pinned1', title: 'Bot Chat', preview: 'pinned chat content', started_at: 1, last_active: 1_700_000_000, message_count: 5 }- },- onEdit: () => undefined- })- const text = textOf(tree)- assert.match(text, /pinned chat content/)- assert.doesNotMatch(text, /unrelated scratch content/)-})--test('previewKind: the primary profile surfaces as @hermes, never @default', () => {- // botHandle() exists so "the word 'default' never surfaces in the UI"; the- // bot-to-bot badge was rendering the raw captured profile name (#89484).- assert.equal(fromBotOf("Message from agent 'default': deploy is green"), 'hermes')-})--test('previewKind: a named profile keeps its own handle', () => {- assert.equal(fromBotOf("Message from agent 'ops': deploy is green"), 'ops')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/roster-query-retry.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/roster-query-retry.test.mjsdeleted file mode 100644index 02150f31944..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/roster-query-retry.test.mjs+++ /dev/null@@ -1,56 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// The Bots pane renders a spinner while useRoster() is isLoading and has no-// snapshot. React Query treats `retry: true` as infinite retries, which keeps-// isLoading true forever — the sidebar stays empty with no error/retry card.-// Bounded retries plus the existing 5s refetch recover SSH/sleep drops.--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: { get: () => 'default', listen: () => undefined },- gateway: { get: () => 'open', listen: () => undefined },- connectionId: { get: () => 'local', listen: () => undefined }- },- request: () => Promise.resolve({ profiles: [] })- },- sdk: new Proxy({}, { get: () => 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(`-globalThis.__roster = { ROSTER_QUERY_RETRY };-`)- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return context.__roster-}--test('roster query retries are bounded so a stalled profiles.list cannot pin the spinner', () => {- const { ROSTER_QUERY_RETRY } = load()- assert.equal(typeof ROSTER_QUERY_RETRY, 'number')- assert.ok(ROSTER_QUERY_RETRY >= 0)- assert.ok(ROSTER_QUERY_RETRY < Number.POSITIVE_INFINITY)- assert.notEqual(ROSTER_QUERY_RETRY, true)- assert.match(pluginSource, /retry:\s*ROSTER_QUERY_RETRY/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routine-deliver-target.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routine-deliver-target.test.mjsdeleted file mode 100644index 4e4fe79d0c5..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routine-deliver-target.test.mjs+++ /dev/null@@ -1,31 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--// The Create Cronjob dialog's "Send results to" target picker: source-shape-// tests in the style of the sibling routine tests (the plugin is a single-// direct file; behavior contracts are pinned via source assertions where a-// full DOM harness would be heavier than the seam warrants).-const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--test('dialog offers a delivery target picker with history and bot-chat options', () => {- assert.match(pluginSource, /Send results to/)- assert.match(pluginSource, /id: 'history', label: 'Run history only'/)- assert.match(pluginSource, /id: 'bot-chat'/)-})--test('bot-chat target sends the BARE deliver token on the profile-scoped create', () => {- // The job is created in the bot's own cron store (profile: bot), so the- // bare token resolves to that profile machine-locally — a named token- // built from a Desktop-side alias could name a profile the backend does- // not have (the #82530 alias trap). Pin the bare form.- assert.match(pluginSource, /\.\.\.\(target === 'bot-chat' \? \{ deliver: 'bot-chat' \} : \{\}\)/)- assert.doesNotMatch(pluginSource, /deliver: `bot-chat:\$\{/)-})--test('history target (default) sends no deliver param — behavior unchanged', () => {- assert.match(pluginSource, /useState\('history'\)/)- // reset() returns the picker to the default so a reopened dialog never- // inherits the previous create's target.- assert.match(pluginSource, /setTarget\('history'\)/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routine-detail.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routine-detail.test.mjsdeleted file mode 100644index 1d7e55293d3..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routine-detail.test.mjs+++ /dev/null@@ -1,205 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// Bot Mode's Cronjobs rows were inert: the only interactive controls were the-// enable switch and the hover-only delete button, so clicking a cronjob to see-// what it runs, when it runs next, or why it stopped did nothing at all. The-// gateway already ships every one of those facts with `cron.manage list`, so-// the inspector reads the record the pane is holding — no extra RPC, and no-// second mutation path beside the row's own switch and delete.--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 node = (type, props = {}) => ({ props, type })- const context = {- atom,- Button: 'Button',- Codicon: 'Codicon',- COMPOSER_AREAS: { middleware: 'middleware' },- cn: (...parts) => parts.filter(Boolean).join(' '),- Dialog: 'Dialog',- DialogContent: 'DialogContent',- DialogDescription: 'DialogDescription',- DialogFooter: 'DialogFooter',- DialogHeader: 'DialogHeader',- DialogTitle: 'DialogTitle',- document: { createElement: () => ({}), getElementById: () => null, head: { appendChild: () => undefined } },- host: { state: { profile: { listen: () => undefined } } },- jsx: node,- jsxs: node,- PALETTE_AREA: 'palette',- relativeTime: () => 'in 5 min',- Switch: 'Switch',- Tip: 'Tip',- useState: initial => [typeof initial === 'function' ? initial() : initial, () => 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(`- globalThis.__api = { RoutineDetailDialog, RoutineRow, routineDetailIssue, routineDetailRows };- `)- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return context.__api-}--/** Depth-first walk over the stubbed element tree. */-function collect(node, match, found = []) {- if (Array.isArray(node)) {- for (const child of node) collect(child, match, found)- return found- }-- if (!node || typeof node !== 'object') {- return found- }-- if (match(node)) {- found.push(node)- }-- return collect(node.props?.children, match, found)-}--function textOf(node) {- return collect(node, entry => typeof entry.props?.children === 'string')- .map(entry => entry.props.children)- .join(' | ')-}--const activeJob = {- deliver: 'bot-chat',- enabled: true,- job_id: 'job-1',- last_run_at: '2026-08-23T09:00:00Z',- last_status: 'success',- name: '[bot:notetaker] Morning digest',- next_run_at: '2026-08-23T10:00:00Z',- prompt_preview: 'Summarize yesterday and post it.',- repeat: 'forever',- schedule: 'every 1440m'-}--// ── the facts the row never showed ──────────────────────────────────────────--test('detail rows only carry fields the gateway actually sent', () => {- const { routineDetailRows } = load()- const rows = routineDetailRows({ enabled: true, job_id: 'bare', name: 'Bare', schedule: 'every 1h' })- const labels = rows.map(row => row.label)-- // A job that has never run carries no last_run_at/last_status/model; those- // rows must be absent rather than rendering an empty or "undefined" value.- assert.ok(!labels.includes('Last run'))- assert.ok(!labels.includes('Last result'))- assert.ok(!labels.includes('Model'))- assert.ok(rows.every(row => row.value.trim().length > 0))-})--test('an active job reports its next run; a paused one does not claim one', () => {- const { routineDetailRows } = load()- const value = (rows, label) => rows.find(row => row.label === label)?.value-- const active = routineDetailRows(activeJob)- assert.equal(value(active, 'Status'), 'Active')- assert.ok(value(active, 'Next run'))-- const paused = routineDetailRows({ ...activeJob, enabled: false, state: 'paused' })- assert.equal(value(paused, 'Status'), 'Paused')- assert.equal(value(paused, 'Next run'), undefined, 'a paused job has no next run to promise')- assert.ok(value(paused, 'Last run'), 'history it does have is still shown')-})--test('the raw schedule appears only when the humanized label dropped something', () => {- const { routineDetailRows } = load()- const raw = rows => rows.find(row => row.label === 'Schedule (raw)')?.value-- // "every 1440m" humanizes to "Daily" — the raw form still carries the cadence.- assert.equal(raw(routineDetailRows(activeJob)), 'every 1440m')- // A schedule the label passes through unchanged would only be duplicated.- const passthrough = routineDetailRows({ ...activeJob, schedule: '0 9 * * 1-5' })- assert.equal(raw(passthrough), undefined)- assert.equal(passthrough.find(row => row.label === 'Schedule')?.value, '0 9 * * 1-5')-})--test('a failing or scheduler-paused job explains itself, in failure order', () => {- const { routineDetailIssue } = load()-- assert.equal(routineDetailIssue(activeJob), null)- assert.equal(routineDetailIssue({ ...activeJob, paused_reason: 'too many failures' }), 'too many failures')- assert.equal(- routineDetailIssue({ ...activeJob, last_delivery_error: 'telegram 401', paused_reason: 'too many failures' }),- 'telegram 401'- )- assert.equal(- routineDetailIssue({- ...activeJob,- last_delivery_error: 'telegram 401',- last_fire_error: 'model timeout',- paused_reason: 'too many failures'- }),- 'model timeout',- 'the run that never happened outranks the delivery of a run that did'- )-})--// ── the row is reachable ────────────────────────────────────────────────────--test('the row title is a button that opens THIS job', () => {- const { RoutineRow } = load()- const opened = []- const tree = RoutineRow({ job: activeJob, onOpen: job => opened.push(job), owner: 'notetaker' })- const buttons = collect(tree, entry => entry.type === 'button' && typeof entry.props.onClick === 'function')-- assert.ok(buttons.length >= 1, 'the row exposes at least one activation target')- const [title] = buttons- title.props.onClick()- assert.deepEqual(opened, [activeJob])-})--test('opening the details cannot swallow the switch or the delete control', () => {- const { RoutineRow } = load()- const tree = RoutineRow({ job: activeJob, onOpen: () => undefined, owner: 'notetaker' })- const openers = collect(tree, entry => entry.props?.title === 'Cronjob details')-- assert.equal(openers.length, 1)- // The switch and the delete button must not live INSIDE the opener: a click- // on them would otherwise also open the inspector (and nested interactive- // elements are invalid markup).- assert.deepEqual(collect(openers[0], entry => entry.type === 'Switch'), [])- assert.deepEqual(collect(openers[0], entry => entry.type === 'Tip'), [])- assert.equal(collect(tree, entry => entry.type === 'Switch').length, 1)-})--// ── the inspector ───────────────────────────────────────────────────────────--test('the inspector renders the job’s instruction and its failure', () => {- const { RoutineDetailDialog } = load()- const job = { ...activeJob, last_fire_error: 'model timeout' }- const rendered = textOf(RoutineDetailDialog({ job, onClose: () => undefined, open: true }))-- assert.match(rendered, /Morning digest/)- assert.match(rendered, /Summarize yesterday and post it\./)- assert.match(rendered, /model timeout/)- assert.doesNotMatch(rendered, /\[bot:notetaker\]/, 'the routing tag is plumbing, not a title')-})--test('the inspector stays shut without a job to inspect', () => {- const { RoutineDetailDialog } = load()-- assert.equal(RoutineDetailDialog({ job: null, onClose: () => undefined, open: true }).props.open, false)- assert.equal(RoutineDetailDialog({ job: activeJob, onClose: () => undefined, open: false }).props.open, false)- assert.equal(RoutineDetailDialog({ job: activeJob, onClose: () => undefined, open: true }).props.open, true)-})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.mjsdeleted file mode 100644index a9793215400..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routine-owner.test.mjs+++ /dev/null@@ -1,146 +0,0 @@-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 requests = []- const node = (type, props = {}) => ({ props, type })- const context = {- atom,- Button: 'Button',- Codicon: 'Codicon',- cn: (...parts) => parts.filter(Boolean).join(' '),- Dialog: 'Dialog',- DialogContent: 'DialogContent',- DialogDescription: 'DialogDescription',- DialogFooter: 'DialogFooter',- DialogHeader: 'DialogHeader',- DialogTitle: 'DialogTitle',- host: {- state: {- profile: { get: () => 'ops', listen: () => undefined },- gateway: { get: () => 'open', listen: () => undefined }- },- request: async (method, params) => {- requests.push({ method, params })- return { jobs: [] }- },- requestProfile: async (route, method, params) => {- requests.push({ method, params, route })- return { jobs: [] }- },- notify: () => undefined,- notifyError: () => undefined- },- jsx: node,- jsxs: node,- queryClient: {- invalidateQueries: async options => invalidations.push(options)- },- relativeTime: () => 'in 5 min',- Switch: 'Switch',- Tip: 'Tip',- useState: initial => [typeof initial === 'function' ? initial() : initial, () => undefined],- 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 = { RoutineRow, routineCreateTarget, invalidateRoutineOwner };\n')- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return { ...context, invalidations, requests }-}--/** Depth-first search over the stubbed element tree. */-function find(node, match) {- if (Array.isArray(node)) {- for (const child of node) {- const hit = find(child, match)- if (hit) return hit- }- return null- }-- if (!node || typeof node !== 'object') {- return null- }-- return match(node) ? node : find(node.props?.children, match)-}--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('a row mutation addresses — and invalidates — the owner that rendered it', async () => {- const runtime = load()- const row = runtime.__routineOwners.RoutineRow({- job: { enabled: true, job_id: 'digest', name: '[bot:ops] Digest', schedule: 'every 1h' },- onOpen: () => undefined,- owner: 'ops'- })-- const toggle = find(row, node => node.type === 'Switch')- assert.ok(toggle, 'the row still exposes its enable switch')-- // 'ops' is the row's owner while the live gateway may already be on another- // bot: both the RPC and the cache eviction must name the owner, not the- // ambient profile.- await toggle.props.onCheckedChange(false)-- assert.deepEqual(plain(runtime.requests), [- { method: 'cron.manage', params: { action: 'pause', name: 'digest', profile: 'ops' } }- ])- assert.deepEqual(plain(runtime.invalidations), [- { queryKey: ['hermes-bots', 'routines', 'ops'], exact: true }- ])-})--test('source contract: create mutations and dialog state retain one owner', () => {- assert.match(- pluginSource,- /function CreateRoutineDialog\(\{ bot, open, onClose \}\)[\s\S]*await requestForBot\(bot, 'cron\.manage',[\s\S]*\.\.\.\(profile \? \{ profile \} : \{\}\)[\s\S]*await invalidateRoutineOwner\(bot\)/- )- assert.match(pluginSource, /const \[createOwner, setCreateOwner\] = useState\(null\)/)- assert.match(pluginSource, /const openCreate = \(\) => \{[\s\S]*setCreateOwner\(owner\)[\s\S]*setCreateOpen\(true\)/)- assert.match(pluginSource, /const createTarget = owner \? routineCreateTarget\(createOwner, bot\) : null/)- // key must be the jsx() THIRD argument (a `key:` prop is silently ignored- // by the react/jsx-runtime and the dialog would keep stale per-bot state).- assert.match(pluginSource, /jsx\(CreateRoutineDialog, \{[\s\S]*?\}, createTarget\)/)- assert.doesNotMatch(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.mjsdeleted file mode 100644index ed2de91bf4b..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routine-prompt.test.mjs+++ /dev/null@@ -1,190 +0,0 @@-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]*requestForBot\(bot, 'cron\.manage'/- )-})--test('regression: Create Cronjob passes the active profile to routinePrompt', () => {- assert.match(pluginSource, /prompt: routinePrompt\(profile, 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 filediff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-dialog-owner-label.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-dialog-owner-label.test.mjsdeleted file mode 100644index 70618002cd0..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-dialog-owner-label.test.mjs+++ /dev/null@@ -1,31 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'--// #93572: CreateRoutineDialog's "Send results to" picker built its label with-// `displayName({ name: bot }, $botMeta.get()[bot])`. The dialog's `bot` prop-// is routineCreateTarget() output — an owner OBJECT for roster-scoped bots —-// so the label rendered "[object Object]" and the meta lookup keyed the map-// with an object. The label must resolve owner objects through the-// object-aware botRosterMeta() path and only wrap bare strings.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--test('CreateRoutineDialog bot-chat label resolves owner objects via botRosterMeta', () => {- const start = pluginSource.indexOf('function CreateRoutineDialog(')- assert.ok(start >= 0, 'CreateRoutineDialog must exist')- const dialog = pluginSource.slice(start, start + 8000)-- const label = dialog.match(/\{ id: 'bot-chat', label: `\$\{displayName\(([^`]+)\)\}/)- assert.ok(label, 'bot-chat picker label must be built through displayName()')-- // Owner objects pass through untouched; only bare strings are wrapped.- assert.match(label[1], /typeof bot === 'string' \? \{ name: bot \} : bot/)- // Meta lookup must go through the object-aware resolver, never index- // $botMeta with a possibly-object key.- assert.match(label[1], /botRosterMeta\(bot, \$botMeta\.get\(\)\)/)- assert.ok(- !/\$botMeta\.get\(\)\[bot\]/.test(dialog),- 'the dialog must not index bot meta with the raw bot prop'- )-})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.mjsdeleted file mode 100644index a83b2ac6821..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-error.test.mjs+++ /dev/null@@ -1,110 +0,0 @@-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('regression: a profile-scoped list shows every job owned by that bot profile', () => {- const profileJobs = [- { name: 'ordinary profile cronjob', job_id: 'legacy' },- { name: '[bot:ops] Bot Mode routine', job_id: 'routine' }- ]- const view = load().__api.selectRoutineJobs({ jobs: profileJobs, scoped: 'ops' }, null, [], 'ops')-- assert.deepEqual(- Array.from(view.jobs, job => job.job_id),- ['legacy', 'routine']- )-})--test('compatibility: an unmarked list keeps tag filtering for older gateways', () => {- const profileJobs = [- { name: 'ordinary launch-profile cronjob', job_id: 'legacy' },- { name: '[bot:ops] Bot Mode routine', job_id: 'routine' }- ]- const view = load().__api.selectRoutineJobs({ jobs: profileJobs }, null, [], 'ops')-- assert.deepEqual(- Array.from(view.jobs, job => job.job_id),- ['routine']- )-})--test('compatibility: a stale scope marker cannot leak another profile\'s jobs', () => {- const profileJobs = [- { name: 'ordinary research cronjob', job_id: 'research' },- { name: '[bot:ops] Bot Mode routine', job_id: 'routine' }- ]- const view = load().__api.selectRoutineJobs({ jobs: profileJobs, scoped: 'research' }, null, [], 'ops')-- assert.deepEqual(- Array.from(view.jobs, job => job.job_id),- ['routine']- )-})--test('regression: untagged legacy cronjobs remain visible only on the default bot', () => {- const legacy = { name: 'Existing reminder', job_id: 'legacy' }- const api = load().__api-- assert.deepEqual(api.selectRoutineJobs({ jobs: [legacy] }, null, [], 'default').jobs, [legacy])- assert.deepEqual(api.selectRoutineJobs({ jobs: [legacy] }, null, [], 'ops').jobs, [])-})--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-filter-hint.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-filter-hint.test.mjsdeleted file mode 100644index 1df7adacc8c..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-filter-hint.test.mjs+++ /dev/null@@ -1,56 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// UX improvement: when a bot's cron store HAS jobs but none are namespaced-// `[bot:<name>]` for the active bot, the Routines pane now explains why it's-// empty instead of showing the generic empty state with no hint.--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 = { routineFilterHint };\n')- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return context-}--test('hint: null when the active bot already has tagged jobs', () => {- const all = [{ name: '[bot:ops] Morning', job_id: '1' }]- assert.equal(load().__api.routineFilterHint(all, all), null)-})--test('hint: null when the store is genuinely empty', () => {- assert.equal(load().__api.routineFilterHint([], []), null)- assert.equal(load().__api.routineFilterHint(undefined, []), null)-})--test('hint: explains hidden jobs when store has jobs but none match the bot', () => {- const all = [- { name: '[bot:research] Digest', job_id: '2' },- { name: 'untagged job', job_id: '3' }- ]- const hint = load().__api.routineFilterHint(all, [])- assert.ok(hint)- assert.match(hint, /tagged for this bot/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-pane-owner.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-pane-owner.test.mjsdeleted file mode 100644index 12dd8b89a90..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-pane-owner.test.mjs+++ /dev/null@@ -1,270 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// The Cronjobs pane read the shared roster with a bare `$lastRoster.get()`-// while rendering. BotsPane owns the roster fetch, so whenever this pane-// mounted before the roster hydrated (fresh boot ordering, renderer reload-// resetting the atoms) it captured an empty snapshot forever: the pane stayed-// pinned on "Cronjobs are unavailable until this agent appears in the-// roster." even for a focused bot chat whose exact roster row existed, and-// Create Cronjob silently no-oped (#94483).-//-// Contract:-// 1. RoutinesPane must SUBSCRIBE to the roster (like every other consumer-// via useValue), so hydration/roster changes can re-render the pane.-// 2. Once the owner resolves, the pane actually renders its content and a-// working create affordance instead of staying on the placeholder.-// 3. A complete (authoritative) focused owner with no exact roster row still-// fails closed — the subscription fix must not loosen identity matching.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--const NL = String.fromCharCode(10)--function stripImports(source) {- const out = []- let inImportBlock = false- for (const line of source.split(NL)) {- if (inImportBlock) {- if (line.includes(' from ')) inImportBlock = false- continue- }- if (line.startsWith('import ')) {- if (!line.includes(' from ')) inImportBlock = true- continue- }- out.push(line)- }- return out.join(NL)-}--function makeAtom(initial) {- const slot = {- value: initial,- listeners: new Set(),- get: () => slot.value,- set: next => {- slot.value = next- for (const fn of [...slot.listeners]) fn()- },- listen: fn => {- slot.listeners.add(fn)- return () => slot.listeners.delete(fn)- }- }- return slot-}--const UNAVAILABLE = 'Cronjobs are unavailable until this agent appears in the roster.'--// Function components are lazily expanded (React would call them during-// render); a component that explodes under the stubs contributes an opaque-// subtree rather than failing the whole traversal.-function expandNode(node, depth) {- if (typeof node.type !== 'function' || depth > 12) return null- try {- return node.type(node.props)- } catch {- return null- }-}--function collectStrings(node, out = [], depth = 0) {- if (node == null || depth > 24) return out- if (Array.isArray(node)) {- for (const child of node) collectStrings(child, out, depth + 1)- return out- }- if (typeof node === 'object') {- if (!node.props) return out- if (typeof node.type === 'function') {- collectStrings(expandNode(node, depth), out, depth + 1)- return out- }- collectStrings(node.props.children, out, depth + 1)- return out- }- if (typeof node === 'string' || typeof node === 'number') out.push(String(node))- return out-}--/** Depth-first search over the stubbed element tree. */-function findNode(node, match, depth = 0) {- if (node == null || depth > 24) return null- if (Array.isArray(node)) {- for (const child of node) {- const hit = findNode(child, match, depth + 1)- if (hit) return hit- }- return null- }- if (!node || typeof node !== 'object' || !node.props) return null- if (match(node)) return node- if (typeof node.type === 'function') return findNode(expandNode(node, depth), match, depth + 1)- return findNode(node.props.children, match, depth + 1)-}--function runtime({ focusedOwner, jobs = [] } = {}) {- const subscribed = new Set()-- // Minimal React hook memory: one slot list per runtime, indexed by call- // order within a render pass. `render()` starts a fresh pass so repeated- // calls model re-renders while setters keep their values across them.- const hooks = []- let hookIndex = 0-- const context = {- atom: initial => makeAtom(initial),- sdk: new Proxy({}, { get: () => undefined }),- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- profileColor: () => '#64748b',- haptic: () => undefined,- queryClient: {},- relativeTime: () => '',- cn: (...parts) => parts.filter(Boolean).join(' '),- Button: 'Button',- Checkbox: 'Checkbox',- Codicon: 'Codicon',- ContextMenu: 'ContextMenu',- ContextMenuContent: 'ContextMenuContent',- ContextMenuItem: 'ContextMenuItem',- ContextMenuSeparator: 'ContextMenuSeparator',- ContextMenuTrigger: 'ContextMenuTrigger',- ConfirmDialog: 'ConfirmDialog',- CopyButton: 'CopyButton',- Dialog: 'Dialog',- DialogContent: 'DialogContent',- DialogDescription: 'DialogDescription',- DialogFooter: 'DialogFooter',- DialogHeader: 'DialogTitle-header',- DialogTitle: 'DialogTitle',- DropdownMenu: 'DropdownMenu',- DropdownMenuContent: 'DropdownMenuContent',- DropdownMenuItem: 'DropdownMenuItem',- DropdownMenuSeparator: 'DropdownMenuSeparator',- DropdownMenuTrigger: 'DropdownMenuTrigger',- EmptyState: 'EmptyState',- GlyphSpinner: 'GlyphSpinner',- Input: 'Input',- ScrollArea: 'ScrollArea',- SearchField: 'SearchField',- Select: 'Select',- SelectContent: 'SelectContent',- SelectItem: 'SelectItem',- SelectTrigger: 'SelectTrigger',- SelectValue: 'SelectValue',- Switch: 'Switch',- Textarea: 'Textarea',- Tip: 'Tip',- jsx: (type, props = {}) => ({ type, props }),- jsxs: (type, props = {}) => ({ type, props }),- // Minimal React stand-ins. useValue mirrors the SDK contract: registering- // the dependency is exactly what lets a later store write re-render us.- useState: initial => {- const i = hookIndex++- if (!(i in hooks)) hooks[i] = typeof initial === 'function' ? initial() : initial- const setValue = value => {- hooks[i] = typeof value === 'function' ? value(hooks[i]) : value- }- return [hooks[i], setValue]- },- useEffect: () => undefined,- useMemo: fn => fn(),- useRef: value => ({ current: value }),- useCallback: fn => fn,- useQuery: () => ({- data: { jobs, scoped: 'research' },- error: null,- isLoading: false,- refetch: () => {}- }),- useValue: value => {- if (value && typeof value.listen === 'function') {- value.listen(() => {})- subscribed.add(value)- }- return value?.get ? value.get() : value- },- host: {- request: async () => ({}),- state: {- connectionId: { get: () => 'local', listen: () => undefined },- profile: { get: () => 'research', listen: () => undefined },- ...(focusedOwner ? { focusedSessionOwner: focusedOwner } : {})- }- }- }-- const marker = [NL + 'globalThis.__pane = { RoutinesPane, $lastRoster };'].join('')- const source = stripImports(pluginSource)- .replace('export default {', 'globalThis.plugin = {')- .concat(marker)-- vm.runInNewContext(source, context, { filename: 'plugin.js' })-- const render = () => {- hookIndex = 0- return context.__pane.RoutinesPane()- }-- return { render, $lastRoster: context.__pane.$lastRoster, subscribed }-}--test('regression: the pane follows the roster hydrating after mount', () => {- const focusedOwner = makeAtom({ connectionId: 'local', profile: 'research' })- const { render, $lastRoster, subscribed } = runtime({- focusedOwner,- jobs: [{ job_id: 'j-1', name: 'Report', schedule: 'every 1h', state: 'scheduled', enabled: true }]- })-- // Mount order: pane first, roster fetch lands afterwards (BotsPane owns- // the fetch). First paint must be the fail-closed placeholder...- const before = collectStrings(render()).join(' ')- assert.ok(before.includes(UNAVAILABLE))-- // ...but the pane must be wired to the store so the write can re-render it.- assert.ok(subscribed.has($lastRoster), 'RoutinesPane must subscribe to $lastRoster (bare .get() captured an empty roster forever)')- assert.ok($lastRoster.listeners.size >= 1, 'hydration must have a live path to re-render the pane')-- // Roster arrives: the same focused bot chat now resolves to its exact row- // and the pane paints real content without any unrelated state change.- $lastRoster.set([{ name: 'research', connectionId: 'local' }])- const after = collectStrings(render()).join(' ')- assert.ok(!after.includes(UNAVAILABLE))- assert.ok(after.includes('Cronjobs'), 'pane should render its header once the owner resolves')- assert.ok(after.includes('Report'), 'the scheduled job row should paint after the roster hydrates')-})--test('create affordance appears once the owner resolves', () => {- const focusedOwner = makeAtom({ connectionId: 'local', profile: 'research' })- const { render, $lastRoster } = runtime({ focusedOwner, jobs: [] })-- $lastRoster.set([{ name: 'research', connectionId: 'local' }])- const tree = render()-- // The reported "Create Cronjob silently no-ops" symptom starts here: while- // the owner is stuck unresolved the pane never offers any create control.- // (Dialog internals are owned by the routine-create flow tests.)- const create = findNode(tree, node => {- if (node.type !== 'Button') return false- return collectStrings(node).join(' ') === 'Create Cronjob'- })- assert.ok(create, 'the empty-state Create Cronjob button should exist once the owner resolves')- assert.equal(typeof create.props.onClick, 'function')-- const headerTip = findNode(tree, node => node.type === 'Tip' && node.props?.label === 'New Cronjob')- assert.ok(headerTip, 'the header New Cronjob affordance should exist once the owner resolves')- assert.equal(typeof headerTip.props.children?.props?.onClick, 'function')-})--test('a complete focused owner without an exact roster row still fails closed', () => {- const focusedOwner = makeAtom({ connectionId: 'local', profile: 'ghost-profile' })- const { render, $lastRoster } = runtime({ focusedOwner })-- $lastRoster.set([{ name: 'research', connectionId: 'local' }])- const text = collectStrings(render()).join(' ')- assert.ok(text.includes(UNAVAILABLE))-})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.mjsdeleted file mode 100644index b81fa7cee3a..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-pause-failure.test.mjs+++ /dev/null@@ -1,99 +0,0 @@-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.mjsdeleted file mode 100644index fd4e52b9613..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-profile-scope.test.mjs+++ /dev/null@@ -1,31 +0,0 @@-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, key\]/)- assert.match(source, /queryFn: \(\) => loadRoutines\(bot\)/)-})--test('RoutineRow toggle and create forward the profile scope', () => {- // RoutineRow pause/resume- assert.match(source, /requestForBot\(owner, 'cron\.manage', \{ action, name: job\.job_id, \.\.\.\(profile \? \{ profile \} : \{\}\) \}\)/)- // create- assert.match(source, /requestForBot\(bot, 'cron\.manage',[\s\S]*\.\.\.\(profile \? \{ profile \} : \{\}\)/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-rpc-error.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-rpc-error.test.mjsdeleted file mode 100644index c334eff125e..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-rpc-error.test.mjs+++ /dev/null@@ -1,103 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// loadRoutines -> requestForBot. A rejected JSON-RPC value that is not an-// Error (or an Error whose `name` is not a string) used to crash React 19's-// formatter: `(e.name || '').trim` is not a function. The Routines pane then-// died instead of showing "Could not load cronjobs" (#94471).--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function load(request, requestProfile) {- 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 host = { request, state: { profile: { listen: () => undefined } } }- if (requestProfile) {- host.requestProfile = requestProfile- }- const context = {- atom,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host- }- 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 = { asRpcError, loadRoutines, requestForBot };\n')- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return context-}--function react19Format(error) {- return `${(error.name || '').trim()}: ${error.message}`-}--test('regression: a non-Error cron.manage rejection becomes a string-named Error', async () => {- const runtime = load(async () => {- const failure = { name: 32000, message: 'cron.manage failed', code: -32603 }- throw failure- })-- await assert.rejects(- () => runtime.__routines.loadRoutines('research'),- error => {- assert.equal(typeof error.name, 'string')- assert.doesNotThrow(() => react19Format(error))- assert.match(String(error.message), /cron.manage failed/)- assert.equal(error.cause.name, 32000)- return true- }- )-})--test('regression: Error with a numeric name is coerced before React 19 format', () => {- const weird = new Error('down')- Object.defineProperty(weird, 'name', { value: 13, configurable: true })- const coerced = load(async () => {}).__routines.asRpcError(weird, 'fallback')- assert.equal(typeof coerced.name, 'string')- assert.doesNotThrow(() => react19Format(coerced))- assert.match(String(coerced.message), /down/)-})--test('regression: a frozen non-string Error name is copied, not mutated in place', () => {- const weird = new Error('down')- Object.defineProperty(weird, 'name', { value: 13, configurable: false, writable: false })- const coerced = load(async () => {}).__routines.asRpcError(weird, 'fallback')- assert.notEqual(coerced, weird)- assert.equal(typeof coerced.name, 'string')- assert.doesNotThrow(() => react19Format(coerced))- assert.match(coerced.message, /down/)-})--test('regression: a sealed Error with a numeric name is copied, not mutated', () => {- const weird = new Error('sealed')- Object.defineProperty(weird, 'name', { value: 32000, configurable: true, writable: true })- Object.seal(weird)- const coerced = load(async () => {}).__routines.asRpcError(weird, 'fallback')- assert.notEqual(coerced, weird)- assert.equal(typeof coerced.name, 'string')- assert.doesNotThrow(() => react19Format(coerced))- assert.match(String(coerced.message), /sealed/)- // Assignment would have succeeded on a sealed writable property; we still- // copy so React 19 never sees a numeric name even if mutation is possible.- assert.equal(weird.name, 32000)-})--test('regression: a real Error passes through unchanged', () => {- const original = new Error('gateway rejected the pause')- const coerced = load(async () => {}).__routines.asRpcError(original, 'fallback')- assert.equal(coerced, original)- assert.equal(coerced.name, 'Error')-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/routines-selected-bot.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/routines-selected-bot.test.mjsdeleted file mode 100644index f7c2f7fb3ee..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/routines-selected-bot.test.mjs+++ /dev/null@@ -1,180 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #89625 follow-up (PR #89637 residual): nanostores' `.listen()` never replays-// the current value the way `.subscribe()` does, so the $focusedBotProfile-// listener in register() only kept $selectedBot current from the moment it was-// attached. A disable -> profile switch -> re-enable cycle (Settings > Plugins)-// left $selectedBot pointed at whichever bot was active before the plugin was-// disabled. bindProfileSync() reseeds $selectedBot from the store's CURRENT-// value before attaching the listener, so every register() starts in sync.-//-// #94516 regression: the same ladder must not dead-end the Routines pane.-// The SDK's focusedSessionOwner store fails closed to null whenever the-// focused session has no unique bot owner (normal chat, ambiguous owner-// hints) — the common case while the user browses the Bots pane. The pane-// must fall back to the bot the user clicked in the roster (the previously-// working scope) instead of pinning every bot on the "Cronjobs are-// unavailable until this agent appears in the roster." placeholder.--const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function load({ focusedSessionOwnerSupported = false, focusedSessionOwner = 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 state = { profile: { listen: () => undefined } }- if (focusedSessionOwnerSupported) {- state.focusedSessionOwner = atom(focusedSessionOwner)- }- const context = {- atom,- PALETTE_AREA: 'palette',- COMPOSER_AREAS: { middleware: 'middleware' },- document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },- host: { state }- }- 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(`- globalThis.__api = {- bindProfileSync,- resolveRoutineOwner: typeof resolveRoutineOwner === 'function' ? resolveRoutineOwner : undefined,- $selectedBot- };- `)- vm.runInNewContext(source, context, { filename: 'plugin.js' })- return context-}--// Mimic real nanostores atom semantics (get + non-replaying listen) — not a-// mock that assumes the fix — so this fails honestly if bindProfileSync-// regresses to a plain, non-reseeding listen().-function fakeProfileStore(initial) {- let value = initial- const listeners = new Set()- return {- get: () => value,- set: next => {- value = next- for (const listener of listeners) listener(value)- },- listen: listener => {- listeners.add(listener)- return () => listeners.delete(listener)- }- }-}--test('regression: re-enabling after a profile switch while disabled resyncs, not stays stale', () => {- const { bindProfileSync, $selectedBot } = load().__api- const profile = fakeProfileStore('blog-writer')-- const unbind1 = bindProfileSync(profile)- assert.equal($selectedBot.get(), 'blog-writer', 'reseeded to the live profile on first bind')-- unbind1() // plugin disabled: listener torn down- profile.set('researcher') // profile changes while nothing is listening-- bindProfileSync(profile) // plugin re-enabled: register() runs again- assert.equal($selectedBot.get(), 'researcher', 'reseeded to the live profile on re-bind, not left stale')-})--test('unit: bindProfileSync keeps forwarding live profile changes after (re)binding', () => {- const { bindProfileSync, $selectedBot } = load().__api- const profile = fakeProfileStore('default')-- bindProfileSync(profile)- profile.set('researcher')- assert.equal($selectedBot.get(), 'researcher', 'live changes still flow through the listener')-})--test('unit: bindProfileSync follows connection changes for the same profile name', () => {- const { bindProfileSync, $selectedBot } = load().__api- const owner = fakeProfileStore({ connectionId: 'source-a', profile: 'default' })-- bindProfileSync(owner)- assert.equal($selectedBot.get(), 'source-a::default')-- owner.set({ connectionId: 'source-b', profile: 'default' })- assert.equal($selectedBot.get(), 'source-b::default')-})--test('unit: an empty/non-string current value is not seeded into $selectedBot', () => {- const { bindProfileSync, $selectedBot } = load().__api- const before = $selectedBot.get()- bindProfileSync(fakeProfileStore(''))- assert.equal($selectedBot.get(), before, 'falsy current value leaves $selectedBot untouched')-})--test('unit: an authoritative focused owner missing from the roster fails closed', () => {- const { resolveRoutineOwner } = load().__api- const roster = [{- connectionId: 'source-a',- name: 'default',- remoteSource: true,- sourceScoped: true- }]- const focusedOwner = {- authoritative: true,- connectionId: 'source-b',- name: 'worker'- }-- assert.equal(resolveRoutineOwner(roster, focusedOwner, 'source-a::default'), null)-})--test('regression #94516: a null focused owner falls back to the roster-clicked bot', () => {- // The focused session has no bot owner (a normal chat, or ambiguous owner- // hints — the SDK fails closed to null), but the user just clicked a bot in- // the populated roster. The Routines pane must scope to THAT bot instead of- // pinning every agent on the unavailable placeholder (#94516).- const { resolveRoutineOwner } = load({ focusedSessionOwnerSupported: true }).__api- const roster = [- { connectionId: 'source-a', name: 'default', remoteSource: true, sourceScoped: true },- { connectionId: 'source-a', name: 'blog-writer', remoteSource: true, sourceScoped: true }- ]-- assert.equal(resolveRoutineOwner(roster, null, 'source-a::blog-writer'), roster[1])-})--test('regression #94516: a null focused owner with no matching selection still fails closed', () => {- // No focused owner AND the selection has no roster row: there is nothing to- // scope cron reads/mutations to, so the pane keeps its fail-closed state.- const { resolveRoutineOwner } = load({ focusedSessionOwnerSupported: true }).__api- const roster = [- { connectionId: 'source-a', name: 'default', remoteSource: true, sourceScoped: true }- ]-- assert.equal(resolveRoutineOwner(roster, null, 'source-a::missing'), null)-})--test('unit: a legacy SDK without focused owner support may use selection', () => {- const { resolveRoutineOwner } = load().__api- const roster = [{- connectionId: 'source-a',- name: 'default',- remoteSource: true,- sourceScoped: true- }]-- assert.equal(resolveRoutineOwner(roster, null, 'source-a::default'), roster[0])-})--test('unit: register() wires the focused-owner ladder through bindProfileSync', () => {- assert.match(- pluginSource,- /const unbindProfileListener = bindProfileSync\(\$focusedBotOwner\)/,- 'the reseeding helper must own the connection-qualified focused owner subscription'- )-})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.mjsdeleted file mode 100644index 05cc64ea2e0..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/single-flight.test.mjs+++ /dev/null@@ -1,61 +0,0 @@-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.mjsdeleted file mode 100644index ef6688648c3..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/soul-protocol-backfill.test.mjs+++ /dev/null@@ -1,145 +0,0 @@-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)-- // composeSoul's generated-identity path also skips the section.- const generated = helpers.composeSoul({ name: 'newbot', title: 'T', description: 'D', roster: [], customSoul: '' })- assert.doesNotMatch(generated, /## Messaging other agents/)-})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/unaddressed-mentions.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/unaddressed-mentions.test.mjsdeleted file mode 100644index 3e8e40f4fb2..00000000000--- a/apps/desktop/src/plugins/hermes-bots/tests/unaddressed-mentions.test.mjs+++ /dev/null@@ -1,65 +0,0 @@-import assert from 'node:assert/strict'-import { readFileSync } from 'node:fs'-import test from 'node:test'-import vm from 'node:vm'--// #94478 review: exercise the REAL unaddressedGroupMentions from plugin.js-// via the same vm-slice pattern as active-now-strip.test.mjs, plus pin the-// log-index ordering fix (entry ids are UUIDs, NOT monotonic).--const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')--function loadUnaddressed(roomLog) {- const start = source.indexOf('function unaddressedGroupMentions')- const end = source.indexOf('/** Drive one bounded round-robin turn for ONE THREAD.')-- assert.ok(start >= 0 && end > start, 'unaddressedGroupMentions block must remain extractable')-- const members = [{ name: 'alpha' }, { name: 'beta' }, { name: 'gamma' }]- const sandbox = {- $groupChats: {- // The production code indexes rooms by name; expose the room under- // both shapes so either access style resolves.- get: k => ({ log: roomLog, [k ?? 'g']: { log: roomLog } }),- },- groupThreadOf: e => e.thread,- parseGroupChatMentions: (text, ms) => ({- mentioned: [...new Set(ms.filter(m => text.includes(`@${m.name}`)).map(m => m.name))],- everyone: false,- }),- groupMemberKey: m => m.name,- members,- out: null,- }- vm.createContext(sandbox)- vm.runInContext(`${source.slice(start, end)}\nout = unaddressedGroupMentions('g', members, 't1')`, sandbox)- return sandbox.out-}--function entry(id, from, text, thread = 't1') {- return { id, at: 0, from: { kind: 'member', name: from }, text, thread }-}--test('unaddressedGroupMentions flags a cited member with no later post', () => {- const pending = loadUnaddressed([- entry('zzzz-0002', 'alpha', 'hello'),- entry('aaaa-0003', 'beta', 'ping @gamma — take this'),- ])- assert.equal(JSON.stringify(pending), JSON.stringify(['gamma']))-})--test('a reply AFTER the citation in log order counts as answered even when its id sorts lower', () => {- const pending = loadUnaddressed([- entry('aaaa-0003', 'beta', 'ping @gamma — take this'),- entry('9999-0004', 'gamma', 'on it'),- ])- assert.equal(JSON.stringify(pending), JSON.stringify([]))-})--test('self-citations and user entries never create pending handoffs', () => {- const pending = loadUnaddressed([- entry('bbbb-0001', 'alpha', 'I will do @alpha things myself'),- { id: 'cccc-0002', at: 0, from: { kind: 'user', name: 'You' }, text: '@beta @gamma look here', thread: 't1' },- ])- assert.equal(JSON.stringify(pending), JSON.stringify([]))-})