The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-mode): key group member sessions by thread
Austin Pickettd631ad5f5cd6
diff --git a/apps/desktop/src/plugins/hermes-bots/group-membership.ts b/apps/desktop/src/plugins/hermes-bots/group-membership.tsindex 7badbed01d9..cac53302b6e 100644--- a/apps/desktop/src/plugins/hermes-bots/group-membership.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-membership.ts@@ -57,6 +57,42 @@ export function groupMemberKey(member: GroupMember): string {return member?.sourceScoped || member?.remoteSource ? botRosterKey(member) : member?.name}+/** Marks a session key as thread-scoped. Pre-thread rooms stored ONE session+ * per member under the bare `groupMemberKey`, and a source-qualified member+ * key is itself `<connectionId>::<name>` — so the thread segment needs its+ * own literal prefix to stay distinguishable from both. */+const GROUP_SESSION_THREAD_PREFIX = 'thread:'++/** Identity of a member's hidden plumbing session INSIDE one thread. Threads+ * are separate conversations (own log slice, own watermarks — see+ * `${thread}::${memberKey}` in group-round-members), so they must not share+ * one backend transcript: thread B resuming thread A's session is how a+ * member answered B carrying A's context (#90420, #106460). */+export function groupSessionKey(thread: string, member: GroupMember): string {+ return `${GROUP_SESSION_THREAD_PREFIX}${thread || 'legacy'}::${groupMemberKey(member)}`+}++/** The member half of a session key. Bare keys are pre-thread rooms and are+ * their own member key; the sweep reads owners by member, not by thread. */+export function groupSessionMemberKey(key: string): string {+ if (!key.startsWith(GROUP_SESSION_THREAD_PREFIX)) {+ return key+ }++ const rest = key.slice(GROUP_SESSION_THREAD_PREFIX.length)+ const boundary = rest.indexOf('::')++ return boundary === -1 ? rest : rest.slice(boundary + 2)+}++/** 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 {+ return Object.keys(sessions || {}).some(+ key => key.startsWith(GROUP_SESSION_THREAD_PREFIX) && groupSessionMemberKey(key) === memberKey+ )+}+/** Serializable immutable owner captured beside every group plumbing session. */export function groupSessionOwner(member: RosterRow) {const route = botConnectionRoute(member)diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.tsindex 86acc313a8d..5e02d3e43c1 100644--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts@@ -11,7 +11,13 @@ import { host } from '@hermes/plugin-sdk'import { recordGroupActivity } from './group-activity'import { $groupChats, $groupClarify, appendGroupChatEntry, updateGroupChat } from './group-chat'import type { GroupChatRoom } from './group-chat'-import { followGroupChat, groupMemberKey, groupSessionOwner } from './group-membership'+import {+ followGroupChat,+ groupMemberKey,+ groupSessionKey,+ groupSessionOwner,+ hasThreadScopedGroupSession+} from './group-membership'import { botConnectionRoute, requestForBot } from './routing'import type { Attachment, GroupMember, GroupPrompt, GroupPromptQuestion, ProfileRoute } from './types'@@ -118,13 +124,25 @@ interface GroupMemberSessionHandle {stored?: null | string | true}-/** Ensure the member's per-group session exists and return a LIVE runtime- * session id for it. Gateway-native: session.create mints the session- * (lazy until its first message), session.resume by stored id — or by- * title, which also covers rehydrated rooms whose sid was lost — reopens+/** Ensure the member's session FOR THIS THREAD exists and return a LIVE+ * runtime session id for it. Gateway-native: session.create mints the+ * session (lazy until its first message), session.resume by stored id — or+ * by title, which also covers rehydrated rooms whose sid was lost — reopens* it after restarts. Cross-connection members route to their OWN source- * via requestForBot; the window's gateway never switches. */-export async function ensureGroupChatSession(group: string, member: GroupMember): Promise<GroupMemberSessionHandle> {+ * via requestForBot; the window's gateway never switches.+ *+ * The session is keyed and titled per THREAD (#90420, #106460). Threads are+ * separate conversations everywhere else in the room engine — own delta+ * slice, own `${thread}::${memberKey}` watermark — so a member-only session+ * pointer made thread B resume thread A's transcript and answer carrying+ * A's context. Rooms persisted before this keep ONE bare member pointer;+ * the first thread to ask adopts it (below) so that history continues in a+ * real thread instead of being orphaned by the upgrade. */+export async function ensureGroupChatSession(+ group: string,+ member: GroupMember,+ thread: string+): Promise<GroupMemberSessionHandle> {const binding = followGroupChat(group, name => {group = name})@@ -134,9 +152,15 @@ export async function ensureGroupChatSession(group: string, member: GroupMember)// New rooms title member sessions by their immutable roomId so a// same-name recreate never resumes the old room's sessions by title;// legacy rooms without a roomId fall back to the display name.- const title = `Group: ${room.roomId || group}`- const key = groupMemberKey(member)- const known = room.sessions && room.sessions[key]+ const roomTitle = `Group: ${room.roomId || group}`+ const title = `${roomTitle} · ${thread || 'legacy'}`+ const memberKey = groupMemberKey(member)+ const key = groupSessionKey(thread, member)+ const sessions = room.sessions || {}+ const known = sessions[key]+ // Pre-thread pointer, adoptable only until some thread has taken it —+ // after that the room is migrated and every other thread mints its own.+ const legacy = hasThreadScopedGroupSession(sessions, memberKey) ? null : sessions[memberKey] || null// Try resuming what we know (stored sid first, then title lookup).//@@ -148,9 +172,16 @@ export async function ensureGroupChatSession(group: string, member: GroupMember)// there and must not be read as "no session, mint a new one" — that// forks the member's real history, and the fork silently overwrites// room.sessions[key] so the old session becomes unreachable from the- // room. Only a genuine 4007 on BOTH targets means there truly is nothing- // to resume yet, so the loop falls through to session.create below.- for (const target of [known, title]) {+ // room. Only a genuine 4007 on EVERY target means there truly is+ // nothing to resume yet, so the loop falls through to session.create.+ //+ // Target order: this thread's own pointer, then — only while the room is+ // still unmigrated — the pre-thread pointer and the pre-thread title, so+ // an upgraded room's existing conversation continues in the first thread+ // that speaks instead of being stranded behind an unreferenced sid.+ const targets = [known, title, ...(legacy === null ? [] : [legacy, roomTitle])]++ for (const target of targets) {if (!target || target === true) {continue}@@ -174,7 +205,11 @@ export async function ensureGroupChatSession(group: string, member: GroupMember)// stores `true` back into room.sessions and hands `true` on as the// durable id, which later rides into `session_id` on the recovery// resume and on session.interrupt. Typed as-written.- const stored = res.session_key || known+ //+ // The fallback is the id we resumed BY, which on the adoption pass+ // is the pre-thread pointer — the two title targets are titles, not+ // ids, and were never eligible.+ const stored = res.session_key || (target === title || target === roomTitle ? known : target)if (stored) {updateGroupChat(group, (current: GroupChatRoom) => {@@ -443,8 +478,17 @@ export const GROUP_TURN_HARD_CAP_MS = 20 * 60000* payload always sync to "no prompt". Clarify wins when both are somehow* present (approvals resolve inside tool batches; clarify is the outer* blocker). */-export function syncGroupClarify(group: string, member: GroupMember, state: GroupSessionSnapshot | null): boolean {- const key = `${group}::${groupMemberKey(member)}`+export function syncGroupClarify(+ group: string,+ member: GroupMember,+ thread: string,+ state: GroupSessionSnapshot | null+): boolean {+ const memberKey = groupMemberKey(member)+ // Per-thread sessions mean one member can now be blocked in two threads at+ // once, so the mirror is keyed by thread as well — a room-and-member key+ // would let thread B's question silently replace thread A's card (#90694).+ const key = `${group}::${thread || 'legacy'}::${memberKey}`const openClarify = Array.isArray(state?.open_requests)? state.open_requests.find(entry => entry?.method === 'clarify' && typeof entry.id === 'string' && entry.id)@@ -489,7 +533,10 @@ export function syncGroupClarify(group: string, member: GroupMember, state: GrourequestId,group,member: member.name,- memberKey: groupMemberKey(member),+ memberKey,+ // The card carries its own thread so the answer/rename paths rebuild+ // exactly this key instead of guessing one.+ thread: thread || 'legacy',// approval.respond keys on the session, not just the request — carry the// runtime id the snapshot came from.sessionId: state?.session_id || null,@@ -586,7 +633,7 @@ export function renameGroupClarify(oldName: string, newName: string) {// Rebuild the key from the mirror's own memberKey rather than// string-replacing oldName in place — a group name that happens to// be a substring of the member key must not corrupt the rekey.- next[`${newName}::${value.memberKey}`] = { ...value, group: newName }+ next[`${newName}::${value.thread || 'legacy'}::${value.memberKey}`] = { ...value, group: newName }}}@@ -646,7 +693,7 @@ export async function answerGroupClarify(}const all = $groupClarify.get()- const key = `${group}::${entry.memberKey}`+ const key = `${group}::${entry.thread || 'legacy'}::${entry.memberKey}`if (all[key]?.requestId === entry.requestId) {const next = {@@ -828,7 +875,7 @@ async function pollGroupMemberTurn(context: GroupTurnPollContext): Promise<null// A clarify blocking inside the member's session is a question for the// HUMAN (#90694) — mirror it into the room store so a card renders, and// hold the turn open: the member isn't stalling, it's waiting on us.- const awaitingUser = syncGroupClarify(context.group, member, state)+ const awaitingUser = syncGroupClarify(context.group, member, thread, state)const done = !busy && !awaitingUserif (messages.length > before && done) {@@ -874,7 +921,7 @@ async function pollGroupMemberTurn(context: GroupTurnPollContext): Promise<nullmember: member.name,thread})- syncGroupClarify(context.group, member, null)+ syncGroupClarify(context.group, member, thread, null)updateGroupChat(context.group, (r: GroupChatRoom) => {r.stranded = {...(r.stranded || {}),@@ -931,7 +978,7 @@ async function runGroupChatMemberTurnLeased(})try {- const { runtime, stored } = await ensureGroupChatSession(group, member)+ const { runtime, stored } = await ensureGroupChatSession(group, member, thread)if (!runtime || !binding.isLive()) {return null@@ -1009,9 +1056,14 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemblet state: GroupSessionSnapshot | null = nulltry {- const stored = room.sessions?.[memberKey]+ // The marker's own thread owns the session the reply is stranded in —+ // the harvest must not resume a sibling thread's transcript and post+ // its answer here.+ const sessions = room.sessions || {}+ const scoped = sessions[groupSessionKey(strandedThread, member)]+ const stored = scoped || (hasThreadScopedGroupSession(sessions, memberKey) ? null : sessions[memberKey])state = (await requestForBot(member, 'session.resume', {- session_id: stored || `Group: ${room.roomId || group}`,+ session_id: stored || `Group: ${room.roomId || group} · ${strandedThread}`,profile: member.name})) as GroupSessionSnapshot} catch {@@ -1023,7 +1075,7 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb}// Pending prompts are authoritative even while the session is running.- const awaitingUser = syncGroupClarify(group, member, state)+ const awaitingUser = syncGroupClarify(group, member, strandedThread, state)if (state?.inflight || state?.running || awaitingUser) {return