fix(desktop): cross-machine bot DMs — canonical chat, sender attribution, reply relay
Follow-up to #88664. The remote @mention delivery path had three gaps that made cross-machine DMs half-work: 1. No reply relay: deliverRemoteRosterMentions submitted the prompt and toasted, but never polled — the handoff note promised a relay that never came. Now a bounded poll (same shape as a group member turn: new assistant message after the baseline, 180s cap) relays the recipient's reply as a notification, or says it's still pending. 2. No sender attribution: the raw user text was submitted, so the recipient's messaging protocol never recognized an agent-to-agent message. Deliveries now carry the standard "Message from 🤖 <sender> (@handle):" prefix. 3. Duplicate Bot Chats: every mention minted a fresh "Bot Chat" session. ensureRemoteCanonicalChat now resolves the recipient's pinned canonical chat from its profile ui_meta, falls back to resume-by-title, and only creates when neither exists — mirroring ensureGroupChatSession. Tests: remote-dm-delivery.test.mjs (pin-resume without create, attribution prefix + reply relay via vm-run behavior tests, source contract for the bounded poll). Plugin suite 187/187.
This commit is contained in:
@@ -2485,13 +2485,109 @@ function resolveRosterMentions(text, roster, active = {}) {
|
||||
return mentioned
|
||||
}
|
||||
|
||||
async function deliverRemoteRosterMentions(bots, userText) {
|
||||
const REMOTE_DM_TIMEOUT_MS = 180000
|
||||
const REMOTE_DM_POLL_MS = 2000
|
||||
|
||||
/** The remote bot's canonical Bot Chat: pinned stored-id from its profile's
|
||||
* ui_meta first, then resume-by-title, then create. Mirrors
|
||||
* ensureGroupChatSession so DMs land in the ONE forever-chat instead of
|
||||
* minting a fresh "Bot Chat" per mention. */
|
||||
async function ensureRemoteCanonicalChat(route, profile) {
|
||||
let pinned = null
|
||||
|
||||
try {
|
||||
const listed = await host.requestProfile(route, 'profiles.list', {})
|
||||
const owner = listed?.profiles?.find(p => p.name === profile)
|
||||
pinned = owner?.ui_meta?.['hermes-bots']?.chat || null
|
||||
} catch {
|
||||
/* older remote gateway — title lookup below still works */
|
||||
}
|
||||
|
||||
for (const target of [pinned, 'Bot Chat']) {
|
||||
if (!target) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await host.requestProfile(route, 'session.resume', {
|
||||
session_id: target,
|
||||
profile,
|
||||
omit_messages: true
|
||||
})
|
||||
|
||||
if (res?.session_id) {
|
||||
return { runtime: res.session_id, stored: res.session_key || pinned }
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
}
|
||||
|
||||
const created = await host.requestProfile(route, 'session.create', {
|
||||
profile,
|
||||
title: 'Bot Chat',
|
||||
...($hideBotChats.get() ? { hidden: true } : {})
|
||||
})
|
||||
|
||||
return { runtime: created?.session_id || null, stored: created?.stored_session_id || null }
|
||||
}
|
||||
|
||||
/** 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
|
||||
|
||||
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 })
|
||||
} 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 null
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** 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()
|
||||
|
||||
if (!text || typeof host.requestProfile !== 'function') {
|
||||
return
|
||||
}
|
||||
|
||||
const senderName = String(sender?.name || 'the user').trim()
|
||||
const senderHandle = String(sender?.handle || senderName).trim()
|
||||
|
||||
for (const bot of bots) {
|
||||
const connectionId = String(bot?.connectionId || '').trim()
|
||||
const profile = String(bot?.name || '').trim() || 'default'
|
||||
@@ -2500,30 +2596,55 @@ async function deliverRemoteRosterMentions(bots, userText) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const created = await host.requestProfile(
|
||||
{ connectionId, profile, mode: 'remote', targetProfile: profile },
|
||||
'session.create',
|
||||
{ profile, title: 'Bot Chat', hidden: true }
|
||||
)
|
||||
const sessionId = created?.session_id
|
||||
const route = { connectionId, mode: 'remote', profile, targetProfile: profile }
|
||||
const label = bot.connectionLabel || connectionId
|
||||
|
||||
if (!sessionId) {
|
||||
try {
|
||||
const { runtime, stored } = await ensureRemoteCanonicalChat(route, profile)
|
||||
|
||||
if (!runtime) {
|
||||
throw new Error('No remote session')
|
||||
}
|
||||
|
||||
await host.requestProfile(
|
||||
{ connectionId, profile, mode: 'remote', targetProfile: profile },
|
||||
'prompt.submit',
|
||||
{ session_id: sessionId, text }
|
||||
)
|
||||
// Baseline before our submit, so the poll can spot the NEW reply.
|
||||
let before = 0
|
||||
|
||||
try {
|
||||
const pre = await host.requestProfile(route, 'session.resume', { session_id: stored || runtime, profile })
|
||||
before = Array.isArray(pre?.messages) ? pre.messages.length : pre?.message_count || 0
|
||||
} catch {
|
||||
/* lazy session — zero messages */
|
||||
}
|
||||
|
||||
// The delivery prefix is the recipient's cue that an agent (not its
|
||||
// human) is talking — same contract as the local CLI handoff.
|
||||
await host.requestProfile(route, 'prompt.submit', {
|
||||
session_id: runtime,
|
||||
text: `Message from \u{1F916} ${senderName} (@${senderHandle}): ${text}`
|
||||
})
|
||||
host.notify?.({
|
||||
kind: 'info',
|
||||
title: displayName(bot),
|
||||
message: `Messaged @${botHandle(profile, bot)} on ${bot.connectionLabel || connectionId} from this chat.`
|
||||
message: `Messaged @${botHandle(profile, bot)} on ${label} — will relay the reply here.`
|
||||
})
|
||||
|
||||
const reply = await pollRemoteDmReply(route, profile, stored || runtime, before)
|
||||
|
||||
if (reply) {
|
||||
host.notify?.({
|
||||
kind: 'info',
|
||||
title: `\u{1F916} ${displayName(bot)} (${label})`,
|
||||
message: reply.slice(0, 500)
|
||||
})
|
||||
} else {
|
||||
host.notify?.({
|
||||
kind: 'info',
|
||||
title: displayName(bot),
|
||||
message: `No reply from @${botHandle(profile, bot)} yet — check its Bot Chat on ${label}.`
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
host.notifyError?.(error, `Could not reach ${bot.connectionLabel || profile}`)
|
||||
host.notifyError?.(error, `Could not reach ${label}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7862,12 +7983,15 @@ export default {
|
||||
const localMentions = mentionedBots.filter(bot => !bot.remoteSource)
|
||||
const remoteMentions = mentionedBots.filter(bot => bot.remoteSource)
|
||||
|
||||
if (remoteMentions.length && typeof host.requestProfile === 'function') {
|
||||
void deliverRemoteRosterMentions(remoteMentions, text)
|
||||
}
|
||||
|
||||
const activeMeta = $botMeta.get()[live.name]
|
||||
const senderName = displayName({ name: live.name, title: activeMeta?.title }, activeMeta)
|
||||
|
||||
if (remoteMentions.length && typeof host.requestProfile === 'function') {
|
||||
void deliverRemoteRosterMentions(remoteMentions, text, {
|
||||
name: senderName,
|
||||
handle: botHandle(live.name)
|
||||
})
|
||||
}
|
||||
let note = ''
|
||||
|
||||
if (localMentions.length) {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
|
||||
// Cross-machine bot DMs: a remote @mention must land in the recipient's
|
||||
// CANONICAL Bot Chat (pinned id → title → create, never a fresh session per
|
||||
// mention), carry the "Message from 🤖 <sender> (@handle):" attribution
|
||||
// prefix so the recipient's messaging protocol recognizes an agent-to-agent
|
||||
// message, and poll for the reply so it can be relayed back.
|
||||
|
||||
const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')
|
||||
|
||||
function runtime(hostOverrides = {}) {
|
||||
const context = {
|
||||
console,
|
||||
setTimeout: fn => {
|
||||
fn()
|
||||
return 0
|
||||
},
|
||||
clearTimeout: () => undefined,
|
||||
Date,
|
||||
URL,
|
||||
atom: initial => {
|
||||
let value = initial
|
||||
return { get: () => value, set: next => (value = next), listen: () => () => undefined }
|
||||
},
|
||||
host: {
|
||||
request: async () => ({}),
|
||||
requestProfile: async () => ({}),
|
||||
notify: () => undefined,
|
||||
notifyError: () => undefined,
|
||||
state: {
|
||||
profile: { get: () => 'default', listen: () => undefined },
|
||||
connectionId: { get: () => 'local', listen: () => undefined },
|
||||
gateway: { listen: () => undefined }
|
||||
},
|
||||
...hostOverrides
|
||||
},
|
||||
document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } }
|
||||
}
|
||||
const code = pluginSource
|
||||
.replace(/^import\s+\*\s+as\s+sdk\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
|
||||
.replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')
|
||||
.replace(/^const \{ McpTab, ToolsetConfigPanel \} = sdk\r?\n/m, '')
|
||||
.replace(/^import .* from 'react'\r?\n/m, '')
|
||||
.replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
|
||||
.replace('export default {', 'globalThis.plugin = {')
|
||||
.concat('\nglobalThis.__dm = { deliverRemoteRosterMentions, ensureRemoteCanonicalChat };\n')
|
||||
vm.runInNewContext(code, context, { filename: 'plugin.js' })
|
||||
return context
|
||||
}
|
||||
|
||||
test('remote DM resumes the pinned canonical Bot Chat instead of creating a new session', async () => {
|
||||
const calls = []
|
||||
const ctx = runtime({
|
||||
requestProfile: async (route, method, params) => {
|
||||
calls.push([method, params])
|
||||
|
||||
if (method === 'profiles.list') {
|
||||
return { profiles: [{ name: 'dixie', ui_meta: { 'hermes-bots': { chat: 'stored-42' } } }] }
|
||||
}
|
||||
|
||||
if (method === 'session.resume' && params.session_id === 'stored-42') {
|
||||
return { session_id: 'runtime-9', session_key: 'stored-42', messages: [] }
|
||||
}
|
||||
|
||||
if (method === 'session.resume') {
|
||||
return { session_id: 'runtime-9', messages: [{ role: 'assistant', content: 'done' }], inflight: false, running: false }
|
||||
}
|
||||
|
||||
return {}
|
||||
}
|
||||
})
|
||||
|
||||
const { runtime: rt, stored } = await ctx.__dm.ensureRemoteCanonicalChat(
|
||||
{ connectionId: 'mac-mini', mode: 'remote', profile: 'dixie', targetProfile: 'dixie' },
|
||||
'dixie'
|
||||
)
|
||||
|
||||
assert.equal(rt, 'runtime-9')
|
||||
assert.equal(stored, 'stored-42')
|
||||
assert.ok(!calls.some(([method]) => method === 'session.create'), 'must not mint a fresh session when the pin resumes')
|
||||
})
|
||||
|
||||
test('remote DM carries sender attribution and relays the reply', async () => {
|
||||
const submits = []
|
||||
const notices = []
|
||||
const ctx = runtime({
|
||||
requestProfile: async (route, method, params) => {
|
||||
if (method === 'profiles.list') {
|
||||
return { profiles: [] }
|
||||
}
|
||||
|
||||
if (method === 'session.resume' && params.session_id === 'Bot Chat' && params.omit_messages) {
|
||||
return { session_id: 'runtime-1', session_key: 'stored-1' }
|
||||
}
|
||||
|
||||
if (method === 'prompt.submit') {
|
||||
submits.push(params.text)
|
||||
return {}
|
||||
}
|
||||
|
||||
if (method === 'session.resume') {
|
||||
// First (baseline) read: empty. After submit: reply present.
|
||||
return submits.length
|
||||
? { messages: [{ role: 'user', content: 'x' }, { role: 'assistant', content: 'disk is 40% full' }], inflight: false, running: false }
|
||||
: { messages: [] }
|
||||
}
|
||||
|
||||
return {}
|
||||
},
|
||||
notify: notice => notices.push(notice)
|
||||
})
|
||||
|
||||
await ctx.__dm.deliverRemoteRosterMentions(
|
||||
[{ name: 'dixie', connectionId: 'mac-mini', connectionLabel: 'Mac Mini', remoteSource: true }],
|
||||
'what is the disk space?',
|
||||
{ name: 'Hermes', handle: 'hermes' }
|
||||
)
|
||||
|
||||
assert.equal(submits.length, 1)
|
||||
assert.match(submits[0], /^Message from 🤖 Hermes \(@hermes\): what is the disk space\?$/u)
|
||||
assert.ok(
|
||||
notices.some(notice => /disk is 40% full/.test(notice?.message || '')),
|
||||
'the recipient reply must be relayed back as a notification'
|
||||
)
|
||||
})
|
||||
|
||||
test('source contract: DM poll shares the group-turn shape (bounded, new-assistant-message)', () => {
|
||||
assert.match(pluginSource, /const REMOTE_DM_TIMEOUT_MS = /)
|
||||
assert.match(pluginSource, /pollRemoteDmReply/)
|
||||
assert.match(pluginSource, /Message from \\u\{1F916\} \$\{senderName\} \(@\$\{senderHandle\}\)/)
|
||||
})
|
||||
Reference in New Issue
Block a user