The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
teknium1803e3f4092cf
diff --cc apps/desktop/electron/main.tsindex 4a29e2ae7e0,ed9512ddbf6..c89e9136ba4--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -17635,8 -18925,39 +17705,40 @@@ function configureSpellChecker()}}+ // Does quitting take the agent down with the app? Reads the primary profile's+ // route through the same resolver resolveRemoteBackend uses, plus every backend-// the quit teardown below will stop (spawned children, SSH-managed servers).++// the quit teardown below will stop (SSH-managed servers; the local gateway is++// attached, never owned).+ // A route we can't resolve counts as owned: the lost-work warning is the safe+ // side to be wrong on.+ function quitStopsBackendWork(): boolean {+ let primaryRouteKind: 'cloud' | 'remote' | 'ssh' | null++ try {+ primaryRouteKind =+ resolveDesktopRemoteRoute({+ config: readDesktopConnectionConfig(),+ env: {+ token: process.env.HERMES_DESKTOP_REMOTE_TOKEN,+ url: process.env.HERMES_DESKTOP_REMOTE_URL+ },+ profile: primaryProfileKey(),+ registry: readDesktopConnectionsRegistry()+ })?.kind ?? null+ } catch {+ return true+ }++ const ownedBackendCount =+ (backendConnectionState.getProcess() ? 1 : 0) ++ [...backendPool.values()].filter(entry => entry?.process).length ++ sshConnections.size++ return backendOwnedByApp({ ownedBackendCount, primaryRouteKind })+ }+// Ask before a quit kills a turn in flight. True when the quit was intercepted- // and the confirmation is on screen; "Quit Anyway" re-enters before-quit with+ // and the confirmation is on screen; the confirm button re-enters before-quit with// the latch set and falls straight through to the teardown below.function heldQuitForActiveWork(event: Electron.Event): boolean {if (SKIP_QUIT_CONFIRM || quitConfirmedWithActiveWork || isQuittingForHandoff) {diff --cc apps/desktop/electron/quit-guard.test.tsindex ddedc3f4dcc,58c91150d98..80c9d5f7adf--- a/apps/desktop/electron/quit-guard.test.ts+++ b/apps/desktop/electron/quit-guard.test.ts@@@ -54,16 -51,45 +54,46 @@@ test('quitPromptFor summarizes past thassert.ok(prompt.detail.includes('• 5 more'))})- test('active-work reports with unknown lifecycle keep a scoped confirmation, not a work-loss claim', () => {- // The real IPC summary has no connection identity or Desktop-tool activity.- // Neither named nor untitled work proves it is independent of the client.- for (const titles of [[], ['Fix login']]) {- const work = mergeActiveWork([normalizeActiveWork({ count: 1, titles })])- const prompt = quitPromptFor(work, false)-// #79579: only a backend the app owns (spawned locally, or started over SSH)-// dies with it. A remote URL or Hermes Cloud backend keeps the turn running++// #79579: only a backend the app owns (started over SSH) dies with it. The++// local profile gateway is attached (`hermes gateway ensure`), and a remote URL++// or Hermes Cloud backend is supervised elsewhere: all keep the turn running+ // after the app quits, so the prompt must not claim the work is lost.-test('backendOwnedByApp: a local primary is owned even before its child attaches', () => {- assert.equal(backendOwnedByApp({ ownedBackendCount: 0, primaryRouteKind: null }), true)++test('backendOwnedByApp: the local gateway is attached, not owned', () => {++ assert.equal(backendOwnedByApp({ ownedBackendCount: 0, primaryRouteKind: null }), false)+ })- assert.ok(prompt)- assert.match(prompt.detail, /[Rr]unning and queued work on a persistent gateway continues after Desktop quits/)- assert.match(prompt.detail, /[Aa]ctivity that depends on this app or an older connection may be interrupted/)- assert.doesNotMatch(prompt.detail, /work.*(?:lost|stops)|stops the agent|all work continues/i)- }+ test('backendOwnedByApp: an SSH primary is owned (the app starts and stops that server)', () => {+ assert.equal(backendOwnedByApp({ ownedBackendCount: 0, primaryRouteKind: 'ssh' }), true)+ })++ test('backendOwnedByApp: a remote URL or cloud primary with nothing spawned is not owned', () => {+ assert.equal(backendOwnedByApp({ ownedBackendCount: 0, primaryRouteKind: 'remote' }), false)+ assert.equal(backendOwnedByApp({ ownedBackendCount: 0, primaryRouteKind: 'cloud' }), false)+ })++ test('backendOwnedByApp: a remote primary alongside a spawned backend stays owned', () => {+ // Another window/profile may be running its turn on that local child.+ assert.equal(backendOwnedByApp({ ownedBackendCount: 1, primaryRouteKind: 'remote' }), true)+ })+-test('quitPromptFor warns about lost work when the app owns the backend (local)', () => {- const owned = backendOwnedByApp({ ownedBackendCount: 1, primaryRouteKind: null })++test('quitPromptFor warns about lost work when the app owns the backend (SSH)', () => {++ const owned = backendOwnedByApp({ ownedBackendCount: 1, primaryRouteKind: 'ssh' })+ const prompt = quitPromptFor({ count: 1, titles: ['Fix login'] }, false, owned)++ assert.ok(prompt)+ assert.ok(prompt.detail.includes('is lost'))+ assert.deepEqual(prompt.buttons, ['Keep Running', 'Quit Anyway'])})+-for (const primaryRouteKind of ['remote', 'cloud'] as const) {- test(`quitPromptFor says the agent keeps running on a ${primaryRouteKind} backend`, () => {++for (const primaryRouteKind of [null, 'remote', 'cloud'] as const) {++ test(`quitPromptFor says the agent keeps running on a ${primaryRouteKind ?? 'local gateway'} backend`, () => {+ const owned = backendOwnedByApp({ ownedBackendCount: 0, primaryRouteKind })+ const prompt = quitPromptFor({ count: 1, titles: ['Fix login'] }, false, owned)++ assert.ok(prompt)+ assert.ok(prompt.detail.includes('• Fix login'))+ assert.ok(!prompt.detail.includes('lost'), 'a backend that outlives the app loses nothing')+ assert.ok(prompt.detail.includes('keeps running'))+ assert.notDeepEqual(prompt.buttons, ['Keep Running', 'Quit Anyway'])+ })+ }diff --cc apps/desktop/electron/quit-guard.tsindex eb6628d6f38,aee55e6575c..4ce93131a25--- a/apps/desktop/electron/quit-guard.ts+++ b/apps/desktop/electron/quit-guard.ts@@@ -1,7 -1,12 +1,14 @@@- // Persistent gateways own their work independently of Desktop. Renderer reports- // do not identify connections or client-dependent activity, so a busy report- // still needs a scoped confirmation, not a claim that quitting loses all work.- // The decision + copy live here so main.ts only owns the IPC and dialog call.+ // Quitting with a turn in flight kills the backend mid-tool-call: the work is+ // lost, and anything the agent had half-written to disk stays half-written.+ // Renderers publish what they're running; the main process asks before it lets+ // that go. The decision + copy live here (pure, testable) so main.ts only owns+ // the IPC and the dialog call.+ //-// That's only true for a backend the app owns. A remote URL or Hermes Cloud-// backend is supervised elsewhere and finishes the turn after the app quits,-// so its prompt says so instead of warning about lost work (#79579).++// That's only true for a backend the app owns: an SSH-managed server the app++// starts and stops. The local profile gateway is attached, not owned (`hermes++// gateway ensure`): it keeps cron, messaging adapters and the in-flight turn++// running after the app quits, exactly like a remote URL or Hermes Cloud++// backend, so those prompts say so instead of warning about lost work (#79579).const MAX_LISTED = 4@@@ -57,6 -64,26 +66,26 @@@ export interface QuitPromptmessage: string}+ export interface BackendOwnershipInput {+ /**+ * Backends this app stops when it quits: spawned local children plus+ * SSH-managed servers, across the primary and every pooled profile.+ */+ ownedBackendCount: number- /** What the primary profile resolves to; null means a locally spawned backend. */++ /** What the primary profile resolves to; null means the local profile gateway (attached, not owned). */+ primaryRouteKind: 'cloud' | 'remote' | 'ssh' | null+ }++ /**- * Whether quitting takes the agent down with the app. Local and SSH backends- * are started and stopped by the app. A remote URL or cloud backend is not,- * but any other backend the app spawned (another window's connection, a- * pooled profile) might be where the turn is running, so it still counts.++ * Whether quitting takes the agent down with the app. Only SSH backends are++ * started and stopped by the app. The local gateway, a remote URL and a cloud++ * backend all outlive it; but any server the app itself manages (another++ * window's SSH connection) might be where the turn is running, so it counts.+ */+ export function backendOwnedByApp({ ownedBackendCount, primaryRouteKind }: BackendOwnershipInput): boolean {- return primaryRouteKind === null || primaryRouteKind === 'ssh' || ownedBackendCount > 0++ return primaryRouteKind === 'ssh' || ownedBackendCount > 0+ }+/*** The confirmation to show, or null when quitting should just proceed.*@@@ -81,8 -116,9 +118,9 @@@ export function quitPromptFordetail: [lines.join('\n'),lines.length > 0 ? '' : null,- 'Running and queued work on a persistent gateway continues after Desktop quits. ' +- 'Activity that depends on this app or an older connection may be interrupted.'+ backendOwned+ ? 'Quitting stops the agent mid-turn. Any work it has not finished writing is lost.'- : 'The agent keeps running on the remote backend. Quitting only closes Hermes on this computer; reconnect later to see the results.'++ : 'The agent keeps running on the gateway. Quitting only closes Hermes on this computer; reconnect later to see the results.'].filter(line => line !== null).join('\n')diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.tsindex 4c5cdd92bf5,a525b8c20f9..3af6857ef17--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts@@@ -1,9 -1,11 +1,12 @@@import { renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+ import { reasoningEffortPending } from '@/app/chat/session-view'+ import type { ClientSessionState } from '@/app/types'import type * as HermesModule from '@/hermes'+ import { createClientSessionState } from '@/lib/chat-runtime'-import { setSessionOwnerHint, setSessions } from '@/store/session'+import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'+import { $activeSessionId, setSessionOwnerHint, setSessions } from '@/store/session'import { $sessionTiles, sessionTileDelegate } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex a06a0b1ae87,6177c2f4644..154dbe82aef--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@@ -428,48 -401,24 +429,51 @@@ export function useSessionTileDelegate(updateSessionState(runtimeId,- state => ({- // The deferred build reports the session's own effort later (#79807).- ...markReasoningEffortPending(state),- busy: Boolean(info?.running),- // Persist the session's own model/provider from resume so the tile- // pill does not wait on a chrome-scoped catalog read (#93892).- ...(typeof info?.model === 'string' ? { model: info.model } : {}),- ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),- ...(typeof info?.reasoning_effort === 'string'- ? { reasoningEffort: info.reasoning_effort, reasoningEffortPending: false }- : {}),- ...(typeof info?.reasoning_effort_wire === 'string'- ? { reasoningEffortWire: info.reasoning_effort_wire }- : {}),- ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),- messages:- state.messages.length > 0 ? state.messages : toChatMessages(prefetch?.messages ?? resumed?.messages ?? [])- }),+ state => {+ const previousMessages = state.messages.length > 0 ? state.messages : resumeRequestBaselineMessages++ const messages = authoritativeSnapshot+ ? resumed.messages.length > 0+ ? overlayConcurrentMessageChanges(+ mergeTileTranscript(+ resumeRequestBaselineMessages,+ resumed.messages,+ cached?.streamId+ ),+ resumeRequestBaselineMessages,+ previousMessages+ )+ : previousMessages+ : previousMessages.length > 0+ ? previousMessages+ : toChatMessages(prefetch?.messages ?? resumed.messages ?? [])++ const busyChangedWhileResuming = cached+ ? Boolean(+ state.busy &&+ (state.turnStartedAt !== cached.turnStartedAt || (state.turnLive && !cached.turnLive))+ )+ : state.busy++ const running = resolveResumedBusy(resumed.running ?? info?.running, busyChangedWhileResuming)++ return {- ...state,++ // The deferred build reports the session's own effort later (#79807).++ ...markReasoningEffortPending(state),+ ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),+ ...(typeof info?.model === 'string' ? { model: info.model } : {}),+ ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),- ...(typeof info?.reasoning_effort === 'string' ? { reasoningEffort: info.reasoning_effort } : {}),++ ...(typeof info?.reasoning_effort === 'string'++ ? { reasoningEffort: info.reasoning_effort, reasoningEffortPending: false }++ : {}),+ ...(typeof info?.reasoning_effort_wire === 'string'+ ? { reasoningEffortWire: info.reasoning_effort_wire }+ : {}),+ awaitingResponse: running && !resumed.inflight?.assistant,+ busy: running,+ messages+ }+ },storedSessionId)diff --cc tests/tools/test_async_delegation_orphan_sweep.pyindex 00000000000,db6af996471..a62e22ae405mode 000000,100644..100644--- a/tests/tools/test_async_delegation_orphan_sweep.py+++ b/tests/tools/test_async_delegation_orphan_sweep.py@@@ -1,0 -1,316 +1,317 @@@+ """A completion whose owner process died is re-offered by processes that are ALREADY running (#97202).++ Startup replay (``restore_undelivered_completions``) runs once per process, so before this a result+ persisted by a process that then died (a desktop reload) waited for the next process start. These+ tests produce the orphan with a real owner process against a real temp ``state.db``; time is injected+ (``now=``) or written into the row, never raced against the wall clock.+ """++ import os+ import queue+ import sqlite3+ import subprocess+ import sys+ import threading+ import time+ from pathlib import Path++ import pytest++ from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override+ from tools import async_delegation as ad+ from tools.process_registry import process_registry++ REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++ # The owner dispatches, its child fails (the reload-interrupted child of the report lands as+ # state='error'), the completion is persisted, and the process dies before anything delivers it.+ _OWNER = r'''+ import os, time+ from tools import async_delegation as ad+ def child():+ raise RuntimeError("interrupted: waiting for model response")+ r = ad.dispatch_async_delegation(+ goal="adversarial review", context=None, toolsets=None, role="leaf", model="m",+ session_key="bot-chat", parent_session_id="bot-parent", runner=child)+ deadline = time.time() + 10+ while ad.active_count() and time.time() < deadline:+ time.sleep(.01)+ print(r["delegation_id"], flush=True)+ os._exit(0)+ '''+++ @pytest.fixture(autouse=True)+ def _clean_state():+ ad._reset_for_tests()+ yield+ ad._reset_for_tests()+++ def _orphan(home: Path) -> str:+ """Run a real owner process under ``home`` and return the id of the completion it left pending."""+ home.mkdir(parents=True, exist_ok=True)+ env = {**os.environ, "HERMES_HOME": str(home), "PYTHONPATH": REPO}+ out = subprocess.run([sys.executable, "-c", _OWNER], cwd=REPO, env=env, text=True,+ capture_output=True, timeout=60, check=True)+ return out.stdout.strip().splitlines()[-1]+++ def _row(home: Path, delegation_id: str) -> dict:+ conn = sqlite3.connect(home / "state.db")+ try:+ conn.row_factory = sqlite3.Row+ return dict(conn.execute("SELECT * FROM async_delegations WHERE delegation_id=?", (delegation_id,)).fetchone())+ finally:+ conn.close()+++ def _set(home: Path, delegation_id: str, **cols) -> None:+ conn = sqlite3.connect(home / "state.db")+ try:+ conn.execute(f"UPDATE async_delegations SET {', '.join(f'{k}=?' for k in cols)} WHERE delegation_id=?",+ (*cols.values(), delegation_id))+ conn.commit()+ finally:+ conn.close()+++ class _Home:+ """Bind the profile home for code outside a turn, the way a delivery loop does."""++ def __init__(self, home: Path):+ self.home = home++ def __enter__(self):+ self._token = set_hermes_home_override(str(self.home))+ return self++ def __exit__(self, *exc):+ reset_hermes_home_override(self._token)+++ def _drain(q) -> list:+ out = []+ while not q.empty():+ out.append(q.get_nowait())+ return out+++ def test_orphaned_terminal_completion_is_offered_once_while_the_process_runs(tmp_path):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ row = _row(home, delegation_id)+ assert (row["state"], row["delivery_state"]) == ("error", "pending") and row["event_json"]+ q = queue.Queue()+ with _Home(home):+ # Freshly written: a live consumer may still be on it, so the sweep leaves it alone.+ assert ad.sweep_orphaned_completions(q, now=row["updated_at"] + 1) == 0+ later = row["updated_at"] + ad._ORPHAN_STALE_S + 1+ assert ad.sweep_orphaned_completions(q, now=later) == 1+ (evt,) = _drain(q)+ assert evt["delegation_id"] == delegation_id and evt["status"] == "error"+ assert evt["session_key"] == "bot-chat" and evt["restored"] is True+ # Offered once per process: the next sweep does not flood the queue with the same row.+ assert ad.sweep_orphaned_completions(q, now=later + 60) == 0+ assert q.empty()+ # Delivery still goes through the atomic claim: a second consumer (another process that+ # also offered the row) cannot claim it, and the winner's ack settles the row.+ claim = ad.claim_event_delivery(evt, "first")+ assert claim+ assert ad.claim_event_delivery(evt, "second") is None+ assert ad.complete_completion_delivery(delegation_id, claim)+ assert _row(home, delegation_id)["delivery_state"] == "delivered"+++ def test_row_owned_by_a_live_process_is_never_swept(tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ q = queue.Queue()+ with _Home(home):+ handle = ad.dispatch_async_delegation(+ goal="mine", context=None, toolsets=None, role="leaf", model="m", session_key="live",+ runner=lambda: {"status": "completed", "summary": "done"})+ deadline = time.monotonic() + 10+ while ad.active_count() and time.monotonic() < deadline:+ time.sleep(0.01)+ row = _row(home, handle["delegation_id"])+ assert row["owner_pid"] == os.getpid() and row["delivery_state"] == "pending"+ assert ad.sweep_orphaned_completions(q, now=row["updated_at"] + 3600) == 0+ assert q.empty()+++ def test_sweep_is_bound_to_the_profile_home_it_runs_under(tmp_path):+ """A→B→A: each profile's sweep reads only its own ledger and never adopts the other's row."""+ home_a, home_b = tmp_path / "a", tmp_path / "b"+ id_a, id_b = _orphan(home_a), _orphan(home_b)+ later = max(_row(home_a, id_a)["updated_at"], _row(home_b, id_b)["updated_at"]) + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ with _Home(home_a):+ ad.sweep_orphaned_completions(q, now=later)+ assert [e["delegation_id"] for e in _drain(q)] == [id_a]+ with _Home(home_b):+ ad.sweep_orphaned_completions(q, now=later)+ assert [e["delegation_id"] for e in _drain(q)] == [id_b]+ with _Home(home_a):+ assert ad.sweep_orphaned_completions(q, now=later + 60) == 0+ assert q.empty()+ assert _row(home_b, id_b)["delivery_state"] == "pending"+++ def test_restart_replay_and_sweep_never_offer_the_same_row_twice(tmp_path):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ later = _row(home, delegation_id)["updated_at"] + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ with _Home(home):+ assert ad.restore_undelivered_completions(q) == 1+ assert ad.sweep_orphaned_completions(q, now=later) == 0+ assert [e["delegation_id"] for e in _drain(q)] == [delegation_id]+++ @pytest.mark.parametrize("exhausted", ["attempts", "age"])+ def test_orphan_past_its_delivery_budget_converges_to_dropped(tmp_path, exhausted):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ row = _row(home, delegation_id)+ later = row["updated_at"] + ad._ORPHAN_STALE_S + 1+ if exhausted == "attempts":+ _set(home, delegation_id, delivery_attempts=ad._MAX_DELIVERY_ATTEMPTS)+ else:+ later = row["completed_at"] + ad._MAX_COMPLETION_REPLAY_AGE_S + 1+ q = queue.Queue()+ with _Home(home):+ assert ad.sweep_orphaned_completions(q, now=later) == 0+ assert q.empty()+ assert _row(home, delegation_id)["delivery_state"] == "dropped"+++ def test_in_flight_claim_is_left_to_its_holder(tmp_path):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ row = _row(home, delegation_id)+ later = row["updated_at"] + ad._ORPHAN_STALE_S + 1+ _set(home, delegation_id, delivery_claim="other-process", delivery_claimed_at=later - 1)+ q = queue.Queue()+ with _Home(home):+ assert ad.sweep_orphaned_completions(q, now=later) == 0+ assert q.empty()+++ def test_gateway_watcher_sweeps_each_served_ledger_in_its_own_scope(tmp_path, monkeypatch):+ """The gateway's delivery loop re-offers a secondary profile's orphan while it runs."""+ from gateway.run import GatewayRunner++ home_b = tmp_path / "b"+ delegation_id = _orphan(home_b)+ stale = time.time() - ad._ORPHAN_STALE_S - 60+ _set(home_b, delegation_id, updated_at=stale, completed_at=stale)+ isolated = queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", isolated)+ runner = object.__new__(GatewayRunner)+ runner._primary_profile_name = "default"+ runner._served_profile_homes = {"default": get_hermes_home(), "b": home_b}+ runner._sweep_orphaned_completion_ledgers()+ assert [e["delegation_id"] for e in _drain(isolated)] == [delegation_id]+++ def test_tui_notification_poller_sweeps_under_its_session_profile(tmp_path, monkeypatch):+ """The desktop/TUI delivery loop runs the (throttled) sweep in the session's own profile scope."""+ from tui_gateway import server++ home_b = tmp_path / "b"+ home_b.mkdir()+ stop = threading.Event()+ seen = []++ def fake_sweep(target_queue):+ seen.append((str(get_hermes_home()), target_queue))+ stop.set()+ return 0++ monkeypatch.setattr(ad, "maybe_sweep_orphaned_completions", fake_sweep)+ isolated = queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", isolated)+ session = {"profile_home": str(home_b), "_finalized": False}+ server._notification_poller_loop(stop, "sid-orphan-sweep", session)+ assert seen and seen[0][0] == str(home_b) and seen[0][1] is isolated+++ def _tui_session(session_key: str, home: Path) -> dict:+ return {"history_lock": threading.RLock(), "running": False, "history": [], "session_key": session_key,+ "profile_home": str(home), "_finalized": False, "_notification_emitted": set()}+++ def test_offer_dropped_by_a_session_that_cannot_own_it_is_re_offered_to_the_owner(tmp_path, monkeypatch):+ """Every TUI/Desktop poller drains one process-wide queue. A session that cannot prove it owns an+ async delegation drops its copy while the durable row stays pending, so the offer must not+ suppress the next sweep: the owning session, live later, still gets the row without a restart."""+ from tools.process_registry_notifications import format_process_notification+ from tui_gateway import server++ home = tmp_path / "home"+ delegation_id = _orphan(home)+ later = _row(home, delegation_id)["updated_at"] + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ registry = type("Registry", (), {"completion_queue": q, "is_completion_consumed": lambda self, sid: False})()+ started = []+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)- monkeypatch.setattr(server, "_run_prompt_submit", lambda rid, sid, session, text, **kw: started.append(sid))++ monkeypatch.setattr(server, "_run_prompt_submit",++ lambda rid, sid, session, text, **kw: (started.append(sid), True)[1]) # accepted turn++ def drain(sid, session):+ server._notif_handle_ready(sid, session, _drain(q), session["_notification_emitted"], registry,+ format_process_notification, None)++ other, owner = _tui_session("other-chat", home), _tui_session("bot-chat", home)+ with _Home(home):+ monkeypatch.setitem(server._sessions, "sid-other", other)+ assert ad.sweep_orphaned_completions(q, now=later) == 1+ drain("sid-other", other) # the wrong session wins the dequeue while the owner is not live yet+ assert q.empty() and started == []+ assert _row(home, delegation_id)["delivery_state"] == "pending"++ monkeypatch.setitem(server._sessions, "sid-owner", owner) # the owner resumes+ assert ad.sweep_orphaned_completions(q, now=later + ad.ORPHAN_SWEEP_INTERVAL_S) == 1+ drain("sid-owner", owner)+ assert started == ["sid-owner"]+ assert _row(home, delegation_id)["delivery_state"] == "delivered"+ with _Home(home): # delivered rows are never offered again+ assert ad.sweep_orphaned_completions(q, now=later + 2 * ad.ORPHAN_SWEEP_INTERVAL_S) == 0+++ def test_offer_released_after_a_failed_tui_turn_is_re_offered(tmp_path, monkeypatch):+ """The TUI poller releases its claim and discards its copy when the turn cannot start; the row is+ pending again with one attempt spent, so the sweep offers it again instead of skipping it."""+ from tui_gateway import server++ home = tmp_path / "home"+ delegation_id = _orphan(home)+ later = _row(home, delegation_id)["updated_at"] + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)+ monkeypatch.setattr(server, "_run_prompt_submit",+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("no free worker")))+ owner = _tui_session("bot-chat", home)+ with _Home(home):+ assert ad.sweep_orphaned_completions(q, now=later) == 1+ (evt,) = _drain(q)+ assert server._notif_claim_turn(owner)+ server._notif_dispatch_event("sid-owner", owner, evt, "text")+ row = _row(home, delegation_id)+ assert (row["delivery_state"], row["delivery_claim"], row["delivery_attempts"]) == ("pending", None, 1)+ assert ad.sweep_orphaned_completions(q, now=row["updated_at"] + ad._ORPHAN_STALE_S + 1) == 1+ assert [e["delegation_id"] for e in _drain(q)] == [delegation_id]+++ def test_throttle_runs_at_most_one_sweep_per_home_per_interval(tmp_path, monkeypatch):+ calls = []+ monkeypatch.setattr(ad, "sweep_orphaned_completions", lambda q, **kw: calls.append(str(get_hermes_home())) or 0)+ q = queue.Queue()+ with _Home(tmp_path / "a"):+ ad.maybe_sweep_orphaned_completions(q, now=100.0)+ ad.maybe_sweep_orphaned_completions(q, now=101.0)+ with _Home(tmp_path / "b"): # another profile has its own clock+ ad.maybe_sweep_orphaned_completions(q, now=101.0)+ ad.maybe_sweep_orphaned_completions(q, now=100.0 + ad.ORPHAN_SWEEP_INTERVAL_S + 1)+ assert calls == [str(tmp_path / "a"), str(tmp_path / "b"), str(tmp_path / "a")]diff --cc tools/async_delegation.pyindex 0aaf70e675a,f38e39e54a4..30b9ee7fbb7--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@@ -20,10 -20,9 +20,10 @@@ import uuifrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Callable, Dict, List, Optional- from hermes_constants import get_hermes_home+ from hermes_constants import get_hermes_home, hermes_home_keyfrom tools.daemon_pool import DaemonThreadPoolExecutorfrom tools.thread_context import propagate_context_to_thread+from tools.async_delegation_worker import worker_ledger, require_ledger_ownerlogger = logging.getLogger(__name__)@@@ -239,10 -258,8 +269,9 @@@ def _owner_liveness() -> Optional[Calladef recover_abandoned_delegations() -> int:"""Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had alreadyrecorded (``record_unit_child``) are replayed with their real results."""+ require_ledger_owner()- try:- from gateway.status import _pid_exists, get_process_start_time, start_time_fingerprints_match- except Exception:+ alive = _owner_liveness()+ if alive is None:return 0now, recovered = time.time(), 0with _DB_LOCK, _transaction() as conn:@@@ -304,13 -319,8 +331,13 @@@ def restore_undelivered_completions(tarownership, otherwise a brand-new session adopts a dead session's delegation results seconds after boot(#64484)."""+ from agent.runtime_session_store import is_worker_process+ if is_worker_process():+ # The ordinary owner restores delivery-only results; a compute import+ # must neither reap that owner's ledger nor steal its delivery queue.+ return 0recover_abandoned_delegations()- now, restored = time.time(), 0+ now = time.time()with _DB_LOCK, _transaction() as conn:rows = conn.execute("""SELECT delegation_id, event_json, completed_at, dispatched_atFROM async_delegationsdiff --cc tui_gateway/session_notifications.pyindex 7b8d0b2c534,326f912ec18..c26f376e853--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@@ -629,9 -703,14 +636,11 @@@ def _notification_poller_scoped_loop(stemitted = session.setdefault("_notification_emitted", set())handle = lambda events, deferred: _notif_handle_ready( # noqa: E731sid, session, events, emitted, process_registry, format_process_notification, deferred)- last_kanban_poll = last_loop_poll = last_bot_poll = 0.0+ last_kanban_poll = last_loop_poll = 0.0while not stop_event.is_set() and not session.get("_finalized"):now = time.monotonic()+ # Completions whose owner process died after this one started (#97202); throttled per profile home.+ async_delegation.maybe_sweep_orphaned_completions(queue)- if now - last_bot_poll >= _BOT_DELIVERY_POLL_SECONDS: # bot DM → live-owner delivery latency ≤ 5 s- last_bot_poll = now- _poll_bot_live_delivery_guarded(sid, session, now)# /loop and /heartbeat wakeup drivers: fire a due tick for THIS session while idle (same claim-under-lock# as kanban dispatch). An active non-parked /goal owns the idle boundary and defers the loop tick.if now - last_loop_poll >= _LOOP_POLL_SECONDS: