Skip to content

The agent that grows with you

fix(desktop): a room turn a Desktop abandons mid-flight is harvested, not lost — the marker goes down at submit

John Paul Soliva7eee6ae65999
diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts
index 07c0278f546..a3416ef768b 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts
@@ -1051,6 +1051,111 @@ describe('clarify and approvals (#90694)', () => {
})
})
+// The marker goes down at SUBMIT, not only at the deadline: a turn this Desktop
+// abandons (quit or crash mid-turn) keeps running on the member's gateway — a
+// remote member's most of all — and only a persisted marker lets the next
+// boundary harvest that reply instead of dropping it and re-driving a live
+// session. While the poll that wrote it is still running here, the marker is
+// "live": not harvested, and no reason to skip the member (#93127 re-drive).
+describe('in-flight marker', () => {
+ it('marks a turn in flight at submit and clears the marker with its reply', async () => {
+ const room = await loadRoom({ pollsBusy: 1, turn: () => 'the answer' })
+ const request = host.request as (method: string, params?: Record<string, unknown>) => Promise<unknown>
+ const seen: { marker?: unknown; live?: boolean } = {}
+
+ host.request = async (method: string, params: Record<string, unknown> = {}) => {
+ const result = await request(method, params)
+
+ if (method === 'session.resume' && room.gateway.rpcFor('prompt.submit').length && seen.marker === undefined) {
+ seen.marker = room.chat.$groupChats.get().Room?.stranded?.helper
+ seen.live = room.turns.strandedMarkerIsLive(seen.marker)
+ }
+
+ return result
+ }
+
+ const reply = await room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi', 't1', [])
+
+ expect(reply).toBe('the answer')
+ expect(seen.marker).toMatchObject({ before: 0, thread: 't1' })
+ expect(typeof (seen.marker as { turn?: unknown }).turn).toBe('string')
+ expect(seen.live).toBe(true)
+ expect(room.chat.$groupChats.get().Room?.stranded?.helper).toBeUndefined()
+ })
+
+ it('a poll still running here owns its marker: the harvest leaves the turn to it', async () => {
+ const room = await loadRoom({ pollsBusy: 1, turn: () => 'late answer' })
+ const request = host.request as (method: string, params?: Record<string, unknown>) => Promise<unknown>
+ // Park the poll on its first post-submit resume so the in-flight window is observable.
+ let release!: () => void
+
+ const gate = new Promise<void>(resolve => {
+ release = resolve
+ })
+
+ let parked = false
+
+ host.request = async (method: string, params: Record<string, unknown> = {}) => {
+ if (method === 'session.resume' && room.gateway.rpcFor('prompt.submit').length && !parked) {
+ parked = true
+ await gate
+ }
+
+ return request(method, params)
+ }
+
+ const turn = room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi', 't1', [])
+
+ await drain(() => !parked)
+ const marker = room.chat.$groupChats.get().Room?.stranded?.helper
+ const resumes = room.gateway.rpcFor('session.resume').length
+
+ expect(room.turns.strandedMarkerIsLive(marker)).toBe(true)
+ await room.turns.harvestStrandedGroupReply('Room', LOCAL_MEMBER)
+ expect(log(room, 'Room')).toHaveLength(0)
+ expect(room.chat.$groupChats.get().Room?.stranded?.helper).toBe(marker)
+ expect(room.gateway.rpcFor('session.resume')).toHaveLength(resumes) // the harvest never touched the session
+
+ release()
+ expect(await turn).toBe('late answer')
+ expect(room.chat.$groupChats.get().Room?.stranded?.helper).toBeUndefined()
+ expect(room.turns.strandedMarkerIsLive(marker)).toBe(false)
+ })
+
+ it('harvests a remote member\'s turn that a previous Desktop process left in flight', async () => {
+ const room = await loadRoom()
+ const { groupSessionKey } = await import('./group-membership')
+
+ // What the durable room looks like after a restart: the marker persisted with a
+ // token no poll in THIS process owns, and the member's session on ITS machine
+ // finished the turn in the meantime.
+ room.chat.updateGroupChat('Fleet', current => {
+ current.sessions = { [groupSessionKey('t1', ROUTED_MEMBER)]: 'sid-mini-helper' }
+ current.stranded = { 'mini::helper': { before: 1, thread: 't1', turn: 'rt-gone:abandoned' } }
+
+ return current
+ })
+ room.gateway.sessions.set('sid-mini-helper', {
+ messages: [
+ { content: 'the turn prompt', role: 'user' },
+ { content: 'Finished on the mini after the Desktop went away.', role: 'assistant' }
+ ],
+ profile: 'helper',
+ runtime: 'rt-mini-helper',
+ stored: 'sid-mini-helper',
+ title: 'Group: Fleet · t1'
+ })
+
+ expect(room.turns.strandedMarkerIsLive(room.chat.$groupChats.get().Fleet.stranded?.['mini::helper'])).toBe(false)
+ await room.turns.harvestStrandedGroupReply('Fleet', ROUTED_MEMBER)
+
+ expect(log(room, 'Fleet')).toHaveLength(1)
+ expect(log(room, 'Fleet')[0].from).toMatchObject({ name: 'helper', source: 'mini' })
+ expect(log(room, 'Fleet')[0].text).toMatch(/Finished on the mini/)
+ expect(room.chat.$groupChats.get().Fleet.stranded?.['mini::helper']).toBeUndefined()
+ })
+})
+
// A turn that outlives its deadline leaves a "stranded" marker. The member is
// still working; the next round harvests whatever landed instead of throwing
// the finished work away.
@@ -1117,6 +1222,39 @@ describe('stranded harvest', () => {
expect(room.chat.$groupChats.get().Rescue.stranded?.research).toBeUndefined()
})
+ it('drops a marker whose session is genuinely gone, but keeps one whose source is unreachable', async () => {
+ const room = await loadRoom()
+ const request = host.request as (method: string, params?: Record<string, unknown>) => Promise<unknown>
+
+ room.chat.updateGroupChat('Gone', current => {
+ current.sessions = { research: 'sid-deleted', ops: 'sid-ops' }
+ current.stranded = { ops: 1, research: 1 }
+
+ return current
+ })
+
+ host.request = async (method: string, params: Record<string, unknown> = {}) => {
+ if (method === 'session.resume' && params.session_id === 'sid-deleted') {
+ throw Object.assign(new Error('session not found'), { code: 4007 })
+ }
+
+ if (method === 'session.resume' && params.session_id === 'sid-ops') {
+ throw new Error('socket closed')
+ }
+
+ return request(method, params)
+ }
+
+ await room.turns.harvestStrandedGroupReply('Gone', { name: 'research', title: '' })
+ await room.turns.harvestStrandedGroupReply('Gone', { name: 'ops', title: '' })
+
+ expect(log(room, 'Gone')).toHaveLength(0)
+ // 4007: nothing will ever land — a marker that cannot resolve would silence the member for good.
+ expect(room.chat.$groupChats.get().Gone.stranded?.research).toBeUndefined()
+ // Unreachable: the turn may still be running there — leave it for the next boundary.
+ expect(room.chat.$groupChats.get().Gone.stranded?.ops).toBe(1)
+ })
+
it('consumes the marker without posting when the late reply is a pass', async () => {
const room = await loadRoom()
diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
index c349f5201e1..28eec4c6e0d 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
@@ -852,6 +852,56 @@ interface GroupTurnPollContext {
* still matches it is an older turn's tombstone, not this turn's death. */
leftover: null | string
binding: { isLive(): boolean }
+ /** The in-flight marker this poll owns (see markGroupTurnInFlight). */
+ turn: string
+}
+
+// Polls alive in THIS process, by marker token. A marker whose token is here belongs to a turn
+// still being awaited, so a harvest that runs meanwhile (the settle loop's tick racing a new
+// drive) must leave it alone: posting the reply the poll is about to return would double-deliver
+// it. Drives are sequential per room, so no round's responders filter ever meets a live marker.
+const liveGroupTurns = new Set<string>()
+
+export function strandedMarkerIsLive(marker: unknown): boolean {
+ const turn = marker && typeof marker === 'object' ? (marker as { turn?: unknown }).turn : undefined
+
+ return typeof turn === 'string' && liveGroupTurns.has(turn)
+}
+
+/** The marker goes down at SUBMIT, not only at the deadline: a turn this process abandons —
+ * Desktop quit or crash mid-turn, a submit whose ack never came back — keeps running on the
+ * member's gateway (a remote member's most of all: its gateway outlives this Desktop), and only
+ * a persisted marker lets the next boundary harvest the finished reply instead of dropping it
+ * and re-driving a live session. */
+function markGroupTurnInFlight(group: string, member: GroupMember, marker: { before: number; thread: string; turn: string }) {
+ updateGroupChat(group, (r: GroupChatRoom) => {
+ r.stranded = {
+ ...(r.stranded || {}),
+ [groupMemberKey(member)]: marker
+ }
+
+ return r
+ })
+}
+
+/** Drop the marker only while it is still this poll's: a newer drive may have re-driven the
+ * member and stamped its own. */
+function clearGroupTurnMarker(group: string, member: GroupMember, turn: string) {
+ updateGroupChat(group, (r: GroupChatRoom) => {
+ const key = groupMemberKey(member)
+ const current = r.stranded?.[key]
+
+ if (current && typeof current === 'object' && current.turn === turn) {
+ const next = {
+ ...(r.stranded || {})
+ }
+
+ delete next[key]
+ r.stranded = next
+ }
+
+ return r
+ })
}
async function pollGroupMemberTurn(context: GroupTurnPollContext): Promise<null | string> {
@@ -884,6 +934,8 @@ async function pollGroupMemberTurn(context: GroupTurnPollContext): Promise<null
const roomDuringPoll = $groupChats.get()[context.group] || {}
if ((roomDuringPoll.epoch || 0) !== dispatchEpoch && (roomDuringPoll.holds || {})[memberKey]) {
+ clearGroupTurnMarker(context.group, member, context.turn)
+
return null
}
@@ -962,26 +1014,15 @@ async function pollGroupMemberTurn(context: GroupTurnPollContext): Promise<null
}
// Timeout — clear any still-mirrored question card (the server-side
- // clarify timeout runs its own course) and read as a pass, but remember the baseline + thread
- // (runtime-only) so the finished reply can be posted late into the RIGHT
- // thread instead of vanishing.
+ // clarify timeout runs its own course) and read as a pass. The marker written
+ // at submit stays, so the finished reply is posted late into the RIGHT thread
+ // instead of vanishing; it stops being "live" when this poll returns.
recordGroupActivity(context.group, {
kind: 'timed-out',
member: groupMemberKey(member),
thread
})
syncGroupClarify(context.group, member, thread, null)
- updateGroupChat(context.group, (r: GroupChatRoom) => {
- r.stranded = {
- ...(r.stranded || {}),
- [groupMemberKey(member)]: {
- before,
- thread
- }
- }
-
- return r
- })
return null
}
@@ -1067,20 +1108,45 @@ async function runGroupChatMemberTurnLeased(
runtimeIds.add(liveRuntime)
- return await pollGroupMemberTurn({
- get group() {
- return group
- },
- member,
- thread,
- dispatchEpoch,
- stored,
- liveRuntime,
- runtimeIds,
+ const turn = `${liveRuntime}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 8)}`
+ liveGroupTurns.add(turn)
+ markGroupTurnInFlight(group, member, {
before,
- leftover,
- binding
+ thread,
+ turn
})
+
+ try {
+ const reply = await pollGroupMemberTurn({
+ get group() {
+ return group
+ },
+ member,
+ thread,
+ dispatchEpoch,
+ stored,
+ liveRuntime,
+ runtimeIds,
+ before,
+ leftover,
+ binding,
+ turn
+ })
+
+ // A reply (or an explicit pass) ends the turn; null is a timeout or a dead
+ // binding, and the marker must outlive this poll for the harvest.
+ if (reply !== null) {
+ clearGroupTurnMarker(group, member, turn)
+ }
+
+ return reply
+ } catch (error) {
+ // The turn died on our prompt: nothing to harvest.
+ clearGroupTurnMarker(group, member, turn)
+ throw error
+ } finally {
+ liveGroupTurns.delete(turn)
+ }
} finally {
binding.dispose()
}
@@ -1102,8 +1168,8 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
const strandedBefore = typeof marker === 'number' ? marker : marker?.before
const strandedThread = (typeof marker === 'object' && marker?.thread) || 'legacy'
- if (typeof strandedBefore !== 'number') {
- return
+ if (typeof strandedBefore !== 'number' || strandedMarkerIsLive(marker)) {
+ return // nothing stranded, or a poll in this process still owns the turn
}
let state: GroupSessionSnapshot | null = null
@@ -1119,8 +1185,23 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
session_id: stored || `Group: ${room.roomId || group} · ${strandedThread}`,
profile: member.name
})) as GroupSessionSnapshot
- } catch {
- return // source unreachable — leave the marker for the next boundary
+ } catch (error: any) {
+ // A session that genuinely no longer exists has nothing to harvest, and a marker that can
+ // never resolve would keep the member out of every round; only unreachability keeps it.
+ if (error?.code === 4007) {
+ updateGroupChat(group, (r: GroupChatRoom) => {
+ const next = {
+ ...(r.stranded || {})
+ }
+
+ delete next[memberKey]
+ r.stranded = next
+
+ return r
+ })
+ }
+
+ return
}
if (!binding.isLive()) {
diff --git a/apps/desktop/src/plugins/hermes-bots/types.ts b/apps/desktop/src/plugins/hermes-bots/types.ts
index 4a889f127b2..a14896dcfa5 100644
--- a/apps/desktop/src/plugins/hermes-bots/types.ts
+++ b/apps/desktop/src/plugins/hermes-bots/types.ts
@@ -200,7 +200,9 @@ export interface GroupChat {
* `{ name }`, and the sweep re-validates the route before trusting one. */
sessionOwners?: Record<string, Partial<RosterRow>>
sessions?: Record<string, string | true>
- stranded?: Record<string, number | { before: number; thread?: string }>
+ /** A member turn this Desktop is not (or no longer) polling: the message-count baseline to
+ * harvest its late reply from. `turn` names the poll that owns it while that poll runs. */
+ stranded?: Record<string, number | { before: number; thread?: string; turn?: string }>
syncRevision?: number
/** Left behind when a room is disbanded, so sync can't resurrect it. */
tombstone?: boolean
diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.md
index a1ec325b8bc..0982d6646e4 100644
--- a/website/docs/user-guide/bot-mode.md
+++ b/website/docs/user-guide/bot-mode.md
@@ -149,7 +149,7 @@ Use the **Move up** and **Move down** arrows beside a room to choose its positio
- **Rooms keep running when you close the Desktop.** When every member of a room lives on the same gateway, that gateway owns turn scheduling through a durable driver: closing Hermes Desktop (or losing its connection) does not stop a room mid-discussion, and the Desktop simply catches up from the room's log when it reconnects. `groups.capabilities` on the gateway reports `driver: true` when this applies. More than one room worker may share a home — the messaging gateway (`hermes gateway run`) and the Desktop's own backend (`hermes serve`) both run one — and whichever holds the room's driver lease runs the next turn; a member's room session is held only for the duration of its turn, so the lease can move between workers without a turn being refused. Room state lives in the install's root `shared-state.db`; installs that created rooms before that file existed (when rooms were still kept in the root `state.db`) get those rooms copied across once, on the first open after updating, so pre-existing Group Chats stay reachable. Rooms whose members span several machines are different: each member's turns run on its own gateway, and the cross-connection courier described under *Bot-to-bot messaging* still applies to them.
- **Mentions read as identities.** In the transcript a routed `@bot` mention, the human handoff `@user`, and the broadcasts `@everyone` / `@all` render as inline references (accent text, not pills); unknown `@words` and e-mail addresses stay plain. Hover a Bot's message and use **Reply to @handle** to seed `@handle ` into the composer, so your next send goes to that Bot only (when a same-named Bot from a Connection shares the room, the tag is device-qualified, e.g. `@reviewer-mini` / `@reviewer-local`) — **Reply in thread** still continues the whole thread. If a reply box for a *different* thread is open, **Reply to** seeds the main composer instead and so starts a fresh thread; use **Reply in thread** to continue that thread.
-- **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.
+- **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.