The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): restore live group after bot open failure
funky-xamarin9ea7a37cc197
diff --git a/apps/desktop/e2e/group-to-local-bot-handoff.spec.ts b/apps/desktop/e2e/group-to-local-bot-handoff.spec.tsindex 2dedaa141d1..419d5a69e05 100644--- a/apps/desktop/e2e/group-to-local-bot-handoff.spec.ts+++ b/apps/desktop/e2e/group-to-local-bot-handoff.spec.ts@@ -7,17 +7,17 @@ let fixture: MockBackendFixture | null = nullasync function openBots(page: MockBackendFixture['page']): Promise<void> {const tab = page.getByRole('button', { name: 'Bots', exact: true }).or(page.getByRole('tab', { name: 'Bots', exact: true })).first()await tab.click()- await expect(page.getByRole('button', { name: 'New agent or group chat' })).toBeVisible()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()}async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {- await page.getByRole('button', { name: 'New agent or group chat' }).click()- await page.getByRole('menuitem', { name: 'New Agent' }).click()+ await page.getByRole('button', { name: 'New bot or group chat' }).click()+ await page.getByRole('menuitem', { name: 'New Bot' }).click()- const dialog = page.getByRole('dialog', { name: 'New Agent' })+ const dialog = page.getByRole('dialog', { name: 'New Bot' })await dialog.getByPlaceholder('inbox-triage').fill(name)await dialog.getByPlaceholder('Inbox Triage').fill(title)- await dialog.getByRole('button', { name: 'Create Agent' }).click()+ await dialog.getByRole('button', { name: 'Create Bot' }).click()await expect(dialog).toBeHidden({ timeout: 30_000 })await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })}@@ -40,7 +40,7 @@ test('local bot replaces an open group main workspace', async () => {await createAgent(page, 'programmer', 'Programmer')await createAgent(page, 'reviewer', 'Reviewer')- await page.getByRole('button', { name: 'New agent or group chat' }).click()+ await page.getByRole('button', { name: 'New bot or group chat' }).click()await page.getByRole('menuitem', { name: 'New Group Chat' }).click()const dialog = page.getByRole('dialog', { name: 'New Group Chat' })@@ -50,24 +50,20 @@ test('local bot replaces an open group main workspace', async () => {await dialog.getByRole('textbox', { name: 'Group name' }).fill('Programmer, Reviewer')await dialog.getByRole('button', { name: 'Create Group (2)' }).click()- const groupTitle = page.getByText('Programmer, Reviewer — group chat', { exact: true }).filter({ visible: true })+ const groupTab = page.getByRole('tab', { name: /Programmer, Reviewer Close/ })const groupComposer = page.getByRole('textbox', { name: 'Message Programmer, Reviewer' }).filter({ visible: true })- await expect(groupTitle).toBeVisible({ timeout: 20_000 })+ await expect(groupTab).toBeVisible({ timeout: 20_000 })+ await expect(groupTab).toHaveAttribute('aria-selected', 'true')await expect(groupComposer).toBeVisible()const programmer = page.getByRole('button', { name: /^Programmer\b/ }).filter({ visible: true }).first()await programmer.click()- await expect(groupTitle).toHaveCount(0, { timeout: 20_000 })+ const botChatTab = page.getByRole('tab', { name: /Bot Chat Close/ }).filter({ visible: true })+ await expect(botChatTab).toBeVisible({ timeout: 30_000 })+ await expect(botChatTab).toHaveAttribute('aria-selected', 'true')+ await expect(groupTab).toHaveCount(0)await expect(groupComposer).toHaveCount(0)- await expect(page.getByRole('tab', { name: /New session/ }).filter({ visible: true })).toBeVisible()+ await expect(page.getByText(/Waking up Programmer/i)).toHaveCount(0)await expect(page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first()).toBeVisible()- await expect- .poll(() =>- page- .getByText('Programmer', { exact: true })- .filter({ visible: true })- .evaluateAll(nodes => nodes.some(node => node.getBoundingClientRect().left > window.innerWidth * 0.65)),- )- .toBe(true)})diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.jsindex 294b8956f47..14ced2e0325 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@ -5756,20 +5756,45 @@ async function findExistingCanonicalChat(owner) {* persistence job is done by the eager session.title write below on modern* gateways; older gateways that reject the eager write keep a narrow* compat kickoff, else the pruner reaps the empty lazy session and the- * chat never survives its own creation. */-function createCanonicalChat(owner, { kickoff = false } = {}) {+ * chat never survives its own creation.+ *+ * `openingStillCurrent` (click-path opens): a staleness probe consulted+ * before every navigation — when the user has already moved on (opened a+ * group, clicked another bot), the create still completes registry-side+ * but never steals the workspace (#89834 family). */+function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = null } = {}) {const { bot, name, key, route } = botOwner(owner)const inflight = canonicalCreations.get(key)if (inflight) {- return inflight+ if (!openingStillCurrent) {+ return inflight.run+ }++ return inflight.run.then(async sid => {+ if (sid && openingStillCurrent() && typeof host.openSession === 'function') {+ await host.openSession(sid, {+ ...(route ? { route } : {}),+ profile: name,+ intent: 'main',+ keepAllProfilesScope: route ? true : false,+ workspaceMode: 'bots',+ workspaceOwnerKey: botWorkspaceOwnerKey(bot),+ tabTitle: CANONICAL_CHAT_TITLE+ })+ }+ return sid+ })}+ const flight = { run: null }+ const canNavigate = () => !openingStillCurrent || openingStillCurrent()+const run = (async () => {const existing = await findExistingCanonicalChat(owner)if (existing?.id) {- if (typeof host.openSession === 'function') {+ if (typeof host.openSession === 'function' && canNavigate()) {// The exact-lookup gateway reports the compression-lineage tip as// resolved_id; open the tip, the registry row stays the identity.await openStoredBotChat(owner, existing.resolved_id || existing.id, existing)@@ -5834,13 +5859,16 @@ function createCanonicalChat(owner, { kickoff = false } = {}) {// an unmounted session left the intro reply invisible until reopen.let opened = false- if (sid && typeof host.openSession === 'function') {+ if (sid && typeof host.openSession === 'function' && canNavigate()) {try {await host.openSession(sid, {...(route ? { route } : {}),profile: name,intent: 'main',- keepAllProfilesScope: route ? true : false+ keepAllProfilesScope: route ? true : false,+ ...(openingStillCurrent+ ? { workspaceMode: 'bots', workspaceOwnerKey: botWorkspaceOwnerKey(bot), tabTitle: CANONICAL_CHAT_TITLE }+ : {})})opened = true} catch {@@ -5863,19 +5891,22 @@ function createCanonicalChat(owner, { kickoff = false } = {}) {try {await requestForBot(bot, 'prompt.submit', { session_id: runtime, text: 'Hey, tell me about yourself!' })- if (!opened && sid && typeof host.openSession === 'function') {+ if (!opened && sid && typeof host.openSession === 'function' && canNavigate()) {await host.openSession(sid, {...(route ? { route } : {}),profile: name,intent: 'main',- keepAllProfilesScope: route ? true : false+ keepAllProfilesScope: route ? true : false,+ ...(openingStillCurrent+ ? { workspaceMode: 'bots', workspaceOwnerKey: botWorkspaceOwnerKey(bot), tabTitle: CANONICAL_CHAT_TITLE }+ : {})})}} catch {// The chat already exists under the canonical title — the next click// finds it by name instead of making a second Bot Chat.}- } else if (!opened && sid && typeof host.openSession === 'function') {+ } else if (!opened && sid && typeof host.openSession === 'function' && canNavigate()) {// No intro turn: still finish mounting the chat when the first open// raced the (now titled) row.try {@@ -5883,7 +5914,10 @@ function createCanonicalChat(owner, { kickoff = false } = {}) {...(route ? { route } : {}),profile: name,intent: 'main',- keepAllProfilesScope: route ? true : false+ keepAllProfilesScope: route ? true : false,+ ...(openingStillCurrent+ ? { workspaceMode: 'bots', workspaceOwnerKey: botWorkspaceOwnerKey(bot), tabTitle: CANONICAL_CHAT_TITLE }+ : {})})} catch {/* row is titled and persistent — the next click opens it by name */@@ -5892,9 +5926,14 @@ function createCanonicalChat(owner, { kickoff = false } = {}) {}return sid || null- })().finally(() => canonicalCreations.delete(key))+ })().finally(() => {+ if (canonicalCreations.get(key) === flight) {+ canonicalCreations.delete(key)+ }+ })- canonicalCreations.set(key, run)+ flight.run = run+ canonicalCreations.set(key, flight)return run}@@ -5907,10 +5946,13 @@ function createCanonicalChat(owner, { kickoff = false } = {}) {* anywhere in this path — remote bots included. The owner route rides* every RPC (requestForBot) and the open (openStoredBotChat), so a remote* bot's chat opens without re-homing Desktop's chrome. */-async function openBotCanonicalChat(owner) {+async function openBotCanonicalChat(owner, openingStillCurrent = null) {const existing = await findExistingCanonicalChat(owner)if (existing?.id && typeof host.openSession === 'function') {+ if (openingStillCurrent && !openingStillCurrent()) {+ return null+ }const openedId = existing.resolved_id || existing.idawait openStoredBotChat(owner, openedId, existing)// Both identities matter downstream: the durable registry row names the@@ -5920,7 +5962,7 @@ async function openBotCanonicalChat(owner) {return { registryId: String(existing.id), openedId: String(openedId) }}- const created = await createCanonicalChat(owner)+ const created = await createCanonicalChat(owner, { openingStillCurrent })return created ? { registryId: String(created), openedId: String(created) } : null}@@ -5978,12 +6020,39 @@ async function openRosterBot(bot) {// has actually fronted a new owner; a failed home open must not steal the// center from a group the user was reading.const previousGroup = $groupChatWorkspace.get()+ const previousGroupRef = previousGroup+ ? { group: previousGroup, roomId: String($groupChats.get()[previousGroup]?.roomId || '') }+ : nullhaptic('tap')saveSelectedRosterBot(bot)setBotsWorkspaceOwner(botWorkspaceOwnerKey(bot), bot)- dismissGroupChatForLocalBotOpen()+ const dismissedGroup = bot.remoteSource ? null : dismissGroupChatForLocalBotOpen()++ if (!dismissedGroup) {+ $groupChatWorkspace.set(null)+ }++ const restorePreviousGroup = () => {+ if (!previousGroupRef || $groupChatWorkspace.get()) {+ return+ }++ const restoreRef = dismissedGroup || previousGroupRef+ const rooms = $groupChats.get()+ const currentGroup = restoreRef.roomId+ ? Object.keys(rooms).find(name => !rooms[name]?.tombstone && String(rooms[name]?.roomId || '') === restoreRef.roomId)+ : liveGroupChatNames().includes(restoreRef.group)+ ? restoreRef.group+ : null++ if (!currentGroup) {+ return+ }++ openGroupChat(currentGroup)+ }if ($botUnread.get()[key]) {const next = { ...$botUnread.get() }@@ -5998,9 +6067,7 @@ async function openRosterBot(bot) {} catch (error) {if (generation === botOpenGeneration) {$openBotChat.set(null)- if (previousGroup && !$groupChatWorkspace.get()) {- $groupChatWorkspace.set(previousGroup)- }+ restorePreviousGroup()syncBotsHomeWorkspace()notifyBotOpenFailure(error, bot, `Could not reach ${bot.connectionLabel || 'the gateway'}`)@@ -6014,7 +6081,7 @@ async function openRosterBot(bot) {}try {- const opened = await openBotCanonicalChat(bot)+ const opened = await openBotCanonicalChat(bot, () => generation === botOpenGeneration)if (generation !== botOpenGeneration) {return false@@ -6040,9 +6107,7 @@ async function openRosterBot(bot) {} catch (error) {if (generation === botOpenGeneration) {$openBotChat.set(null)- if (previousGroup && !$groupChatWorkspace.get()) {- $groupChatWorkspace.set(previousGroup)- }+ restorePreviousGroup()syncBotsHomeWorkspace()notifyBotOpenFailure(error, bot, `Could not open ${displayName(bot, meta)}'s chat — try again`)@@ -6055,9 +6120,7 @@ async function openRosterBot(bot) {// do not navigate the current workspace or create a draft on the wrong owner.if (typeof host.newChat !== 'function') {$openBotChat.set(null)- if (previousGroup && !$groupChatWorkspace.get()) {- $groupChatWorkspace.set(previousGroup)- }+ restorePreviousGroup()syncBotsHomeWorkspace()return false}@@ -14046,8 +14109,9 @@ function dismissGroupChatForLocalBotOpen() {return null}+ const roomId = String($groupChats.get()[group]?.roomId || '')closeGroupChatMainTab(group)- return group+ return { group, roomId }}/** Main-window wrapper: seats the member roster reactively (live roster +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.mjsindex c667250a306..d99b00755e1 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/active-now-strip.test.mjs@@ -189,5 +189,5 @@ test('ActiveNowStrip renders above the roster, is a live region, and is click-acconst open = source.slice(openStart, openStart + 3200)assert.match(open, /await prepareBotSource\(bot\)/)- assert.match(open, /await openBotCanonicalChat\(bot\)/)+ assert.match(open, /await openBotCanonicalChat\(bot, \(\) => generation === botOpenGeneration\)/)})diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjsindex d20db31067c..e1174c0dc84 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjs@@ -147,6 +147,7 @@ globalThis.__home = {$botChatFocused,$botsHomeFronted,$groupChatWorkspace,+ $groupChats,$lastRoster,$lastSources,$openBotChat,@@ -556,10 +557,11 @@ test('a missing profile-scoped draft API returns to the home without navigating'assert.ok(t.botsHomeVisible(), 'the owner home remains the visible recovery surface')})-test('a bot chat opens from its canonical name-registry row without closing the prior group tab', async () => {+test('a local bot chat retires the prior group tab before taking the center', async () => {const t = load()t.setPluginCtx({ storage: { set: () => undefined } })t.$botsPaneVisible.set(true)+ t.$groupChats.set({ 'Launch room': { roomId: 'r-launch', log: [], watermarks: {}, sessions: {} } })t.host.openSession = async () => undefinedt.host.request = async method => {if (method === 'session.list') {@@ -578,7 +580,7 @@ test('a bot chat opens from its canonical name-registry row without closing theassert.equal(result, true)assert.equal(t.$groupChatWorkspace.get(), null)- assert.equal(groupEntry.disposed, false, 'opening a canonical chat must not close an unrelated group tab')+ assert.equal(groupEntry.disposed, true, 'the local bot chat must release the group workspace owner')assert.equal(t.$openBotChat.get()?.key, 'local::writer')assert.equal(t.$openBotChat.get()?.openedRegistryId, 'bot-chat')})@@ -587,6 +589,7 @@ test('a failed canonical-chat open preserves the visible group owner', async ()const t = load()t.setPluginCtx({ storage: { set: () => undefined } })t.$botsPaneVisible.set(true)+ t.$groupChats.set({ 'Launch room': { roomId: 'r-launch', log: [], watermarks: {}, sessions: {} } })t.host.openSession = async () => {throw new Error('gateway unavailable')}@@ -604,11 +607,114 @@ test('a failed canonical-chat open preserves the visible group owner', async ()assert.equal(result, false)assert.equal(t.$groupChatWorkspace.get(), 'Launch room')- assert.equal(groupEntry.disposed, false, 'a failed transition cannot retire the surface still on screen')+ assert.equal(groupEntry.disposed, true, 'the stale group tab was retired before the attempted open')+ const restoredGroup = t.opened.filter(entry => entry.id === 'hermes-bots:group:launch-room').at(-1)+ assert.notEqual(restoredGroup, groupEntry)+ assert.equal(restoredGroup.disposed, false, 'a failed transition re-registers the group tab')assert.equal(t.$openBotChat.get(), null)assert.equal(t.notifications.at(-1).kind, 'error')})+test('a failed remote canonical open re-fronts the preserved group tab', async () => {+ const t = load()+ t.setPluginCtx({ storage: { set: () => undefined } })+ t.$botsPaneVisible.set(true)+ t.$groupChats.set({ 'Launch room': { roomId: 'r-launch', log: [], watermarks: {}, sessions: {} } })+ t.openGroupChat('Launch room')+ const groupEntry = t.opened.find(entry => entry.id === 'hermes-bots:group:launch-room')+ t.host.openSession = async () => {+ throw new Error('hydration failed after fronting Bot Chat')+ }++ const result = await t.openRosterBot({+ connectionId: 'work-vps',+ connectionLabel: 'Work',+ name: 'researcher',+ remoteSource: true+ })++ assert.equal(result, false)+ assert.equal(groupEntry.disposed, false, 'remote open preserves the original tab')+ assert.equal(t.$groupChatWorkspace.get(), 'Launch room')+ assert.equal(+ t.opened.filter(entry => entry.id === 'hermes-bots:group:launch-room').length,+ 2,+ 're-opening the same workspace id re-fronts the preserved group tab'+ )+})++test('a failed remote open cannot restore a group disbanded while the tab was preserved', async () => {+ const t = load()+ t.setPluginCtx({ storage: { set: () => undefined } })+ t.$botsPaneVisible.set(true)+ t.$groupChats.set({ 'Launch room': { roomId: 'r-launch', log: [], watermarks: {}, sessions: {} } })+ t.openGroupChat('Launch room')++ let rejectOpen+ let markOpenStarted+ const openStarted = new Promise(resolve => {+ markOpenStarted = resolve+ })+ t.host.openSession = () =>+ new Promise((resolve, reject) => {+ rejectOpen = reject+ markOpenStarted()+ })++ const opening = t.openRosterBot({+ connectionId: 'work-vps',+ connectionLabel: 'Work',+ name: 'researcher',+ remoteSource: true+ })+ await openStarted++ t.$groupChats.set({ 'Launch room': { roomId: 'r-launch', tombstone: true } })+ t.closeGroupChatMainTab('Launch room')+ rejectOpen(new Error('gateway unavailable'))++ assert.equal(await opening, false)+ assert.equal(t.$groupChatWorkspace.get(), null)+ assert.equal(t.$openBotChat.get(), null)+})++test('a failed local open cannot re-register a group tombstoned after retirement', async () => {+ const t = load()+ t.setPluginCtx({ storage: { set: () => undefined } })+ t.$botsPaneVisible.set(true)+ t.$groupChats.set({ 'Launch room': { roomId: 'r-launch', log: [], watermarks: {}, sessions: {} } })+ t.host.request = async method => {+ if (method === 'session.list') {+ return { sessions: [{ id: 'bot-chat', title: 'Bot Chat', message_count: 4 }] }+ }++ return {}+ }++ let rejectOpen+ let markOpenStarted+ const openStarted = new Promise(resolve => {+ markOpenStarted = resolve+ })+ t.host.openSession = () =>+ new Promise((resolve, reject) => {+ rejectOpen = reject+ markOpenStarted()+ })++ t.openGroupChat('Launch room')+ const opening = t.openRosterBot({ connectionId: 'local', name: 'writer' })+ await openStarted++ t.$groupChats.set({ 'Launch room': { roomId: 'r-launch', tombstone: true } })+ rejectOpen(new Error('gateway unavailable'))++ assert.equal(await opening, false)+ assert.equal(t.$groupChatWorkspace.get(), null)+ assert.equal(t.opened.filter(entry => entry.id === 'hermes-bots:group:launch-room').length, 1)+ assert.equal(t.$openBotChat.get(), null)+})+test('choosing a group prevents a stale canonical-chat open from closing it later', async () => {const t = load()t.setPluginCtx({ storage: { set: () => undefined } })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.mjsindex bfc8be4e739..b4348e651d9 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjs@@ -14,6 +14,7 @@ function loadCanonicalCreation({ openSession, request }) {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() }}@@ -115,3 +116,53 @@ test('regression: a failed intro still returns the created registry row', async// 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', () => 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', () => firstCurrent)+ await createStarted+ firstCurrent = false+ const second = runtime.createCanonicalChat('ops', () => 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.mjsindex c5934ee6454..3e013bbda19 100644--- 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.mjs@@ -125,10 +125,11 @@ test('the open path never reads or writes a stored pointer', () => {assert.doesNotMatch(section, /preferred_session_ids/, 'no id-verification RPC on the canonical path')})-test('openBotCanonicalChat takes only the bot owner — identity needs nothing else', () => {+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). Still no pins, no session ids.- assert.match(source, /async function openBotCanonicalChat\(owner\) \{/)+ // 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 ─────────────────────────────────────────────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.mjsindex 86e3957d083..8feedb4a20d 100644--- 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.mjs@@ -3,47 +3,43 @@ import { readFileSync } from 'node:fs'import test from 'node:test'import vm from 'node:vm'-// #89834 — local open invokes registered group main-tab closer before canonical open.const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')-const atom = i => {- let v = i- return { get: () => v, set: n => { v = typeof n === 'function' ? n(v) : n }, listen: () => () => {} }+const atom = initial => {+ let value = initial+ return { get: () => value, set: next => { value = typeof next === 'function' ? next(value) : next }, listen: () => () => {} }}-const jsx = (t, p = {}) => ({ type: t, props: p })-const find = (tree, pred) => {+const jsx = (type, props = {}) => ({ type, props })+const find = (tree, predicate) => {if (tree == null || typeof tree !== 'object') return nullif (Array.isArray(tree)) {- for (const c of tree) { const f = find(c, pred); if (f) return f }+ for (const child of tree) { const match = find(child, predicate); if (match) return match }return null}- return pred(tree) ? tree : find(tree.props?.children, pred)+ return predicate(tree) ? tree : find(tree.props?.children, predicate)}-function load() {- const timeline = [], notifications = []+function load({ rejectOpen = false, rejectPrepare = false } = {}) {+ const timeline = []const host = {state: {- profile: { get: () => 'other', listen: () => {} },+ profile: { get: () => 'default', listen: () => {} },gateway: { get: () => 'open', listen: () => {} },connectionId: { get: () => 'local', listen: () => {} }},- request: async m => m === 'session.create'- ? { stored_session_id: 'stored-chat', session_id: 'rt-chat' }- : { profiles: [], sessions: [] },- notify: p => notifications.push(p),- notifyError: () => {}, openSession: async () => {}, ensureAgent: async () => {},+ 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: () => timeline.push({ type: 'navigate' })+ 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 ctx = {- atom, jsx, jsxs: jsx, cn: (...a) => a.filter(Boolean).join(' '), haptic: () => {},- useEffect: () => {}, useRef: i => ({ current: typeof i === 'function' ? i() : i }),- useState: i => [typeof i === 'function' ? i() : i, () => {}],- useValue: s => (s && typeof s.get === 'function' ? s.get() : s),+ 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(n => [n, n])),+ ...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: () => {} } },@@ -57,93 +53,68 @@ function load() {.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,ActiveNowStrip,BotsPane,openGroupChat,groupChatMainTabs,$groupChatWorkspace};`)- vm.runInNewContext(code, ctx, { filename: 'plugin.js' })- // Live binding: handlers resolve this mutable global at call time.- ctx.openBotCanonicalChat = async (...a) => { timeline.push({ type: 'openBotCanonicalChat', args: a }); return 'stored-chat' }- const api = ctx.__h+ .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.__hconst registerGroup = group => {- let closed = 0- ctx.host.openWorkspace = () => () => { closed += 1; timeline.push({ type: 'mainTabClose', group }) }+ api.$groupChats.set({ ...api.$groupChats.get(), [group]: { log: [], watermarks: {}, sessions: {}, stranded: {} } })+ host.openWorkspace = id => () => timeline.push({ type: 'workspaceClose', id })api.openGroupChat(group)- assert.equal(api.$groupChatWorkspace.get(), group)- assert.ok(api.groupChatMainTabs.has(group))- return { closed: () => closed, registered: () => api.groupChatMainTabs.has(group) }+ return { closed: () => timeline.filter(event => event.type === 'workspaceClose' && event.id.includes(':group:')).length }}const botRow = bot => {const tree = api.BotRow({ bot, onEdit: () => {} })- const row = tree.type === 'button' ? tree : tree.props.children[0].props.children- assert.equal(typeof row.props.onClick, 'function')- return row- }- // Real Active Now onOpen from BotsPane (not a hand-copied fragment).- const strip = find(api.BotsPane(), n => n?.props && typeof n.props.onOpen === 'function' && 'roster' in n.props)- assert.ok(strip, 'BotsPane mounts ActiveNowStrip with onOpen')- const onOpen = strip.props.onOpen- const activeChip = bot => {- const b = { ...bot, last_session: bot.last_session || { id: 'live', last_active: Math.floor(Date.now() / 1000) - 5 } }- const tree = api.ActiveNowStrip({ roster: [b], activeProfile: 'other', gatewayState: 'open', metaByName: {}, onOpen })- const chip = find(tree, n => n.type === 'button' && /Open /.test(String(n.props?.title || ''))- && (String(n.props.title).includes(bot.name) || String(n.props.title).includes(bot.title || '')))- assert.ok(chip, 'Active Now chip renders')- return chip+ return tree.type === 'button' ? tree : tree.props.children[0].props.children}- return { api, timeline, notifications, registerGroup, botRow, activeChip }+ 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(r => setImmediate(r)); await new Promise(r => setImmediate(r)) }-const assertCloseBeforeOpen = tl => {- const c = tl.findIndex(e => e.type === 'mainTabClose'), o = tl.findIndex(e => e.type === 'openBotCanonicalChat')- assert.ok(c >= 0, 'registered main-tab closer must run')- assert.ok(o >= 0, 'local open must reach canonical chat')- assert.ok(c < o, 'close must precede canonical open')+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)}-const remote = { name: 'research', title: 'Research', remoteSource: true, sourceScoped: true, connectionId: 'work', connectionLabel: 'Work' }-test('BotRow local open closes group main tab before canonical open', async () => {- const r = load(), tab = r.registerGroup('Core')- await r.botRow({ name: 'alpha', title: 'Alpha' }).props.onClick()- assert.equal(tab.closed(), 1, 'registered main-tab closer must run')- assert.equal(r.api.$groupChatWorkspace.get(), null)- assert.equal(tab.registered(), false)- assertCloseBeforeOpen(r.timeline)+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 remote open does not dismiss group main tab', async () => {- const r = load(), tab = r.registerGroup('Core')- await r.botRow(remote).props.onClick()- assert.equal(tab.closed(), 0, 'remote open must not dismiss the group tab')- assert.equal(r.api.$groupChatWorkspace.get(), 'Core')- assert.equal(tab.registered(), true)- assert.equal(r.timeline.some(e => e.type === 'openBotCanonicalChat'), false)- assert.ok(r.notifications.some(n => /Stay in this chat/.test(n.message || '')))+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('Active Now local open closes group main tab before canonical open', async () => {- const r = load(), tab = r.registerGroup('Ops')- await r.activeChip({ name: 'alpha', title: 'Alpha' }).props.onClick()- await drain()- assert.equal(tab.closed(), 1, 'registered main-tab closer must run')- assert.equal(r.api.$groupChatWorkspace.get(), null)- assert.equal(tab.registered(), false)- assertCloseBeforeOpen(r.timeline)+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('Active Now remote open does not dismiss group main tab', async () => {- const r = load(), tab = r.registerGroup('Ops')- await r.activeChip(remote).props.onClick(); await drain()- assert.equal(tab.closed(), 0, 'remote open must not dismiss the group tab')- assert.equal(r.api.$groupChatWorkspace.get(), 'Ops')- assert.equal(tab.registered(), true)+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('no group / old-host: local open is safe and still opens chat', async () => {- const r = load()- assert.equal(r.api.$groupChatWorkspace.get(), null)- await assert.doesNotReject(() => r.botRow({ name: 'alpha', title: 'Alpha' }).props.onClick())- assert.ok(r.timeline.some(e => e.type === 'openBotCanonicalChat'))- r.api.$groupChatWorkspace.set('Legacy')- assert.equal(r.api.groupChatMainTabs.has('Legacy'), false)- await r.botRow({ name: 'beta', title: 'Beta' }).props.onClick()- assert.equal(r.api.$groupChatWorkspace.get(), null)+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)})