The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge PR #90006: connection-bound Bot Mode actions, reconciled with name-identity + fail-closed canonical resolution
Teknium0404020f7b94
diff --cc apps/desktop/src/plugins/hermes-bots/plugin.jsindex c332c44ae75,5e76524d4d3..68c9f3c2b9a--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@@ -185,23 -191,65 +191,72 @@@ const $lastJobs = atom([]* (the bot you're actually chatting with) and roster clicks. */const $selectedBot = atom('default')- /** Owner profile of the chat the user is LOOKING AT. Newer desktops expose- * `host.state.focusedSessionProfile` (the focused session row's stamped- * owner, gateway profile for drafts); older builds fall back to the gateway- * profile atom — the socket's home — which is the previous behavior. The- * distinction matters because tab/tile focus moves WITHOUT swapping the- * gateway socket: with only the socket atom, opening another bot's chat in- * a tab left the roster highlight (and the Cronjobs tile) on whichever bot- * the socket happened to be homed on. */+ /** Owner of the chat the user is LOOKING AT. Newer desktops expose a+ * connection-qualified owner. Older builds synthesize the previous+ * profile/gateway fallback and listen to both atoms when available. */const $focusedBotProfile = host.state.focusedSessionProfile || host.state.profile+/** Profile that owns the chat currently on screen. Bot Mode opens another+ * profile's session without moving the gateway socket, so mention filtering+ * and sender identity must follow focus rather than host.state.profile. */+function focusedMentionProfile() {+ return String($focusedBotProfile.get?.() || '').trim() || 'default'+}++ function fallbackFocusedBotOwner(profile = $focusedBotProfile.get?.()) {+ const focusedProfile = String(profile || 'default').trim() || 'default'+ const activeProfile = String(host.state.profile?.get?.() || 'default').trim() || 'default'++ // focusedSessionProfile without focusedSessionOwner is a legacy half-shape:+ // it carries no source identity. Only reuse the active connection when the+ // focused profile is also the active profile; otherwise fail closed rather+ // than manufacturing a cross-source owner from unrelated atoms.+ if (host.state.focusedSessionProfile && focusedProfile !== activeProfile) {+ return null+ }++ const connectionId = String(+ host.state.connectionId?.get?.() ||+ (typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||+ ''+ ).trim()++ return {+ authoritative: false,+ connectionId,+ profile: focusedProfile+ }+ }++ const hasFocusedSessionOwnerSupport = Boolean(host.state.focusedSessionOwner)+ const $focusedBotOwner = host.state.focusedSessionOwner || {+ get: () => fallbackFocusedBotOwner(),+ listen: listener => {+ const emit = profile => listener(fallbackFocusedBotOwner(profile))+ const unbindProfile = $focusedBotProfile.listen(emit)+ const unbindConnection = host.state.connectionId?.listen?.(() => emit($focusedBotProfile.get?.()))++ return () => {+ unbindProfile?.()+ unbindConnection?.()+ }+ }+ }++ function focusedRosterOwner(owner) {+ const name = String(owner?.profile || owner?.name || '').trim()++ if (!owner || !name) {+ return null+ }++ return {+ authoritative: owner.authoritative !== false,+ connectionId: String(owner.connectionId || '').trim(),+ name+ }+ }+/** Optional secondary navigation inside the Bots pane (group-chat rooms). *//** Group-chat rooms: { [group]: { log: [{from:{kind,name},text,at}], watermarks:{[member]:idx}, epoch, running } }.@@@ -1276,23 -721,87 +1544,55 @@@ function fallbackSelectionAfterHide(nam/** One-time reconciliation: Bot Mode sessions are always hidden, but rooms* and Bot Chats created before this policy (or while the old pref was off)- * left visible rows behind. On every plugin load, sweep every session id we- * own — canonical chats from bot meta plus each group room's member- * sessions — through the core session.set_hidden RPC, then run the- * ownership-based sweep for the rows we DON'T know by id. Idempotent (the DB- * setter is a no-op on already-hidden rows) and feature-detected: older- * gateways lack session.set_hidden and simply keep the rows visible. */+ * left visible rows behind. On every plugin load, sweep the session ids we+ * own by id (each group room's member sessions) through the core+ * session.set_hidden RPC, then run the TITLE-based ownership sweep for+ * everything else — canonical Bot Chats are identified by name (the+ * registry row titled "Bot Chat"), so the title sweep is what hides them;+ * no stored-id pointer is consulted. Idempotent (the DB setter is a no-op+ * on already-hidden rows) and feature-detected: older gateways lack+ * session.set_hidden and simply keep the rows visible. */function hideOwnedBotSessions() {- const rooms = Object.values($groupChats.get())- .flatMap(room => Object.values(room?.sessions || {}))- .filter(sid => Boolean(sid) && sid !== true)- const roster = $lastRoster.get()- const canonical = Object.entries($botMeta.get())- .map(([key, meta]) => {- const bot = roster.find(candidate => botMetaKey(candidate) === key)- return meta?.chat && bot ? { bot, id: meta.chat } : null- })- .filter(Boolean)- const canonicalIds = new Set(canonical.map(({ id }) => id))- const rooms = Object.values($groupChats.get()).flatMap(room =>++ const roomEntries = Object.values($groupChats.get()).flatMap(room =>+ Object.entries(room?.sessions || {})+ .map(([key, id]) => {- if (!id || id === true || canonicalIds.has(id)) {++ if (!id || id === true) {+ return null+ }++ const persisted = room?.sessionOwners?.[key]+ const derived = (room?.members || []).find(member => groupMemberKey(member) === key)+ // Bare keys are legacy local rooms. A source-qualified key without its+ // immutable owner is unsafe: never let it fall through ambient routing.+ const owner = persisted || derived || (!key.includes('::') ? { name: key } : null)++ if (key.includes('::')) {+ const route = owner?.route+ const sourceMarked = owner?.sourceScoped || owner?.remoteSource+ const routeKey = route?.connectionId && route?.profile+ ? `${route.connectionId}::${route.profile}`+ : ''++ if (!sourceMarked || !route?.targetProfile || routeKey !== key) {+ return null+ }+ }+- return owner ? { owner, id } : null++ return owner ? { owner, id, dedupe: `${key}\u0000${id}` } : null+ })+ .filter(Boolean)+ )+- // Verify every canonical pointer on its immutable source before hiding it.- // A stale pointer must never hide an unrelated ordinary conversation.- const verifiedCanonical = Promise.all(- canonical.map(async entry => {- try {- const route = botConnectionRoute(entry.bot)- const profile = backendTargetProfile(route, entry.bot.name)- const res = await requestForBot(entry.bot, 'profiles.list', {- include_sessions: true,- preferred_session_ids: { [profile]: entry.id }- })- const preferred = (res?.profiles || []).find(item => item?.name === profile)?.preferred_session- const ids = [preferred?.id, preferred?.resolved_id, preferred?.session_id, preferred?.session_key]- .filter(Boolean)- .map(String)-- return String(preferred?.title || '').trim() === 'Bot Chat' && ids.includes(String(entry.id))- ? entry- : null- } catch {- return null- }- })- )++ // The same member session can appear in several rooms (and legacy rooms can++ // share ids) — hide each (owner, id) pair exactly once.++ const rooms = [...new Map(roomEntries.map(entry => [entry.dedupe, entry])).values()]- const known = verifiedCanonical.then(validCanonical =>- Promise.all([- ...validCanonical.filter(Boolean).map(({ bot, id }) =>- Promise.resolve(requestForBot(bot, 'session.set_hidden', { session_id: id, hidden: true })).catch(() => undefined)- ),- ...rooms.map(({ owner, id }) =>- Promise.resolve(requestForBot(owner, 'session.set_hidden', { session_id: id, hidden: true })).catch(- () => undefined- )+ const known = Promise.all(- [...new Set(rooms)].map(sid =>- Promise.resolve(host.request('session.set_hidden', { session_id: sid, hidden: true })).catch(() => undefined)++ rooms.map(({ owner, id }) =>++ Promise.resolve(requestForBot(owner, 'session.set_hidden', { session_id: id, hidden: true })).catch(++ () => undefined+ )- ])+ ))return Promise.all([known, sweepBotProfileSessions().catch(() => undefined)])@@@ -3563,11 -3157,18 +3899,15 @@@ function useRoster()// a write can only carry pre-write ui_meta. (Issue time is the// conservative bound — the server answered no earlier than this.)const issuedAt = Date.now()- // Rich rows (last_session, ui_meta, has_avatar) come from the ACTIVE- // gateway's profiles.list — unchanged single-source behavior.+ // Rich rows (last_session, canonical_session, ui_meta, has_avatar)+ // come from the ACTIVE gateway's profiles.list — the canonical Bot+ // Chat is resolved server-side by NAME (the "Bot Chat" registry row),+ // so the roster never sends session pointers.- const local = await host.request('profiles.list', {})+ const route = await activeBotRoute()+ const activeBot = route+ ? { name: route.profile, sourceScoped: true, route }+ : { name: String(host.state.profile?.get?.() || 'default').trim() || 'default' }- const pins = preferredSessionIds($botMeta.get(), route)- const local = await requestForBot(- activeBot,- 'profiles.list',- Object.keys(pins).length ? { preferred_session_ids: pins } : {}- )++ const local = await requestForBot(activeBot, 'profiles.list', {})// Newer backends inject the teammate-messaging protocol into every// session's system prompt (agent.bot_mode_protocol) — SOUL.md must not// carry a second copy. Older gateways lack the flag: keep appending.@@@ -3879,19 -3453,269 +4238,39 @@@ function isActiveRosterBot(bot, activereturn false}- return botName === activeName-}--function botSelectionKey(bot) {- return bot?.sourceScoped || bot?.remoteSource ? botRosterKey(bot) : bot?.name-}--function isDefaultBot(bot) {- const route = botConnectionRoute(bot)-- return String(route?.profile || bot?.name || '').trim().toLowerCase() === 'default'-}--function newBotChat(bot) {- if (typeof host.newChat !== 'function') {- host.navigate?.('/')-- return- }-- host.newChat(bot?.sourceScoped || bot?.remoteSource ? botConnectionRoute(bot) : bot?.name)-}--/** Resolve @handles in prose against the Bot Mode roster (local + Connections).- * Skips the bot already speaking in this chat. Unique bare names match;- * duplicate names require the @name-device handle. */-function resolveRosterMentions(text, roster, active = {}) {- const members = Array.isArray(roster) ? roster : []- const prose = String(text || '').replace(/```[\s\S]*?```/g, ' ').replace(/`[^`\n]*`/g, ' ')- const byForm = new Map()-- for (const bot of members) {- if (!bot?.name || isActiveRosterBot(bot, active)) {- continue- }-- const handle = String(botHandle(bot.name, bot) || '').toLowerCase()- const name = String(bot.name || '').toLowerCase()- const forms = new Set([handle, name])-- if (bot.handle) {- forms.add(String(bot.handle).toLowerCase())- }-- // Renamed bots are taggable by their friendly names too — the core- // profile display_name and the Bot Mode title (issue: renaming a bot- // didn't change what you @-tag it with).- for (const friendly of botFriendlyNames(bot)) {- for (const form of mentionNameForms(friendly)) {- forms.add(form)- }- }-- for (const form of forms) {- if (!form) {- continue- }-- const existing = byForm.get(form)-- if (existing && existing !== bot) {- byForm.set(form, null)- continue- }-- if (!existing) {- byForm.set(form, bot)- }- }- }-- const mentioned = []- const seen = new Set()-- for (const match of prose.matchAll(/(^|\s)@([a-z0-9][a-z0-9_-]*)/gi)) {- let token = match[2].toLowerCase()-- if (token === 'hermes') {- token = byForm.has('hermes') ? 'hermes' : token- }-- const bot = byForm.get(token)-- if (!bot) {- continue- }-- const key = botRosterKey(bot)-- if (seen.has(key)) {- continue- }-- seen.add(key)- mentioned.push(bot)- }-- return mentioned-}--const REMOTE_DM_TIMEOUT_MS = 180000-const REMOTE_DM_POLL_MS = 2000--/** Resolve the remote bot's canonical Bot Chat with the same no-fork rules- * as the interactive opener: precise pin verification, title-drift- * preservation, exact hidden-title adoption, and minting only after an- * authoritative empty adoption scan. Every successful resolution writes the- * durable id through the connection-qualified owner metadata. */-async function ensureRemoteCanonicalChat(route, profile) {- const backendProfile = route.targetProfile || profile- const owner = { name: profile, sourceScoped: true, remoteSource: route.mode !== 'local', route }- const listed = await requestForBot(owner, 'profiles.list', {})- const profileRow = (listed?.profiles || []).find(row => row?.name === backendProfile)-- if (!profileRow) {- throw new Error(`Remote profile ${backendProfile} could not be resolved`)- }-- const pinned = profileRow?.ui_meta?.['hermes-bots']?.chat || null-- if (pinned) {- const verified = await requestForBot(owner, 'profiles.list', {- include_sessions: true,- preferred_session_ids: { [backendProfile]: pinned }- })- const verifiedRow = (verified?.profiles || []).find(row => row?.name === backendProfile)- const preferred = verifiedRow?.preferred_session-- // `undefined` is an older/ambiguous resolver, not proof of absence. Try- // the immutable pin and surface any failure rather than minting.- if (preferred === undefined) {- const resumed = await requestForBot(owner, 'session.resume', {- session_id: pinned,- profile: backendProfile,- omit_messages: true- })- if (!resumed?.session_id) {- throw new Error(`Remote canonical session ${pinned} did not resume`)- }- await saveBotMeta(owner, { chat: pinned })- return { runtime: resumed.session_id, stored: pinned }- }-- // A canonical title or any real history preserves the pin. Real history- // covers grandfathered/title-drifted forever chats exactly as the upstream- // interactive resolver does.- if (preferred && (isCanonicalBotChatHistory(preferred) || Number(preferred.message_count) > 0)) {- const resumed = await requestForBot(owner, 'session.resume', {- session_id: preferred.resolved_id || preferred.id || pinned,- profile: backendProfile,- omit_messages: true- })- if (!resumed?.session_id) {- throw new Error(`Remote canonical session ${pinned} did not resume`)- }- await saveBotMeta(owner, { chat: pinned })- return { runtime: resumed.session_id, stored: pinned }- }- // `null` (or an empty non-plumbing draft) is confirmed recovery territory.- }-- // Adopt-before-mint. This exact lookup must succeed: a transient list error- // is ambiguous and therefore propagates instead of forking the forever chat.- const existingResult = await requestForBot(owner, 'session.list', {- profile: backendProfile,- title: 'Bot Chat',- limit: PROFILE_SESSION_LIST_LIMIT,- include_hidden: true- })- const existing = (existingResult?.sessions || []).find(row => isCanonicalBotChatHistory(row))-- if (existing?.id) {- const resumed = await requestForBot(owner, 'session.resume', {- session_id: existing.resolved_id || existing.id,- profile: backendProfile,- omit_messages: true- })- if (!resumed?.session_id) {- throw new Error(`Remote canonical session ${existing.id} did not resume`)- }- await saveBotMeta(owner, { chat: existing.id })- return { runtime: resumed.session_id, stored: existing.id }- }-- const created = await requestForBot(owner, 'session.create', {- profile: backendProfile,- title: 'Bot Chat',- hidden: true- })- const stored = created?.stored_session_id || null-- if (stored) {- await saveBotMeta(owner, { chat: stored })- }-- return { runtime: created?.session_id || null, stored }-}--/** Bounded reply poll on the recipient's session — same shape as a group- * member turn: wait for a NEW assistant message after `before`, or time out. */-async function pollRemoteDmReply(route, profile, sessionRef, before) {- const deadline = Date.now() + REMOTE_DM_TIMEOUT_MS- const backendProfile = route.targetProfile || profile-- while (Date.now() < deadline) {- await new Promise(resolve => setTimeout(resolve, REMOTE_DM_POLL_MS))-- let state = null-- try {- state = await host.requestProfile(route, 'session.resume', {- session_id: sessionRef,- profile: backendProfile- })- } catch {- continue- }-- const messages = Array.isArray(state?.messages) ? state.messages : []- const done = !state?.inflight && !state?.running-- if (messages.length > before && done) {- for (let i = messages.length - 1; i >= 0; i--) {- const msg = messages[i]-- if (msg?.role === 'assistant') {- const text = typeof msg.content === 'string'- ? msg.content- : Array.isArray(msg.content)- ? msg.content.map(p => (typeof p === 'string' ? p : p?.text || '')).join('')- : msg?.text || ''-- return String(text).trim() || null- }- }+ return botName === activeName+}- return null- }- }++function botSelectionKey(bot) {++ return bot?.sourceScoped || bot?.remoteSource ? botRosterKey(bot) : bot?.name++}+- return null++function isDefaultBot(bot) {++ const route = botConnectionRoute(bot)++++ return String(route?.profile || bot?.name || '').trim().toLowerCase() === 'default'+ }+-/** Deliver a user mention to bots on OTHER connections: into each bot's- * canonical Bot Chat, with the standard sender-attribution prefix (so the- * recipient's messaging protocol recognizes an agent-to-agent message), then- * relay the reply back as a notification. Sequential and fire-and-forget- * from the composer's perspective. */-async function deliverRemoteRosterMentions(bots, userText, sender) {- const text = String(userText || '').trim()++function newBotChat(bot) {++ if (typeof host.newChat !== 'function') {++ host.navigate?.('/')+- if (!text || typeof host.requestProfile !== 'function') {+ return+ }+- const senderName = String(sender?.name || 'the user').trim()- const senderHandle = String(sender?.handle || senderName).trim()++ host.newChat(bot?.sourceScoped || bot?.remoteSource ? botConnectionRoute(bot) : bot?.name)++}+- for (const bot of bots) {- const connectionId = String(bot?.connectionId || '').trim()- const profile = String(bot?.name || '').trim() || 'default'+/** Resolve @handles in prose against the Bot Mode roster (local + Connections).+ * Skips the bot already speaking in this chat. Unique bare names match;+ * duplicate names require the @name-device handle. */+function resolveRosterMentions(text, roster, active = {}) {+ const members = Array.isArray(roster) ? roster : []+ const prose = String(text || '').replace(/```[\s\S]*?```/g, ' ').replace(/`[^`\n]*`/g, ' ')+ const byForm = new Map()- if (!connectionId) {+ for (const bot of members) {+ if (!bot?.name || isActiveRosterBot(bot, active)) {continue}@@@ -4040,11 -3986,7 +4545,11 @@@ const canonicalCreations = new Map(const PROFILE_SESSION_LIST_LIMIT = 200let botOpenGeneration = 0+/** The one canonical title. (profile, CANONICAL_CHAT_TITLE) IS the bot's+ * forever-chat identity — see the header above. */+const CANONICAL_CHAT_TITLE = 'Bot Chat'+- async function openStoredBotChat(name, storedId, summary) {+ async function openStoredBotChat(owner, storedId, summary) {if (!storedId || typeof host.openSession !== 'function') {throw new Error('This Hermes Desktop version cannot open stored sessions')}@@@ -4064,95 -4009,77 +4572,105 @@@intent: 'main',awaitHydration: true,expectHistory,- keepAllProfilesScope: true,+ // Move the WORKSPACE onto this bot, not just the transcript.+ //+ // With the default (true) the bot's chat opened against its own backend+ // while `$activeGatewayProfile` stayed on whatever profile was active+ // before — so "New session" from inside any bot was created on that other+ // backend. Measured: four consecutive new chats started from different+ // bots all landed in the `ops` profile's state.db. Clicking a bot is a+ // workspace switch in this product (one bot = one workspace), so the- // chrome has to follow.- keepAllProfilesScope: false,++ // chrome has to follow. EXCEPT across connections: a remote bot's chat++ // opens on its own source while Desktop's chrome/API home stays put —++ // re-homing the window onto another machine for one chat is the bug++ // #90006 exists to remove.++ keepAllProfilesScope: route ? true : false,retryHydrationTimeoutOnce: true})return storedId}-/** Adopt-before-mint: the profile may already own a canonical Bot Chat that- * the pin lost track of (pin cleared during an outage, ui_meta rolled back,- * a fork squatting the title). The core UNIQUE title index guarantees at- * most ONE session titled "Bot Chat" per profile db — Profile → Named- * Session is an exact registry, so consult it exactly: `title` asks the- * gateway for an indexed WHERE title = ? lookup (window-free; a busy- * profile can push the forever-chat past any recency window, which would- * re-open the fork loop with a higher trigger threshold). Minting while a- * "Bot Chat" row exists is always wrong twice over: it forks the- * forever-chat AND the new row can never take the (already held) canonical- * title, so the next identity check misreads it and forks again — the- * infinite-fork loop. An older gateway ignores the unknown `title` param- * and returns the plain windowed listing instead — the pre-exact-lookup- * behavior — so the local scan below stays as the compatibility rung.- * include_hidden is required (canonical chats are always hidden); a gateway- * without it simply finds nothing and we fall through to mint. */+/** True when a session summary IS the canonical registry row. root_title is+ * the durable lineage-root title reported by exact-lookup gateways; plain+ * title covers windowed listings. */+function isCanonicalBotChatHistory(history) {+ const rootTitle = String(history?.root_title || '').trim()+ const title = String(history?.title || '').trim()+ return rootTitle === CANONICAL_CHAT_TITLE || (!rootTitle && title === CANONICAL_CHAT_TITLE)+}+- /** THE identity lookup: the profile's session titled exactly "Bot Chat".- * The core UNIQUE title index guarantees at most ONE such row per profile- * db — Profile → Named Session is an exact registry, so consult it exactly:- * `title` asks the gateway for an indexed WHERE title = ? lookup- * (window-free; a busy profile can push the forever-chat past any recency- * window). include_hidden is required (canonical chats are always hidden). */- async function findExistingCanonicalChat(name) {++/** THE identity lookup: the profile's session titled exactly "Bot Chat",++ * consulted on the bot's OWN source. The core UNIQUE title index guarantees++ * at most ONE such row per profile db — Profile → Named Session is an exact++ * registry, so consult it exactly: `title` asks the gateway for an indexed++ * WHERE title = ? lookup (window-free; a busy profile can push the++ * forever-chat past any recency window). include_hidden is required++ * (canonical chats are always hidden). Remote bots route via requestForBot++ * on the immutable captured owner — activation is a UI concern and never++ * authorizes this RPC. */+ async function findExistingCanonicalChat(owner) {+ const { bot, name, route } = botOwner(owner)+++ // FAIL CLOSED. A failed registry lookup MUST NOT read as "no Bot Chat+ // exists" — that is the one remaining way to fork a bot's forever chat.+ // The failure lives exactly in the post-update window: the desktop+ // restarts every profile backend, the first bot click races the warm-up,+ // the lookup RPC fails transiently, and a swallowed error here sent+ // createCanonicalChat() straight to session.create — minting a fresh+ // "Bot Chat" while the real one (data intact, hidden) still held the+ // canonical title. Users read that as "my bot lost all context after the- // update". Both open paths catch and toast "try again", which is the- // correct outcome for a transient lookup failure: retry, never mint.++ // update". Cross-connection lookups fail MORE often (network), so this++ // matters doubly for remote bots. Both open paths catch and toast "try++ // again", which is the correct outcome: retry, never mint.+ let restry {- res = await host.request('session.list', {- profile: name,- const res = await requestForBot(bot, 'session.list', {++ res = await requestForBot(bot, 'session.list', {+ profile: backendTargetProfile(route, name),- title: 'Bot Chat',+ title: CANONICAL_CHAT_TITLE,limit: PROFILE_SESSION_LIST_LIMIT,include_hidden: true})- const rows = res?.sessions ?? []- return rows.find(row => isCanonicalBotChatHistory(row)) || null- } catch {- return null+ } catch (error) {+ const detail = error instanceof Error && error.message ? ` (${error.message})` : ''+ throw new Error(`Could not check ${name}'s Bot Chat registry${detail} — not starting a new chat`)}++ const rows = res?.sessions ?? []+ return rows.find(row => isCanonicalBotChatHistory(row)) || null}-/** Create the bot's ONE forever chat: a real session opened with a kickoff- * message (the gateway prunes zero-message sessions, so the chat is born- * with the bot introducing itself). Pins the stored id in bot meta and- * returns it. Adopts an existing "Bot Chat" row instead of creating when- * the profile already has one (see findExistingCanonicalChat). */+/** Create the bot's ONE forever chat: a real session titled "Bot Chat",+ * opened with a kickoff message (the gateway prunes zero-message sessions,+ * so the chat is born with the bot introducing itself). Adopts the existing+ * "Bot Chat" row instead of creating when the profile already has one —+ * minting while a "Bot Chat" row exists is always wrong twice over: it+ * forks the forever-chat AND the new row can never take the (already held)- * canonical title. */- function createCanonicalChat(name) {- const inflight = canonicalCreations.get(name)++ * canonical title. Creates on the bot's own source via requestForBot. */+ function createCanonicalChat(owner) {- const { bot, key, name, route } = botOwner(owner)++ const { bot, name, key, route } = botOwner(owner)+ const inflight = canonicalCreations.get(key)if (inflight) {return inflight}const run = (async () => {- const existing = await findExistingCanonicalChat(name)+ const existing = await findExistingCanonicalChat(owner)if (existing?.id) {- saveBotMeta(owner, { chat: existing.id })-if (typeof host.openSession === 'function') {// The exact-lookup gateway reports the compression-lineage tip as- // resolved_id; the pin stays the durable row id (same split the- // preferred_session path uses).+ // resolved_id; open the tip, the registry row stays the identity.- await openStoredBotChat(name, existing.resolved_id || existing.id, existing)+ await openStoredBotChat(owner, existing.resolved_id || existing.id, existing)}return existing.id}- const res = await host.request('session.create', {- profile: name,+ const res = await requestForBot(bot, 'session.create', {+ profile: backendTargetProfile(route, name),- title: 'Bot Chat',+ title: CANONICAL_CHAT_TITLE,// Always born hidden from the global sidebar — Bot Mode sessions are// plugin-owned. Core applies this via the generic `hidden` flag// (deferred as pending_hidden until the row exists); older gateways@@@ -4162,22 -4089,8 +4680,22 @@@const sid = res?.stored_session_idconst runtime = res?.session_id- if (sid) {- saveBotMeta(owner, { chat: sid })+ // session.create is intentionally lazy: its stored row does not exist until+ // the first prompt. Mounting `sid` immediately therefore emits a noisy REST+ // 404 ("Session not found"), and the turn-start auto-titler can win the race+ // against the deferred `title: 'Bot Chat'` — under name-identity that is an+ // identity outage: until the row is titled, the registry has no "Bot Chat"+ // entry, so a second click during the intro turn mints a duplicate.+ // session.title materializes the row now and records a user-authority title+ // before either the open or kickoff, closing both the 404 race and the+ // untitled window. Older gateways may not support the eager write; retain+ // the kickoff-and-retry fallback below.+ if (runtime) {+ try {- await host.request('session.title', { session_id: runtime, title: CANONICAL_CHAT_TITLE })++ await requestForBot(bot, 'session.title', { session_id: runtime, title: CANONICAL_CHAT_TITLE })+ } catch {+ /* compatibility fallback: prompt.submit will persist the lazy row */+ }}// Mount the session view FIRST, then send the kickoff — submitting into@@@ -4186,7 -4099,12 +4704,12 @@@if (sid && typeof host.openSession === 'function') {try {- await host.openSession(sid, { profile: name, intent: 'main', keepAllProfilesScope: false })+ await host.openSession(sid, {+ ...(route ? { route } : {}),+ profile: name,+ intent: 'main',- keepAllProfilesScope: true++ keepAllProfilesScope: route ? true : false+ })opened = true} catch {// The stored row may not exist until the kickoff persists it. Retry@@@ -4198,14 -4116,19 +4721,19 @@@await new Promise(resolve => window.setTimeout(resolve, 400))try {- await host.request('prompt.submit', { session_id: runtime, text: 'Hey, tell me about yourself!' })+ await requestForBot(bot, 'prompt.submit', { session_id: runtime, text: 'Hey, tell me about yourself!' })if (!opened && sid && typeof host.openSession === 'function') {- await host.openSession(sid, { profile: name, intent: 'main', keepAllProfilesScope: false })+ await host.openSession(sid, {+ ...(route ? { route } : {}),+ profile: name,+ intent: 'main',- keepAllProfilesScope: true++ keepAllProfilesScope: route ? true : false+ })}} catch {- // The chat already exists. Keep the pin so the next click- // opens it instead of making a second Bot Chat.+ // The chat already exists under the canonical title — the next click+ // finds it by name instead of making a second Bot Chat.}}@@@ -4217,46 -4140,163 +4745,65 @@@return run}-/** Open the bot's ONE forever chat and return the opened id (or the pin).+/** Open the bot's ONE forever chat and return the opened registry id.*- * The whole resolution is one registry consultation: the profile's session- * titled "Bot Chat" exists → open it (lineage tip); it doesn't → create it.- * No id pointer is read or written anywhere in this path. */- async function openBotCanonicalChat(name) {- const existing = await findExistingCanonicalChat(name)- * Identity rules (hermes-agent#88200 — the row must open the session its- * preview describes):- * - grandfather: no pin + an existing Bot Chat adopts the previewed session- * (`history`, the roster's last_session for this bot) instead of minting- * a new empty chat. Ordinary user conversations are never adopted;- * `last_session` is only a recency hint, not an ownership proof;- * - a live pin is verified through the backend's precise preferred_session- * resolver (hidden rows still resolve; compression lineages resolve to- * the live tip) — never inferred from a paginated, hidden-excluding- * session.list window, which misjudged real hidden pins as gone;- * - transient lookup failures keep the pin: try the stored id as-is, and- * only a rejected open enters recovery. */-function isCanonicalBotChatHistory(history) {- const rootTitle = String(history?.root_title || '').trim()- const title = String(history?.title || '').trim()- return rootTitle === 'Bot Chat' || (!rootTitle && title === 'Bot Chat')-}++ * The whole resolution is one registry consultation ON THE BOT'S OWN++ * SOURCE: the profile's session titled "Bot Chat" exists → open it++ * (lineage tip); it doesn't → create it. No id pointer is read or written++ * 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) {++ const existing = await findExistingCanonicalChat(owner)-async function openBotCanonicalChat(owner, pinned, history) {- const { bot, name, route } = botOwner(owner)- const backendProfile = backendTargetProfile(route, name)- if (!pinned) {- // Grandfather only an actual Bot Chat. `last_session` is merely the most- // recent row for the profile; adopting it blindly can claim an unrelated- // user conversation and the hide sweep would then hide that conversation.- const adoptId = isCanonicalBotChatHistory(history) ? history.id : null- if (adoptId && typeof host.openSession === 'function') {- await openStoredBotChat(owner, adoptId, history)- saveBotMeta(owner, { chat: adoptId })- return adoptId- }- return createCanonicalChat(owner)- }-- // Precise verification. An older gateway ignores the unknown param and- // omits the key — that reads as a lookup failure below, NOT as a missing- // session, so legacy backends keep the try-as-is escape hatch.- let preferred- let lookupFailed = false- try {- const res = await requestForBot(bot, 'profiles.list', {- include_sessions: true,- preferred_session_ids: { [backendProfile]: pinned }- })- const row = (res?.profiles ?? []).find(p => p.name === backendProfile)- preferred = row?.preferred_session- if (preferred === undefined) {- lookupFailed = true- }- } catch {- lookupFailed = true- }-- if (lookupFailed) {- // Transient gateway state (or an older backend): the pin is innocent- // until proven guilty — try it as-is. A rejected open is still ambiguous:- // it can be the same reconnect/hydration outage that broke this lookup, so- // preserve the forever-chat pin and surface Retry instead of forking it.- return openStoredBotChat(owner, pinned, history)- }-- if (preferred && isCanonicalBotChatHistory(preferred)) {- try {- await openStoredBotChat(owner, preferred.resolved_id || preferred.id, preferred)- return pinned- } catch (error) {- // The precise lookup JUST confirmed this session exists, so a failed- // open is transient (reconnect, backend restart). Clearing the pin or- // minting a replacement here would fork the bot's forever-chat on- // every hiccup — report and keep everything as it is.- throw error- }+ if (existing?.id && typeof host.openSession === 'function') {- await openStoredBotChat(name, existing.resolved_id || existing.id, existing)++ await openStoredBotChat(owner, existing.resolved_id || existing.id, existing)+ return existing.id}- return createCanonicalChat(name)- if (preferred) {- // The stored pointer resolved to a real session, but not to Bot Mode's- // titled plumbing session. Two legitimate ways to get here, and neither- // means "mint a new chat":- // - the pin IS the forever-chat but its title drifted (grandfathered- // pre-convention chats; the LLM auto-titler renaming an untitled row- // after a silent unique-title conflict dropped "Bot Chat"). A pinned- // session carrying real history is the user's conversation — forking- // away from it silently loses their thread, the exact bug this whole- // resolver exists to prevent. The pin is the durable intent: keep it- // and open it, even when some other (likely forked) row holds the- // "Bot Chat" title. The hide sweep only matches plumbing titles, so- // an adopted odd-titled chat is never swept out of the user's- // ordinary session list.- // - the pin resolves to an EMPTY non-plumbing session (a stray draft):- // genuinely corrupted metadata. Clear it — createCanonicalChat then- // adopts the profile's existing "Bot Chat" row if one exists before- // ever creating a new one.- const messageCount = Number(preferred.message_count) || 0-- if (messageCount > 0) {- await openStoredBotChat(owner, preferred.resolved_id || preferred.id, preferred)- return pinned- }-- await saveBotMeta(owner, { chat: null })- return createCanonicalChat(owner)- }-- // Definitively gone (db reset, or the lineage was rewritten past- // recovery): re-anchor on the previewed session when there is one.- // A previewed row is safe to re-anchor only when it is Bot Mode plumbing.- // Otherwise a stale pin must not steal the profile's ordinary latest chat.- const recoveryId = isCanonicalBotChatHistory(history) ? history.id : null- if (recoveryId && typeof host.openSession === 'function') {- await openStoredBotChat(owner, recoveryId, history)- saveBotMeta(owner, { chat: recoveryId })- return recoveryId- }- saveBotMeta(owner, { chat: null })+ return createCanonicalChat(owner)}-async function prepareBotSource(bot, pinnedChat) {- if (!bot.sourceScoped || pinnedChat) {- return pinnedChat+async function prepareBotSource(bot) {+ if (!bot.sourceScoped) {+ return}- if (typeof host.ensureAgent !== 'function') {- // Thin rows deliberately omit metadata. Read it on the captured owner- // route; activation is a UI concern and cannot authorize this RPC.- try {- const route = botConnectionRoute(bot)- const backendProfile = backendTargetProfile(route, bot.name)- const refreshed = await requestForBot(bot, 'profiles.list', {})- const owner = refreshed?.profiles?.find(profile => profile.name === backendProfile)++ // Cross-connection RPCs ride the immutable captured route (requestForBot →++ // host.requestProfile) — Desktop's active connection does not move, and++ // activation is a UI concern that never authorizes the calls. All this++ // gate does is refuse when the desktop predates routed profile requests.++ const route = botConnectionRoute(bot)+- return owner?.ui_meta?.['hermes-bots']?.chat || null- } catch {- // Metadata refresh is best-effort; canonical creation remains the fallback.- return null++ if (route && typeof host.requestProfile !== 'function') {+ throw new Error('Update Hermes Desktop to chat with agents on other connections.')+ }+- await host.ensureAgent(bot.connectionId, bot.name)++ if (!route && typeof host.ensureAgent === 'function') {++ // Source-annotated row on the ACTIVE connection (no captured route):++ // legacy activation path, unchanged.++ await host.ensureAgent(bot.connectionId, bot.name)+ }+ }- if (!bot.remoteSource) {- return+ async function ensureBotMetadata(bot) {+ if (!bot?.sourceScoped) {+ return botRosterMeta(bot, $botMeta.get()) || {}}- const liveId = String(typeof host.activeConnectionId === 'function' ? host.activeConnectionId() || '' : '').trim()- const targetId = String(bot.connectionId || '').trim()+ const route = botConnectionRoute(bot)+ const backendProfile = backendTargetProfile(route, bot.name)+ const result = await requestForBot(bot, 'profiles.list', {})+ const row = (result?.profiles || []).find(profile => profile?.name === backendProfile)+ const server = row?.ui_meta?.['hermes-bots']- if (targetId && targetId !== 'local' && liveId !== targetId) {- throw new Error(`Still on ${liveId || 'this device'}, not ${bot.connectionLabel || targetId}`)+ if (server && typeof server === 'object') {+ const key = botMetaKey(bot)+ $botMeta.set({ ...$botMeta.get(), [key]: { ...($botMeta.get()[key] || {}), ...server } })+ persistBotMetaSnapshot($botMeta.get(), true)}- // The canonical chat is found by NAME on the now-active owner source —- // there is no per-source pointer to recover.+ return botRosterMeta(bot, $botMeta.get()) || {}}function displayName(bot, meta) {@@@ -4795,10 -4834,10 +5345,11 @@@ async function disbandGroupChat(group,log: room.log,watermarks: room.watermarks,sessions: room.sessions || {},+ sessionOwners: room.sessionOwners || {},members: Array.isArray(room.members) ? room.members : [],roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,- image: room.image || null+ image: room.image || null,+ syncRevision: Math.max(0, Number(room.syncRevision || 0))}}}@@@ -6025,28 -6005,20 +6593,18 @@@ function BotRow({ bot, onDelete, onEditconst generation = ++botOpenGenerationhaptic('tap')$groupChatWorkspace.set(null)- $selectedBot.set(bot.name)-- if (bot.remoteSource) {- const handle = botHandle(bot.name, bot)- host.notify?.({- kind: 'info',- title: displayName(bot),- message: `Stay in this chat and @${handle} to message them. Gateway stays on this device.`- })- return- }+ $selectedBot.set(botSelectionKey(bot))- if (!bot.remoteSource && $botUnread.get()[bot.name]) {- let pinnedChat = meta?.chat-+ if ($botUnread.get()[botSelectionKey(bot)]) {const next = { ...$botUnread.get() }- delete next[bot.name]+ delete next[botSelectionKey(bot)]$botUnread.set(next)}- // Activate the owner first so every canonical-chat RPC lands on the- // backend that owns this bot's state database.+ // Refresh through the immutable owner route. Foreground activation is+ // presentation state and is never routing authority for this open.try {- pinnedChat = await prepareBotSource(bot, pinnedChat)+ await prepareBotSource(bot)} catch (error) {host.notifyError?.(error, `Could not reach ${bot.connectionLabel || 'the remote source'}`)@@@ -6058,10 -6030,7 +6616,11 @@@}try {- const id = await openBotCanonicalChat(bot, pinnedChat, previewSession)+ // Identity is the NAMED registry row (profile → session titled- // "Bot Chat"), resolved fresh on every click — preview identity and- // click identity agree because both describe that same row (#88200).- const id = await openBotCanonicalChat(bot.name)++ // "Bot Chat") on the bot's own source, resolved fresh on every click —++ // preview identity and click identity agree because both describe that++ // same row (#88200).++ const id = await openBotCanonicalChat(bot)if (generation === botOpenGeneration && id) {return@@@ -8672,18 -8689,14 +9278,18 @@@ function CreateRoutineDialog({ bot, opesched.freq !== 'once' && sched.freq !== 'advanced' && String(sched.repeatN || '').trim()? Math.max(1, parseInt(sched.repeatN, 10) || 1): null- await host.request('cron.manage', {+ await requestForBot(bot, 'cron.manage', {action: 'add',- name: `[bot:${bot}] ${title}`,+ name: `[bot:${profile}] ${title}`,schedule: schedule.trim(),- prompt: routinePrompt(bot, title, task, activeProfile),- ...(bot ? { profile: bot } : {}),+ prompt: routinePrompt(profile, title, task, activeProfile),+ ...(profile ? { profile } : {}),...(repeatN ? { repeat: repeatN } : {}),- ...(continuity ? { continuity: true } : {})+ ...(continuity ? { continuity: true } : {}),+ // 'bot-chat' (bare, no name): the job is created IN the bot's own+ // cron store (profile scoping above), so the scheduler resolves the+ // token to that profile — no cross-gateway name ambiguity possible.+ ...(target === 'bot-chat' ? { deliver: 'bot-chat' } : {})})await invalidateRoutineOwner(bot)host.notify({ kind: 'success', message: `Cronjob "${title}" scheduled` })@@@ -11119,7 -11041,11 +11748,7 @@@ function BotsPane()}try {- const id = await openBotCanonicalChat(bot.name)- const id = await openBotCanonicalChat(- bot,- pinnedChat,- bot.preferred_session || bot.last_session- )++ const id = await openBotCanonicalChat(bot)if (generation === botOpenGeneration && id) {returndiff --cc apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-creation.test.mjsindex 4174413ce98,2395bf92625..d965d72ee53--- 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@@@ -8,8 -8,14 +8,13 @@@ const source = readFileSync(new URL('..function loadCanonicalCreation({ openSession, request }) {const start = source.indexOf('const canonicalCreations = new Map()')const end = source.indexOf('function displayName(', start)- const saved = []const context = {host: { openSession, request },- saveBotMeta: (name, patch) => saved.push({ name, patch }),+ backendTargetProfile: (route, name) => route?.targetProfile || name,- botOwner: name => ({ bot: { name }, key: name, name, route: null }),++ 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),- $hideBotChats: { get: () => false },window: { setTimeout: callback => callback() }}const section = sourcediff --cc apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjsindex f5d242ae4ec,00000000000..1fb3ad1edffmode 100644,000000..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@@@ -1,224 -1,0 +1,234 @@@+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,++ 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 {}+ }+ })++ assert.equal(await runtime.openBotCanonicalChat('ops'), '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, false,+ 'opening a bot moves the workspace onto that bot')++ 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 {}+ }+ })++ assert.equal(await runtime.openBotCanonicalChat('ops'), 'root-1',+ 'the durable registry id is returned')+ 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 only the bot name — identity needs nothing else', () => {- assert.match(source, /async function openBotCanonicalChat\(name\) \{/)++test('openBotCanonicalChat takes only the bot owner — identity needs nothing else', () => {++ // 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\) \{/)+})++// ── 2. no registry row → create ─────────────────────────────────────────────++test('no registry row mints a hidden "Bot Chat" session with the intro kickoff', async () => {+ 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 {}+ }+ })++ assert.equal(await runtime.openBotCanonicalChat('newbie'), '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)+ const kickoff = runtime.requests.find(r => r.method === 'prompt.submit')+ assert.equal(kickoff?.params?.session_id, 'rt-1')+})++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 {}+ }+ })++ assert.equal(await runtime.openBotCanonicalChat('ops'), 'fresh-2',+ 'no row titled "Bot Chat" → create; never adopt an ordinary conversation')+ 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 --cc apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjsindex 8d973a82c00,3b2a67d9796..b37c29cbe49--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs@@@ -62,6 -65,20 +65,12 @@@ test('hideOwnedBotSessions sweeps roomreturn {}}},- $botMeta: { get: () => ({ alpha: { chat: 'chat-a' }, beta: { chat: 'chat-b' }, gamma: {} }) },- $lastRoster: { get: () => [{ name: 'alpha' }, { name: 'beta' }] },++ $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' } },@@@ -81,17 -97,147 +90,126 @@@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 }) },+ $botMeta: { get: () => ({}) },+ $lastRoster: { get: () => [] },+ $groupChats: {+ get: () => ({+ Core: {+ sessions: { 'source-a::worker': 'remote-room-1' },+ members: [owner]+ }+ })+ },+ groupMemberKey: member => `${member.route.connectionId}::${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-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].bot.route.connectionId, 'source-a')+ assert.equal(routed[0].bot.route.targetProfile, 'backend-worker')+ assert.equal(routed[0].params.session_id, '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 }) },+ $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}`,+ 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-collision.js' })++ await context.__h.hideOwnedBotSessions()++ assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)+ assert.deepEqual(routed.map(call => call.bot.route.connectionId).sort(), ['source-a', 'source-b'])+ assert.ok(routed.every(call => call.params.session_id === '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('safety: a stale canonical pointer to an ordinary session is not hidden', async () => {- const start = source.indexOf('function hideOwnedBotSessions()')- const end = source.indexOf('/** Fetch server-side avatars', start)- const calls = []- const context = {- host: {- request: async (method, params) => {- calls.push({ method, params })- if (method === 'profiles.list') {- return {- profiles: [{ name: 'default', preferred_session: { id: 'ordinary-1', title: '生产调度会优化' } }]- }- }- return {}- }- },- $botMeta: { get: () => ({ default: { chat: 'ordinary-1' } }) },- $groupChats: { get: () => ({}) },- $lastRoster: { get: () => [{ name: 'default' }] },- backendTargetProfile: (route, name) => route?.targetProfile || name,- botConnectionRoute: () => null,- botMetaKey: bot => bot.name,- requestForBot: (_bot, method, params) => context.host.request(method, params),- sweepBotProfileSessions: async () => undefined- }- const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')- vm.runInNewContext(section, context, { filename: 'h-stale.js' })- await context.__h.hideOwnedBotSessions()-- assert.equal(calls.some(c => c.method === 'session.set_hidden'), false)-})-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 /@@@ -154,8 -300,12 +272,12 @@@ test('hideOwnedBotSessions chains the otest('the canonical-chat adoption scan lists with include_hidden', () => {// The one session.list consumer that must see the always-hidden rows:- // findExistingCanonicalChat (adopt-before-mint) — canonical Bot Chats are- // born hidden, so a visible-only scan would miss the very row whose- // existence forbids minting. (Pin recovery goes through profiles.list- // preferred_session_ids, whose resolver already sees 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.- assert.match(source, /include_hidden: true\s*\}\)\s*\} catch \(error\) \{[\s\S]{0,400}?const rows = res\?\.sessions \?\? \[\]\s*return rows\.find\(row => isCanonicalBotChatHistory\(row\)\)/)++ // 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\S]*title: 'Bot Chat',[\s\S]*include_hidden: true[\s\S]*return rows\.find\(row => isCanonicalBotChatHistory\(row\)\)/++ /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,400}?const rows = res\?\.sessions \?\? \[\]\s*return rows\.find\(row => isCanonicalBotChatHistory\(row\)\)/+ )})diff --cc apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjsindex 971ba37980b,e62f5f11a78..a79bfeb3c7e--- a/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/profile-prewarm.test.mjs@@@ -26,8 -26,9 +26,12 @@@ function renderBotRow(input = 'alpha')const name = bot.nameconst prepareSource = sourceBetween('async function prepareBotSource(', 'function displayName(')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 => ({@@@ -52,6 -54,11 +57,9 @@@$lastRoster: atom([]),$selectedBot: atom('default'),botAppearance: () => ({ shape: 'round', color: '#000', image: null }),- botConnectionRoute: value => value.route || null,- backendTargetProfile: (route, fallback) => route?.targetProfile || route?.profile || fallback,+ botMetaKey: value => value.sourceScoped+ ? `${value.route?.connectionId || value.connectionId}::${value.name}`+ : value.name,botGroups: () => [],botHandle: value => value,botOpenGeneration: 0,@@@ -79,6 -97,6 +98,10 @@@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 =>@@@ -99,7 -126,7 +131,7 @@@useValue: store => store.get()}-- vm.runInNewContext(`${activitySessionSource()}\n${prepareSource}\n${botRowSource}\nglobalThis.BotRow = BotRow`, context)++ vm.runInNewContext(`${activitySessionSource()}\n${routeSource}\n${prepareSource}\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@@@ -203,6 -262,6 +267,7 @@@ test('behavior: remote default never ophost: {state: { gateway: atom('open'), profile: atom('default') },ensureAgent: async (connectionId, profile) => ensured.push([connectionId, profile]),++ requestProfile: async () => ({}),activeConnectionId: () => 'local',warmAgent: () => undefined,warmProfile: () => undefined,@@@ -221,7 -280,7 +286,8 @@@useValue: store => store.get()}-- vm.runInNewContext(`${activitySessionSource()}\n${prepareSource}\n${botRowSource}\nglobalThis.BotRow = BotRow`, context)++ const routeSource = sourceBetween('function botConnectionRoute(', 'function rewriteCliProfileOperands(')++ vm.runInNewContext(`${activitySessionSource()}\n${routeSource}\n${prepareSource}\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.childrendiff --cc apps/desktop/src/plugins/hermes-bots/tests/remote-routing-races.test.mjsindex 00000000000,f39e46ec915..f53786c4e87mode 000000,100644..100644--- 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.mjs@@@ -1,0 -1,625 +1,634 @@@+ 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, storage } = {}) {+ 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 => calls.push(['newChat', route]),+ 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 {}+ }),+ 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,+ 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 } }+ }+ })+- const prepared = await runtime.context.__race.prepareBotSource(workerBot, null)- assert.equal(prepared, 'worker-chat')++ // 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 reuses a canonical pin through the backend profile name', async () => {++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])- return {- profiles: [{- name: 'backend-worker',- preferred_session: {- id: 'pin-worker',- resolved_id: 'pin-worker-tip',- message_count: 3- }- }]++ 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,- 'pin-worker',- { message_count: 3 }- )++ const result = await runtime.context.__race.openBotCanonicalChat(workerBot)+- assert.equal(result, 'pin-worker')- assert.deepEqual(JSON.parse(JSON.stringify(requests[0])), [- 'profiles.list',- {- include_sessions: true,- preferred_session_ids: { 'backend-worker': 'pin-worker' }- }- ])++ assert.equal(result, 'worker-chat')++ 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], 'pin-worker-tip')++ assert.equal(opened[1], 'worker-chat-tip', 'the lineage tip opens; the registry row stays the identity')++})++++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, 'stored-remote', { message_count: 2 })++ 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'))+ })+++ 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 }))+ })