The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): hold a per-turn socket lease so group-chat member turns survive the runtime-session reaper (#93602)
Tekniumc29c9d17901e
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.jsindex ebbdde4b24f..77a7c95760e 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@ -7020,6 +7020,94 @@ async function ensureGroupChatSession(group, member) {const GROUP_TURN_TIMEOUT_MS = 180000const GROUP_TURN_POLL_MS = 2000++// --- group-turn session-lease helpers (#93602) ------------------------------+// A member turn is a session-scoped RPC SEQUENCE (resume → attach → submit →+// poll) issued with the runtime id its first RPC minted. requestForBot routes+// each RPC through a per-request socket lease (retained:false secondaries in+// store/gateway), so between two RPCs the refcount can hit 0, the leased+// socket closes, the gateway detaches the runtime session on WS disconnect,+// and the orphan reaper frees it — the next RPC then fails 4001 "not in+// memory" and the bot goes silent in the room.++/** 4001-class "the runtime session was reaped" failure. Distinct from 4007+ * ("genuinely never existed"), which must keep flowing to session.create. */+function isSessionGoneError(error) {+ if (!error || error.code === 4007) {+ return false+ }++ if (error.code === 4001) {+ return true+ }++ // Duck-typed (not instanceof): gateway errors can cross realm boundaries.+ const message = typeof error?.message === 'string' ? error.message : typeof error === 'string' ? error : ''++ return message.includes('not in memory') || /session not found/i.test(message)+}+// --- end group-turn session-lease helpers ---++/** Hold the member's pooled socket open for the WHOLE turn. Feature-detected:+ * hosts without retainProfile (or members on the active gateway, which never+ * closes mid-turn) get a no-op release. A failed acquire must not kill the+ * turn — the catch-retry on submit still covers the race. */+async function retainGroupTurnRoute(member) {+ const noop = () => undefined++ let route = null++ try {+ route = botConnectionRoute(member)+ } catch {+ return noop+ }++ if (!route || typeof host.retainProfile !== 'function') {+ return noop+ }++ try {+ const release = await host.retainProfile(route)++ return typeof release === 'function' ? release : noop+ } catch {+ return noop+ }+}++/** prompt.submit with one belt-and-braces retry: when the runtime session was+ * reaped between minting and submitting (4001 class), re-resume via the+ * STORED id — the durable identity — to mint a fresh runtime id, and submit+ * exactly once more. Returns the runtime id the submit actually landed on so+ * the poll loop keeps a live fallback target. */+async function submitGroupTurnPrompt(member, runtime, stored, text) {+ try {+ await requestForBot(member, 'prompt.submit', { session_id: runtime, text })++ return runtime+ } catch (error) {+ if (!isSessionGoneError(error) || !stored) {+ throw error+ }++ const res = await requestForBot(member, 'session.resume', {+ session_id: stored,+ profile: member.name,+ omit_messages: true+ })+ const fresh = res?.session_id++ if (!fresh) {+ throw error+ }++ await requestForBot(member, 'prompt.submit', { session_id: fresh, text })++ return fresh+ }+}+// A member turn that is VISIBLY still working (session reports// inflight/running) keeps its slot alive up to this hard cap. The base// timeout alone silently dropped long real turns: a 7-minute research run@@ -7174,6 +7262,20 @@ async function answerGroupClarify(entry, member, answers) {* records a stranded marker so the finished reply can be harvested into* the room at the member's next turn instead of being lost. */async function runGroupChatMemberTurn(group, member, prompt, thread, images) {+ // #93602: hold the member's route socket for the whole turn. Without the+ // lease, every RPC below rides its own request-scoped socket lease; the+ // socket that minted `runtime` can close between RPCs, the gateway reaps+ // the runtime session, and prompt.submit dies 4001 — the bot goes silent.+ const releaseTurnLease = await retainGroupTurnRoute(member)++ try {+ return await runGroupChatMemberTurnLeased(group, member, prompt, thread, images)+ } finally {+ releaseTurnLease()+ }+}++async function runGroupChatMemberTurnLeased(group, member, prompt, thread, images) {const { runtime, stored } = await ensureGroupChatSession(group, member)if (!runtime) {@@ -7244,7 +7346,10 @@ async function runGroupChatMemberTurn(group, member, prompt, thread, images) {? `${prompt}\n\nAttached files staged in your session workspace:\n${fileRefs.join('\n')}`: prompt- await requestForBot(member, 'prompt.submit', { session_id: runtime, text: turnText })+ // #93602: one-shot recovery when the runtime session was reaped between+ // minting and submitting. Tracks the runtime id the submit landed on so+ // the poll fallback below targets a live session.+ const liveRuntime = await submitGroupTurnPrompt(member, runtime, stored, turnText)const started = Date.now()let deadline = started + GROUP_TURN_TIMEOUT_MS@@ -7256,7 +7361,7 @@ async function runGroupChatMemberTurn(group, member, prompt, thread, images) {try {state = await requestForBot(member, 'session.resume', {- session_id: stored || runtime,+ session_id: stored || liveRuntime,profile: member.name})} catch {diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-turn-lease.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-lease.test.mjsnew file mode 100644index 00000000000..08bbc626708--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/tests/group-turn-lease.test.mjs@@ -0,0 +1,272 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import vm from 'node:vm'++// #93602: sub-profile bot silent in a group room. A member turn is a+// session-scoped RPC sequence (resume → attach → prompt.submit → poll) issued+// with the runtime id its FIRST rpc minted, but every requestForBot call rides+// its own request-scoped socket lease — at refcount 0 the leased secondary is+// disposed, the gateway detaches the runtime session on WS disconnect, the+// orphan reaper frees it, and the next RPC dies 4001 "not in memory" with no+// reply in the room. The fix holds a retained per-turn lease+// (host.retainProfile) across the whole sequence and adds a one-shot+// catch-and-retry on prompt.submit that re-resumes via the STORED id.++const pluginSource = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')++/** Harness mirroring group-chat-attachments.test.mjs, extended with a+ * refcounted host.requestProfile/host.retainProfile pair so socket lease+ * lifetimes are assertable. */+function load({ failFirstSubmitWith = null, failEverySubmitWith = null, reply = 'hello from turn' } = {}) {+ const values = new Map()+ const atom = initial => {+ const slot = { get: () => values.get(slot), set: value => values.set(slot, value) }+ values.set(slot, initial)+ return slot+ }++ const sessions = new Map()+ const runtimeToStored = new Map()+ const titleToStored = new Map()+ let sessionSequence = 0+ let submits = 0+ const rpcLog = []++ // Mock socket-pool refcount for the member's route: every RPC takes a+ // per-request lease (acquire → handle → release), exactly like+ // requestGatewayForAgent in store/gateway.ts. `disposals` counts every time+ // the refcount hits 0 — each one is a socket close that reaps the runtime+ // session in production.+ let refcount = 0+ let disposals = 0+ const timeline = []++ const acquire = () => {+ refcount += 1+ }+ const release = () => {+ refcount -= 1+ if (refcount === 0) {+ disposals += 1+ }+ }++ const resolveSession = (profile, target) =>+ (stored => (stored ? sessions.get(stored) : null))(+ runtimeToStored.get(target) || (sessions.has(target) ? target : titleToStored.get(`${profile}::${target}`))+ )++ const handle = async (method, params) => {+ if (method === 'session.create') {+ sessionSequence += 1+ const stored = `sid-${sessionSequence}`+ const runtime = `rt-${sessionSequence}`+ const session = { stored, runtime, profile: params.profile, title: params.title, messages: [] }+ sessions.set(stored, session)+ runtimeToStored.set(runtime, stored)+ titleToStored.set(`${params.profile}::${params.title}`, stored)+ return { session_id: runtime, stored_session_id: stored, message_count: 0, messages: [] }+ }+ if (method === 'session.resume') {+ const session = resolveSession(params.profile, params.session_id)+ if (!session) {+ const err = new Error(`session not found: ${params.session_id}`)+ err.code = 4007+ throw err+ }+ // Every resume mints a FRESH runtime id — the stored id is the durable+ // identity, mirroring the gateway's resume contract.+ sessionSequence += 1+ const runtime = `rt-${sessionSequence}`+ session.runtime = runtime+ runtimeToStored.set(runtime, session.stored)+ return {+ session_id: runtime,+ session_key: session.stored,+ message_count: session.messages.length,+ messages: params.omit_messages ? [] : [...session.messages],+ inflight: false,+ running: false+ }+ }+ if (method === 'image.attach_bytes' || method === 'pdf.attach' || method === 'file.attach') {+ const session = resolveSession(null, params.session_id)+ if (!session) {+ const err = new Error(`session-scoped RPC rejected: ${params.session_id} not in memory`)+ err.code = 4001+ throw err+ }+ return { attached: true }+ }+ if (method === 'prompt.submit') {+ submits += 1+ if (failEverySubmitWith) {+ throw failEverySubmitWith+ }+ if (submits === 1 && failFirstSubmitWith) {+ throw failFirstSubmitWith+ }+ const session = resolveSession(null, params.session_id)+ if (!session) {+ const err = new Error(`session-scoped RPC rejected: ${params.session_id} not in memory`)+ err.code = 4001+ throw err+ }+ session.messages.push({ role: 'user', content: params.text })+ session.messages.push({ role: 'assistant', content: reply })+ return {}+ }+ return {}+ }++ const context = {+ atom,+ setTimeout: fn => {+ fn()+ return 0+ },+ clearTimeout: () => undefined,+ Date,+ console,+ PALETTE_AREA: 'palette',+ COMPOSER_AREAS: { middleware: 'middleware' },+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },+ host: {+ request: async (method, params) => handle(method, params),+ requestProfile: async (route, method, params) => {+ acquire()+ try {+ return await handle(method, params)+ } finally {+ release()+ rpcLog.push({ method, refcountAfter: refcount })+ timeline.push(method)+ }+ },+ retainProfile: async route => {+ timeline.push('retain')+ acquire()+ let released = false+ return () => {+ if (!released) {+ released = true+ timeline.push('release')+ release()+ }+ }+ },+ state: { profile: { get: () => 'default', listen: () => undefined }, gateway: { listen: () => undefined } },+ notify: () => undefined,+ notifyError: () => undefined+ }+ }++ const source = 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.__lease = { runGroupChatMemberTurn, submitGroupTurnPrompt, isSessionGoneError, $groupChats };\n'+ )+ vm.runInNewContext(source, context, { filename: 'plugin.js' })+ context.plugin.register({+ storage: { get: () => null, set: () => undefined },+ register: () => undefined+ })+ return {+ ...context.__lease,+ context,+ rpcLog,+ timeline,+ stats: () => ({ refcount, disposals, submits })+ }+}++const LOCAL_MEMBER = { name: 'helper', title: '' }+const ROUTED_MEMBER = { name: 'helper', connectionId: 'mini', remoteSource: true }+const IMG = { name: 'shot.png', data: 'data:image/png;base64,iVBORw0KGgo=' }++test('isSessionGoneError: 4001 and "not in memory" are recoverable, 4007 is not', () => {+ const gc = load()+ const gone = new Error('x')+ gone.code = 4001+ assert.equal(gc.isSessionGoneError(gone), true)+ assert.equal(gc.isSessionGoneError(new Error('session_id=rt-1 not in memory')), true)+ const missing = new Error('session not found')+ missing.code = 4007+ assert.equal(gc.isSessionGoneError(missing), false)+ assert.equal(gc.isSessionGoneError(null), false)+ assert.equal(gc.isSessionGoneError(new Error('network blip')), false)+})++test('a 4001 on the first prompt.submit recovers via session.resume on the STORED id and delivers', async () => {+ const reaped = new Error("session-scoped RPC rejected: session_id='rt-1' not in memory")+ reaped.code = 4001+ const gc = load({ failFirstSubmitWith: reaped, reply: 'recovered reply' })++ const reply = await gc.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi there', 't1', [])++ assert.equal(reply, 'recovered reply')+ // One failed submit + exactly one retry — never more.+ assert.equal(gc.stats().submits, 2)+ // The recovery re-resumed the durable stored id, not the dead runtime id.+ const room = gc.$groupChats.get().Room+ assert.ok(room.sessions.helper, 'stored session id survives in the room record')+})++test('a persistent non-4001 submit failure is NOT retried and still surfaces', async () => {+ const fatal = new Error('backend exploded')+ const gc = load({ failEverySubmitWith: fatal })++ await assert.rejects(() => gc.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'hi', 't1', []), /backend exploded/)+ assert.equal(gc.stats().submits, 1)+})++test('the per-turn lease is acquired before any session RPC and held across attach+submit', async () => {+ const gc = load({ reply: 'routed reply' })++ const reply = await gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'look at this', 't1', [IMG])++ assert.equal(reply, 'routed reply')+ // The retain landed before the first session-scoped RPC on the route.+ assert.equal(gc.timeline[0], 'retain')+ // The socket was NEVER disposed mid-turn: after every per-request lease+ // released, the turn lease still held the refcount above zero.+ for (const rpc of gc.rpcLog) {+ assert.ok(rpc.refcountAfter >= 1, `${rpc.method} left refcount ${rpc.refcountAfter} — socket disposed mid-turn`)+ }+ // Exactly one disposal, and only via the turn lease's own release at the end.+ assert.equal(gc.stats().disposals, 1)+ assert.equal(gc.timeline[gc.timeline.length - 1], 'release')+})++test('the per-turn lease is released after the turn — refcount returns to zero', async () => {+ const gc = load({ reply: 'done' })++ await gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', [])++ assert.equal(gc.stats().refcount, 0)+ assert.equal(gc.stats().disposals, 1)+})++test('the per-turn lease is released even when the turn fails', async () => {+ const fatal = new Error('backend exploded')+ const gc = load({ failEverySubmitWith: fatal })++ await assert.rejects(() => gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', []))++ assert.equal(gc.stats().refcount, 0)+})++test('hosts without retainProfile still run the turn (feature detection)', async () => {+ const gc = load({ reply: 'legacy ok' })+ delete gc.context.host.retainProfile++ const reply = await gc.runGroupChatMemberTurn('Room', ROUTED_MEMBER, 'hi', 't1', [])++ assert.equal(reply, 'legacy ok')+})diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 67beeadc755..59f01962d69 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -49,6 +49,7 @@ import {openGatewayForProfile,requestGatewayForAgent,requestGatewayForProfile,+ retainGatewayForAgent,retainGatewayForRelay,retireLocalProfileGateways} from '@/store/gateway'@@ -1148,6 +1149,24 @@ export const host = {return retainGatewayForRelay(route.connectionId, route.profile)},+ /** Hold a route's pooled socket open across a multi-RPC, session-scoped+ * sequence (#93602). Each requestProfile call is its own request lease, so+ * a non-retained secondary socket closes at refcount 0 between calls — and+ * the gateway reaps any runtime session that socket minted, failing the+ * next RPC with 4001. Acquire before the first session-scoped RPC, release+ * (idempotent) in a `finally`. Feature-detect: older hosts lack this. */+ retainProfile: async (route: PluginProfileRoute | string): Promise<() => void> => {+ if (typeof route !== 'string') {+ if (!route.connectionId.trim() || !route.profile.trim()) {+ throw new Error('Profile route must include connectionId and profile')+ }++ return retainGatewayForAgent(route.connectionId, route.profile)+ }++ return retainGatewayForAgent(null, route.trim() || 'default')+ },+/** Gateway JSON-RPC — sessions, config, skills, cron, kanban, everything* the app itself uses. Lazy: resolves the LIVE socket per call. */request: async <T>(method: string, params: Record<string, unknown> = {}): Promise<T> => {diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.tsindex 196c76e14dd..2aa098f5deb 100644--- a/apps/desktop/src/store/gateway-profile-request.test.ts+++ b/apps/desktop/src/store/gateway-profile-request.test.ts@@ -57,6 +57,7 @@ const {pruneSecondaryGateways,requestGatewayForAgent,requestGatewayForProfile,+ retainGatewayForAgent,setPrimaryGateway} = await import('./gateway')@@ -370,3 +371,94 @@ describe('requestGatewayForAgent', () => {expect($gateway.get()).toBe(primary)})})++describe('retainGatewayForAgent (#93602)', () => {+ function installRegistryDesktop() {+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {+ getConnection: vi.fn(async (profile: null | string) => ({ port: 4242, profile, token: 't' })),+ getConnectionFor: vi.fn(async ({ connectionId, profile }) => ({ connectionId, port: 5151, profile })),+ getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({+ ok: true as const,+ wsUrl: `ws://${connectionId}/${profile}`+ })),+ touchBackend: vi.fn(async () => undefined)+ }+ }++ it('holds the registry socket across multiple leased requests — no mid-turn disposal', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installRegistryDesktop()+ await ensureGatewayForProfile('default')++ const release = await retainGatewayForAgent('mini', 'helper')++ // The whole member-turn RPC sequence: each call takes and releases its own+ // per-request lease. Without the retain, refcount 0 between calls disposes+ // the socket and the runtime session with it.+ await requestGatewayForAgent('mini', 'helper', 'session.create', { title: 'g' })+ await requestGatewayForAgent('mini', 'helper', 'image.attach_bytes', { session_id: 'rt-1' })+ await requestGatewayForAgent('mini', 'helper', 'prompt.submit', { session_id: 'rt-1', text: 'hi' })++ expect(secondaryGateways).toHaveLength(1)+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()+ expect(secondaryGateways[0].request).toHaveBeenCalledTimes(3)++ release()+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()+ })++ it('release is idempotent — a double release never underflows into a foreign disposal', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installRegistryDesktop()+ await ensureGatewayForProfile('default')++ const release = await retainGatewayForAgent('mini', 'helper')+ release()+ release()++ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()++ // A fresh retain still works after the double release.+ const again = await retainGatewayForAgent('mini', 'helper')+ await requestGatewayForAgent('mini', 'helper', 'prompt.submit', { session_id: 'rt-2', text: 'hi' })+ expect(secondaryGateways[1].close).not.toHaveBeenCalled()+ again()+ expect(secondaryGateways[1].close).toHaveBeenCalledOnce()+ })++ it('without the retain, the leased socket closes after each request (the #93602 race)', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installRegistryDesktop()+ await ensureGatewayForProfile('default')++ await requestGatewayForAgent('mini', 'helper', 'session.create', { title: 'g' })++ // Refcount hit 0 → disposed: this is the socket close that reaps the+ // runtime session server-side and makes the later prompt.submit 4001.+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()+ })++ it('plain-profile retain leases the pooled profile socket and releases it', async () => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ installDesktop(+ vi.fn(async (profile: null | string) =>+ profile ? { port: 5151, profile, token: 'secondary-token' } : { port: 4242, token: 'primary-token' }+ )+ )+ await ensureGatewayForProfile('default')++ const release = await retainGatewayForAgent(null, 'worker')+ await requestGatewayForProfile('worker', 'session.create', { title: 'g' })+ await requestGatewayForProfile('worker', 'prompt.submit', { session_id: 'rt-1', text: 'hi' })++ expect(secondaryGateways).toHaveLength(1)+ expect(secondaryGateways[0].close).not.toHaveBeenCalled()++ release()+ expect(secondaryGateways[0].close).toHaveBeenCalledOnce()+ })+})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex f6a3ccff593..1f578ecd609 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -774,6 +774,80 @@ export function retainGatewayForRelay(connectionId: null | string, profile: stri}}+/**+ * Hold `profile`'s socket open across a multi-RPC sequence without activating+ * it (#93602). Every requestGatewayForProfile/requestGatewayForAgent call is a+ * per-request lease: at refcount 0 a non-retained secondary is disposed, so a+ * session-scoped sequence (session.create → attach → prompt.submit) minted a+ * runtime id on a socket that closed between calls — the gateway detached the+ * session on WS disconnect and the next RPC hit 4001 "not in memory". Callers+ * acquire this lease before the first session-scoped RPC and release it in a+ * `finally`; the refcount keeps the socket (and the session it minted) alive+ * for the whole sequence. Primary/shared-primary routes return a no-op release.+ */+export async function retainGatewayForAgent(connectionId: null | string, profile: string): Promise<() => void> {+ const key = normKey(profile)+ const scope = registryBackendScopeKey(connectionId, key)++ if (scope === key) {+ // Plain-profile route: gatewayForProfile's request lease IS the retain —+ // hold it until the caller releases.+ const route = await gatewayForProfile(key, true)++ return route.release+ }++ if (!window.hermesDesktop?.getConnectionFor) {+ // No registry dialing in this build — nothing to hold; the request path+ // will throw its own actionable error.+ return () => undefined+ }++ const entry = g.secondaries.get(scope) ?? createSecondary(key, connectionId)++ // Existing dev-HMR entries predate request leases/ownership.+ if (!Number.isFinite(entry.activeRequests)) {+ entry.activeRequests = 0+ }++ if (typeof entry.retained !== 'boolean') {+ entry.retained = true+ }++ entry.wantOpen = true+ entry.activeRequests += 1++ let released = false++ const release = () => {+ if (released) {+ return+ }++ released = true+ entry.activeRequests = Math.max(0, entry.activeRequests - 1)++ if (entry.activeRequests === 0 && !entry.retained && !relayRetained(entry) && g.activeKey !== entry.scope) {+ disposeSecondary(entry)++ if (g.secondaries.get(entry.scope) === entry) {+ g.secondaries.delete(entry.scope)+ }+ }+ }++ try {+ if (!isOpen(entry.gateway)) {+ await openSecondary(entry)+ }+ } catch (error) {+ release()+ throw error+ }++ return release+}+// Open `profile`'s socket WITHOUT making it active — the hover-intent pre-warm// (store/profile). Runs the same spawn + connect chain as a real switch, so by// click time ensureGatewayForProfile finds an open socket and just activates