Skip to content

The agent that grows with you

fix(desktop/bots): outside writes into member sessions surface on room open (#93813)

teknium1099d19a512b3
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
index fa4008aaa0b..4bee0f42b57 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
@@ -74,6 +74,7 @@ import { GroupClarifyCard, GroupImageControls, GroupMentionInput } from './group
import type { GroupRoomPrompt } from './group-chat-parts'
import { GroupMemberPicker } from './group-chat-view-members'
import { compressGroupMemberHistory } from './group-compress'
+import { sweepExternalGroupWrites } from './group-external-writes'
import { GroupHoldStatus } from './group-hold-status'
import {
botGroups,
@@ -1473,6 +1474,10 @@ export function openGroupChat(group: string): void {
})
const ownerKey = groupWorkspaceOwnerKey(group)
setBotsWorkspaceOwner(ownerKey, null, 'New group conversations start in the group composer.')
+ // #93813: what reached the members' room sessions while nobody drove them
+ // (a Bot posting reports into its own session, a CLI resume) is posted as
+ // the room opens, not only once the room next drives that member.
+ void sweepExternalGroupWrites(group, groupChatMemberBots(group, $lastRoster.get(), $botMeta.get()))
if (typeof host.openWorkspace === 'function') {
try {
diff --git a/apps/desktop/src/plugins/hermes-bots/group-external-writes.test.ts b/apps/desktop/src/plugins/hermes-bots/group-external-writes.test.ts
index c2968c64223..3cbb723c2b9 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-external-writes.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-external-writes.test.ts
@@ -135,13 +135,50 @@ describe('external writes into a member session', () => {
])
})
- it('leave room-fed prompts and their replies alone', async () => {
- const room = await loadRoom(createGroupGateway(options))
+ it('leave room-fed prompts alone and surface outside writes on room open, without a drive', async () => {
+ const gateway = createGroupGateway(options)
+ const room = await loadRoom(gateway)
+ const view = await import('./group-chat-view')
const thread = await drive(room, 'hello room')
await drive(room, 'second', thread)
expect(texts(room)).toEqual(['hello room', 'room reply 1', 'second', 'room reply 2'])
expect(room.gateway.calls).toHaveLength(2)
+
+ // Nobody drives the room: a peer asks the member something in its session,
+ // the agent answers a compaction handoff and a cron delivery (plumbing rows
+ // the room never speaks for), then the user merely opens the room.
+ const key = room.membership.groupSessionKey(thread, MEMBER)
+ const session = gateway.sessions.get(String(room.chat.$groupChats.get().Room.sessions?.[key]))!
+ session.messages.push(
+ { content: 'manager: status?', role: 'user' },
+ { content: 'status report: all green', role: 'assistant' },
+ { content: '[CONTEXT COMPACTION — REFERENCE ONLY] summary…', role: 'user' },
+ { content: 'noted the summary', role: 'assistant' },
+ { content: 'Cronjob Response: nightly\nran', role: 'user' },
+ { content: 'cron acknowledged', role: 'assistant' },
+ { content: 'continue', display_kind: 'auto_continue', role: 'user' } as never,
+ { content: 'nudged answer', role: 'assistant' }
+ )
+
+ // The member sits on this Desktop's roster, as it does in production; the
+ // stored descriptor alone would read as a remote seat.
+ const data = await import('./data')
+ data.$lastRoster.set([{ name: 'research' }] as never)
+ data.$botMeta.set({ research: { groups: ['Room'] } } as never)
+
+ view.openGroupChat('Room')
+ await drain(() => texts(room).length < 6)
+
+ expect(texts(room)).toEqual([
+ 'hello room',
+ 'room reply 1',
+ 'second',
+ 'room reply 2',
+ 'manager: status?',
+ 'status report: all green'
+ ])
+ expect(room.gateway.calls).toHaveLength(2)
})
})
diff --git a/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts b/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts
index 6c53afbe368..37881d08178 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-external-writes.ts
@@ -12,23 +12,40 @@
* Cursor identity is the SESSION key (`thread:<t>::<memberKey>`): one member
* owns one session per thread, and a cursor shared across threads would skip
* one thread's rows after another thread's sweep advanced it.
+ *
+ * The cursor is an absolute row index into the transcript `session.resume`
+ * reports. Two edges follow from that:
+ * - First sight of a session (no cursor yet — a room hydrated from the
+ * gateway mirror, which does not carry cursors, or one that predates this
+ * sweep) seeds the cursor at the transcript's current length. Trade-off:
+ * "late, never lost" holds from that moment on, but history already in the
+ * session is not replayed — a second Desktop taking the room over would
+ * otherwise post every historical external row again.
+ * - Compaction shrinks the transcript. A cursor past the current end is
+ * reset to the end: whatever compaction folded away is gone from the
+ * view anyway, and the alternative (waiting for the session to regrow past
+ * the old length) starts the next slice mid-exchange.
*/
import { $groupChats, appendGroupChatEntry, updateGroupChat } from './group-chat'
import type { GroupChatRoom } from './group-chat'
-import { groupMemberKey, groupSessionKey } from './group-membership'
+import { groupMemberKey, groupSessionKey, groupSessionMemberKey, groupSessionThread } from './group-membership'
import { GROUP_PROMPT_HEADER_PREFIX } from './group-round-prompt'
+import { requestForBot } from './routing'
import type { GroupMember } from './types'
/** A transcript row as `session.resume` reports it; `content` is a plain string
* on most providers and a part array on the rest. */
export interface GroupTranscriptRow {
content?: string | Array<string | { text?: string }>
+ /** The gateway's display type for scaffolding rows it persists typed
+ * (`persist_user_display_kind`); absent on real user words. */
+ display_kind?: string
role?: string
text?: string
}
-function transcriptRowText(row: GroupTranscriptRow): string {
+export function groupTranscriptRowText(row: GroupTranscriptRow): string {
const text =
typeof row.content === 'string'
? row.content
@@ -39,33 +56,60 @@ function transcriptRowText(row: GroupTranscriptRow): string {
return String(text).trim()
}
-/** Opens the user-role rows the agent loop injects into its own transcript
- * (continuation nudges, truncation recovery — `agent/conversation_loop.py`,
- * `agent/context_compressor.py`). They continue whichever exchange is open. */
-const AGENT_INJECTED_ROW_PREFIX = '[System:'
+/** Openers of the user-role rows the agent loop, compressor, cron and
+ * delegation plumbing inject into a transcript. Mirrors
+ * `agent/context_compressor.py::_SYNTHETIC_USER_ROW_PREFIXES` — keep the two
+ * lists in step. `session.resume` already drops `[System:` and
+ * `display_kind: hidden` rows and projects compaction carriers, so most of
+ * these only matter for rows persisted before the gateway typed them. */
+export const SYNTHETIC_USER_ROW_PREFIXES = [
+ '[System:',
+ '[CONTEXT',
+ '[PRIOR CONTEXT',
+ '[IMPORTANT: Background',
+ '[Your active task list',
+ '[Planning state preserved',
+ '[ASYNC DELEGATION',
+ '[OUT-OF-BAND',
+ 'Cronjob Response:'
+]
+
+/** A user row that carries no user words: typed scaffolding (auto-continue
+ * notes, steer markers, model-switch notices — anything but a skill
+ * invocation, which is the user's own `/command`) or an untyped row opening
+ * with one of the canonical prefixes. */
+export function syntheticGroupUserRow(row: GroupTranscriptRow, text = groupTranscriptRowText(row)): boolean {
+ if (row.display_kind && row.display_kind !== 'skill_invocation') {
+ return true
+ }
+
+ return SYNTHETIC_USER_ROW_PREFIXES.some(prefix => text.startsWith(prefix))
+}
/** The rows in `rows` the room engine did not write itself. A user row that
* does not open with the room prompt header is external; an assistant row
- * answers whichever user row preceded it, so it inherits that row's origin;
- * agent-injected user rows, tool rows and empty rows are plumbing and never
- * mirrored. */
+ * answers whichever user row preceded it, so it inherits that row's origin.
+ * Synthetic user rows are plumbing: neither they nor the assistant row
+ * reacting to them (a compaction handoff, a cron report, a finished
+ * delegation) is a member speaking to anyone, so they close the exchange
+ * instead of continuing it. Tool rows and empty rows are never mirrored. */
export function externalGroupTranscriptRows(rows: GroupTranscriptRow[]): string[] {
const external: string[] = []
let answeringExternal = false
for (const row of rows) {
- const text = transcriptRowText(row)
+ const text = groupTranscriptRowText(row)
if (!text || (row.role !== 'user' && row.role !== 'assistant')) {
continue
}
if (row.role === 'user') {
- if (text.startsWith(AGENT_INJECTED_ROW_PREFIX)) {
+ answeringExternal = !syntheticGroupUserRow(row, text) && !text.startsWith(GROUP_PROMPT_HEADER_PREFIX)
+
+ if (!answeringExternal) {
continue
}
-
- answeringExternal = !text.startsWith(GROUP_PROMPT_HEADER_PREFIX)
}
if (answeringExternal) {
@@ -79,24 +123,33 @@ export function externalGroupTranscriptRows(rows: GroupTranscriptRow[]): string[
/** Append the rows written to `member`'s `thread` session since the last sweep
* to the room log, then move that session's cursor to the end of `messages`.
* Idempotent per row: the cursor persists with the room, so a restarted
- * window never mirrors a row twice. */
+ * window never mirrors a row twice. `undefined` messages (no snapshot) leave
+ * the cursor alone — seeding from a failed resume would replay history on
+ * the next successful one. */
export function mirrorExternalGroupWrites(
group: string,
member: GroupMember,
thread: string,
messages: GroupTranscriptRow[] | undefined
) {
- const rows = Array.isArray(messages) ? messages : []
+ if (!Array.isArray(messages)) {
+ return
+ }
+
+ const rows = messages
const key = groupSessionKey(thread, member)
const room = ($groupChats.get()[group] || {}) as GroupChatRoom
- const seen = Math.max(0, Number(room.externalCursors?.[key] || 0))
+ const cursor = room.externalCursors?.[key]
+ // First sight or compaction shrink: park the cursor at the end (see header).
+ const seen = typeof cursor === 'number' && cursor >= 0 && cursor <= rows.length ? cursor : rows.length
- if (rows.length <= seen) {
+ if (seen === rows.length && cursor === seen) {
return
}
const markKey = `${thread}::${groupMemberKey(member)}`
const logLengthBefore = (room.log || []).length
+
const mirrored = externalGroupTranscriptRows(rows.slice(seen)).map(text =>
appendGroupChatEntry(
group,
@@ -132,3 +185,45 @@ export function mirrorExternalGroupWrites(
return r
})
}
+
+/** Idle trigger: read every member session the room still shows a thread for
+ * and mirror what reached it, without the room driving anyone. Runs when the
+ * room is opened, so a Bot posting reports into its own room session between
+ * rounds surfaces the next time the user looks — not only once the user
+ * types and that member happens to be a responder. One `session.resume` per
+ * stored session, bounded by the room's own (trimmed) log; no polling. A
+ * room mid-round is left to the round, which sweeps its responders itself. */
+export async function sweepExternalGroupWrites(group: string, members: GroupMember[]) {
+ const room = ($groupChats.get()[group] || {}) as GroupChatRoom
+
+ if (room.running || room.tombstone) {
+ return
+ }
+
+ const shown = new Set<string>(['legacy', ...(room.log || []).map(entry => entry.thread || 'legacy')])
+ const sessions = room.sessions || {}
+
+ for (const member of members) {
+ const memberKey = groupMemberKey(member)
+
+ for (const [key, stored] of Object.entries(sessions)) {
+ const thread = groupSessionThread(key)
+
+ if (typeof stored !== 'string' || groupSessionMemberKey(key) !== memberKey || !shown.has(thread)) {
+ continue
+ }
+
+ let state: { messages?: GroupTranscriptRow[]; running?: boolean } | null = null
+
+ try {
+ state = await requestForBot(member, 'session.resume', { session_id: stored, profile: member.name })
+ } catch {
+ continue // unreachable or gone: nothing to mirror from here
+ }
+
+ if (!state?.running && ($groupChats.get()[group] || {}).sessions?.[key] === stored) {
+ mirrorExternalGroupWrites(group, member, thread, state?.messages)
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src/plugins/hermes-bots/group-membership.ts b/apps/desktop/src/plugins/hermes-bots/group-membership.ts
index 1697c10aaf5..cc7667119f2 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-membership.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-membership.ts
@@ -104,6 +104,19 @@ export function groupSessionMemberKey(key: string): string {
return boundary === -1 ? rest : rest.slice(boundary + 2)
}
+/** The thread half of a session key; bare (pre-thread) keys belong to the
+ * `legacy` thread, the same name their turns run under. */
+export function groupSessionThread(key: string): string {
+ if (!key.startsWith(GROUP_SESSION_THREAD_PREFIX)) {
+ return 'legacy'
+ }
+
+ const rest = key.slice(GROUP_SESSION_THREAD_PREFIX.length)
+ const boundary = rest.indexOf('::')
+
+ return (boundary === -1 ? rest : rest.slice(0, boundary)) || 'legacy'
+}
+
/** Whether this member already owns a thread-scoped session anywhere in the
* room — i.e. the room has been through the pre-thread migration. */
export function hasThreadScopedGroupSession(sessions: Record<string, unknown>, memberKey: string): boolean {
diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
index 5ad3108a12f..c377c19f249 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
@@ -12,7 +12,7 @@ import { noteBotAttention } from './data'
import { groupFailureReason, recordGroupActivity } from './group-activity'
import { $groupChats, $groupClarify, appendGroupChatEntry, updateGroupChat } from './group-chat'
import type { GroupChatRoom } from './group-chat'
-import { mirrorExternalGroupWrites } from './group-external-writes'
+import { groupTranscriptRowText, mirrorExternalGroupWrites, syntheticGroupUserRow } from './group-external-writes'
import {
followGroupChat,
groupMemberAuthor,
@@ -21,6 +21,7 @@ import {
groupSessionOwner,
hasThreadScopedGroupSession
} from './group-membership'
+import { GROUP_PROMPT_HEADER_PREFIX } from './group-round-prompt'
import { botConnectionRoute, requestForBot } from './routing'
import type { Attachment, GroupMember, GroupPrompt, GroupPromptQuestion, ProfileRoute } from './types'
@@ -85,6 +86,47 @@ function pickGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: numb
return passText
}
+/** The reply of a STRANDED turn: the first substantive assistant row after the
+ * turn's own prompt (the header-prefixed user row at or after `before`),
+ * stopping where an outside writer takes the session over. Newest-first
+ * (`pickGroupTurnReply`) would post a CLI answer written after the late reply
+ * as the turn reply — and the external-write mirror posts it again. Only
+ * passes in range → the last pass; no anchor row → scan from `before`. */
+function pickStrandedGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: number): null | string {
+ const anchor = messages.findIndex(
+ (msg, i) => i >= before && msg?.role === 'user' && groupTranscriptRowText(msg).startsWith(GROUP_PROMPT_HEADER_PREFIX)
+ )
+
+ let passText: null | string = null
+
+ for (let i = anchor === -1 ? before : anchor; i < messages.length; i++) {
+ const msg = messages[i]
+ const text = groupTranscriptRowText(msg)
+
+ if (msg?.role === 'user') {
+ if (text.startsWith(GROUP_PROMPT_HEADER_PREFIX) || syntheticGroupUserRow(msg, text)) {
+ continue
+ }
+
+ break
+ }
+
+ if (msg?.role !== 'assistant' || !text) {
+ continue
+ }
+
+ if (isGroupPassText(text)) {
+ passText = text
+
+ continue
+ }
+
+ return text
+ }
+
+ return passText
+}
+
/** A clarify question blocking inside a member's session, as `session.resume`
* reports it. Older backends omit the field entirely. */
interface GroupPendingClarify {
@@ -1248,7 +1290,7 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
const messages = Array.isArray(state?.messages) ? state.messages : []
// A transcript that never grew is not proof of nothing: a turn that dies
// before its prompt is committed leaves only the retained error behind.
- const reply = messages.length > strandedBefore ? pickGroupTurnReply(messages, strandedBefore) : null
+ const reply = messages.length > strandedBefore ? pickStrandedGroupTurnReply(messages, strandedBefore) : null
if (reply === null) {
// The late turn died instead of answering: say so where the user looks
diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.md
index e94de152d4d..c5657e979d7 100644
--- a/website/docs/user-guide/bot-mode.md
+++ b/website/docs/user-guide/bot-mode.md
@@ -154,7 +154,7 @@ Use the **Move up** and **Move down** arrows beside a room to choose its positio
- **Rooms can span machines.** **New Group Chat** is available as soon as two Bots are selectable across all your registered connections — one Bot on this device plus one on another gateway is enough. The picker seats Bots from any registered connection; each member's turns run on its own machine, in its own room session there. Cross-machine members carry a device badge (`dixie · Mac Mini`) in the room and in other members' transcripts, and the disambiguated `@name-device` handle works in room mentions — so same-named agents on two machines never blur together. A member's turn that outlives this Desktop — you quit or it crashed mid-turn — finishes on the member's own machine: the room posts that reply the next time it is driven, and does not re-drive the member while it is still working.
- **Rooms show the same identity as the roster.** Transcript rows, the “X is thinking…” line and Activity rows resolve each member's title and avatar by its owning connection and profile — re-titling a Bot or changing its picture updates every room it sits in, remote members keep their own titles, and two same-named Bots on different connections never borrow each other's avatar. When two members would still read identically, Activity appends the connection label (`Reviewer · Mac Mini`).
- **Plugins can watch members work.** The durable room log records `turn.started` and `turn.settled`; what a member does in between (tools, approvals, streamed text) is projected to plugins through the [`on_room_member_activity`](./features/hooks.md#on_room_member_activity) hook with room, member and turn coordinates, so community clients can build tool cards and live member status on top of Group Chat without reading Hermes internals.
-- **What a member says outside the room still reaches it.** Each member's room session is an ordinary Hermes session (titled `Group: <room> · <thread>`), so you can resume it from the CLI, a routine can post into it, or the Bot's own tools can write to it. The next time the room drives that member, whatever those writers added since the room last looked — your questions and the member's answers — is posted into the room log under that member's name, once, in the thread the session belongs to; a window restart does not repeat it. The room's own turn prompts and their replies are never duplicated this way.
+- **What a member says outside the room still reaches it.** Each member's room session is an ordinary Hermes session (titled `Group: <room> · <thread>`), so you can resume it from the CLI, a routine can post into it, or the Bot's own tools can write to it. When you open the room, and again each time the room drives that member, whatever those writers added since the room last looked — your questions and the member's answers — is posted into the room log under that member's name, once, in the thread the session belongs to; a window restart does not repeat it. The room's own turn prompts and their replies are never duplicated this way, and neither are the agent's housekeeping rows (context compaction notes, routine deliveries, delegation results) or the member's reactions to them. The room starts watching a session the first time it sees it: what was already in that session by then is not replayed, so a room restored on a second Desktop does not re-post its members' history.
## Bot-to-bot messaging