Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution

teknium11958b2a14690
diff --cc apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts
index dc06b6c769e,7544aeeb115..71d36f2d908
--- a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts
+++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts
@@@ -208,27 -208,42 +208,62 @@@ describe('createSessionRpcDispatcher: e
})
})
+ describe('createSessionRpcDispatcher: routes by the session OWNING connection when two connections share a profile name', () => {
+ // Two registered connections, both exposing `default` (the default install:
+ // this device + a remote gateway), and the window's primary is the OTHER
+ // connection. A bare profile name carries no connection identity, and the
+ // profile door (requestGatewayForProfile -> gatewayForProfile) resolves a
+ // bare name equal to the primary profile against the PRIMARY socket — a
+ // different machine than the one holding the session. The inbound event
+ // already proved which socket owns the runtime, so that exact owner has to
+ // outrank the connection-blind row profile: otherwise the 2nd prompt of a
+ // `This device` chat is answered by the remote backend with
+ // `4001 session not found`.
+ function twoConnections(): void {
+ $connectionsRegistry.set({ connections: [{ id: 'local' }, { id: 'homelab' }] } as never)
+ }
+
+ it('routes a session that lives on the LOCAL connection back to that connection', async () => {
+ gatewayMocks.activeConnectionId = 'homelab'
+ twoConnections()
+ recordSessionEventScope({ connectionId: 'local', profile: 'default', session_id: 'rt-local' })
+ setSessions([makeSessionInfo({ id: 'rt-local', profile: 'default' })])
+ const { ambientRequest, request } = dispatcher()
+
+ await expect(request('prompt.submit', { session_id: 'rt-local', text: 'again' })).resolves.toEqual({
+ routed: true
+ })
+
+ expect(gatewayMocks.requestGatewayForAgent).toHaveBeenCalledWith('local', 'default', 'prompt.submit', {
+ session_id: 'rt-local',
+ text: 'again'
+ })
+ expect(gatewayMocks.requestGatewayForProfile).not.toHaveBeenCalled()
+ expect(ambientRequest).not.toHaveBeenCalled()
+ })
+ })
+
describe('createSessionRpcDispatcher: stale runtime recovery', () => {
+ it('surfaces canonical refusals without requesting another resume of the healthy selected session', async () => {
+ setSessions([makeSessionInfo({ connection_id: 'local', id: 'stored-omar', profile: 'omar' })])
+ const { request } = dispatcher(undefined, 'stored-omar')
+
+ for (const reason of ['invalid_params', 'permission_denied', 'stale_generation', 'profile_mismatch']) {
+ const error = Object.assign(new Error(reason), { code: 4001, data: { reason } })
+ gatewayMocks.requestGatewayForAgent.mockRejectedValueOnce(error)
+ await expect(request('config.get', { session_id: 'rt-omar' })).rejects.toBe(error)
+ expect(sessionMocks.requestSessionResume).not.toHaveBeenCalled()
+ }
+
+ const missing = Object.assign(new Error('not_found'), { code: 4001, data: { reason: 'not_found' } })
+ gatewayMocks.requestGatewayForAgent.mockRejectedValueOnce(missing)
+ await expect(request('process.list', { session_id: 'rt-omar' })).rejects.toBe(missing)
+ expect(sessionMocks.requestSessionResume).toHaveBeenCalledExactlyOnceWith('stored-omar', {
+ connectionId: 'local',
+ profile: 'omar'
+ })
+ })
+
it('requests a durable rebind for the visible session after a structured 4001', async () => {
setSessions([makeSessionInfo({ connection_id: 'local', id: 'stored-omar', profile: 'omar' })])
gatewayMocks.requestGatewayForAgent.mockRejectedValueOnce(
diff --cc apps/desktop/src/app/contrib/wiring-routing.ts
index b7cd694d1e1,c0d8835b8a6..b51ea83160b
--- a/apps/desktop/src/app/contrib/wiring-routing.ts
+++ b/apps/desktop/src/app/contrib/wiring-routing.ts
@@@ -5,8 -5,12 +5,8 @@@
* React/Electron controller module.
*/
- import type { SessionOwnerRoute } from '@/store/session-request-router'
+ import type { SessionOwnerRoute, SessionOwnerScope } from '@/store/session-request-router'
-import { SETTINGS_ROUTE } from '../routes'
-
-/** The in-app destination for pool-cap recovery. */
-export const POOL_LIMITS_SETTINGS_ROUTE = `${SETTINGS_ROUTE}?tab=config:advanced`
/**
* Resolve a runtime session id back to its stored id by reverse-scanning the
diff --cc apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 12207e2238a,a67815115e8..28c5e0d55ed
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@@ -852,9 -857,9 +863,10 @@@ export function useSessionActions(
cwd,
capturedRoute,
requestedProfile,
- options?.route === null || defaultTarget?.route === null
+ options?.route === null || defaultTarget?.route === null,
+ workspaceScope.workspaceMode !== 'bots'
)),
+ request_id: crypto.randomUUID(),
...(workspaceScope.workspaceMode === 'bots' ? { hidden: true } : {})
}
diff --cc apps/desktop/src/store/profile.test.ts
index 1da7bdc6ab0,9e0488d73d6..f91218e92c7
--- a/apps/desktop/src/store/profile.test.ts
+++ b/apps/desktop/src/store/profile.test.ts
@@@ -18,8 -21,17 +21,10 @@@ vi.mock('@/store/gateway', () => (
activeGatewayProfileKey: () => ensureGatewayForProfile.mock.lastCall?.[0] ?? $activeGatewayProfile.get(),
ensureGatewayForAgent,
ensureGatewayForProfile,
- openGatewayForProfile
+ openGatewayForAgent,
+ openGatewayForProfile,
+ openSecondaryCount
}))
-// The pool-limits atom is profile.ts's live saturation signal — keep the real
-// one so tests can move the cap via the store, but stub its IPC bridge.
-vi.mock('@/store/pool-limits', async () => {
- const { atom } = await import('nanostores')
-
- return { $poolLimits: atom({ idleMs: 600_000, maxBackends: 3 }) }
-})
vi.mock('@/hermes', () => ({
getProfiles: vi.fn(async () => ({ profiles: [] })),
setApiRequestProfile: vi.fn()
diff --cc tests/tui_gateway/test_relay_live_author.py
index f3a482ad1d8,0b109f03373..fde458cb414
--- a/tests/tui_gateway/test_relay_live_author.py
+++ b/tests/tui_gateway/test_relay_live_author.py
@@@ -57,29 -57,20 +57,30 @@@ def turn_env(monkeypatch, tmp_path)
monkeypatch.setattr(srv, "_get_usage", lambda agent: {})
-def test_live_relay_stamps_the_sender_as_a_delivery_author(tmp_path, monkeypatch):
+def test_live_relay_forwards_sender_to_canonical_authority(tmp_path, monkeypatch):
+ from tools import bot_live_delivery
+
home = tmp_path / ".hermes"
(home / "profiles" / "ops").mkdir(parents=True)
+ (home / "profiles" / "ops" / "config.yaml").touch() # identity marker: bare dirs are not profiles
monkeypatch.setenv("HERMES_HOME", str(home))
submitted = []
- monkeypatch.setitem(srv._methods, "prompt.submit", lambda rid, p: submitted.append(p) or srv._ok(rid, {"status": "streaming"}))
- monkeypatch.setattr(srv, "_profile_home", lambda name: home / "profiles" / name)
- monkeypatch.setitem(srv._sessions, "live-ops",
- {"profile_home": str(home / "profiles" / "ops"), "pending_title": "Bot Chat", "history": []})
-
- _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", "from_profile": "coder", "from_handle": "coder"}))
-
- assert submitted == [{"session_id": "live-ops", "text": "ping", "queued": True, "_turn_author": DeliveryAuthor(AUTHOR)}]
+ receipt = {"status": "queued", "delivery_id": "a" * 32, "admission_id": "admission"}
+ monkeypatch.setattr(bot_live_delivery, "authority_delivery",
+ lambda target, params: submitted.append((target, params)) or receipt)
+ monkeypatch.setitem(srv._methods, "prompt.submit",
+ lambda *a: pytest.fail("relay must not execute through the UI"))
+ monkeypatch.setattr(srv, "current_transport", lambda: None)
+
+ response = srv._methods["bot_relay.deliver"](1, {
+ "id": "a" * 32, "profile": "ops", "message": "ping",
+ "from_profile": "coder", "from_handle": "coder",
+ })
+
+ assert _result(response) == receipt
+ assert submitted == [(home / "profiles" / "ops", {
+ "id": "a" * 32, "profile": "ops", "message": "ping", "author": AUTHOR,
+ })]
def test_prompt_submit_refuses_a_client_supplied_author(monkeypatch):
diff --cc tui_gateway/methods_bot_relay.py
index 7fd38e7c905,a5eacf40b12..b17417fcf95
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@@ -54,34 -57,106 +54,39 @@@ def _(rid, params: dict, _root=_relay_r
@method("bot_relay.deliver")
-def _(rid, params: dict, _root=_relay_root, _run=_run_delivery) -> dict:
- """Deliver a relayed DM (``profile``, attribution-prefixed ``message``) into a Bot Chat ON THIS
- GATEWAY via the one-turn ``hermes -p <profile> chat -c "Bot Chat"`` transport local DMs use →
- ``{reply}``. Blocking by design (Desktop relay worker; the RPC pool keeps it off the reader)."""
- import tempfile
- profile = str(params.get("profile") or "").strip()
- message = str(params.get("message") or "").strip()
- if not profile or not message:
- return _err(rid, 4090, "profile and message required")
+def _(rid, params: dict, _root=_relay_root) -> dict:
+ """Legacy transport bridge only: canonical admission or an explicit refusal."""
+ from tools.bot_live_delivery import _delivery_id, authority_delivery
+ from tools.bot_relay import _HANDLE_RE
try:
- from tools.bot_mode_dm import MESSAGE_MAX_CHARS
- from tools.bot_relay import acquire_turn_lock
- if len(message) > MESSAGE_MAX_CHARS + 200: # + attribution headroom
- return _err(rid, 4091, "message too long")
- root = _root()
- from tools.bot_mode_probe import _roster
- known = {name for name, _ in _roster(root)}
- resolved = "default" if profile.lower() == "hermes" else profile
- if resolved not in known:
- return _err(rid, 4092, f"no profile '{profile}' on this gateway")
-
- # When THIS gateway already hosts the target's Bot Chat live, the subprocess transport is
- # fenced out by the single-owner lease and the payload dropped. Land the DM in the live
- # session via prompt.submit — the composer's choke point, so role alternation, persistence
- # and streaming behave as a typed message would.
- # (Nested per method_ctx rebinding.) See #100523.
- from tools.bot_mode_probe import BOT_CHAT_TITLE
- live_home = _profile_home(resolved)
- want_home = str(live_home) if live_home is not None else None
- live_sid = next((
- live_sid for live_sid, record in list(_sessions.items())
- if isinstance(record, dict) and (record.get("profile_home") or None) == want_home
- and _session_live_title(
- record, _session_lookup_key(record, fallback=live_sid)) == BOT_CHAT_TITLE), "")
- # The sender fields are whatever the relaying client says. The author labels memory only and grants nothing.
- from tools.bot_relay import DeliveryAuthor, delivery_env, delivery_turn_author
- from tui_gateway.methods_browser_control import _is_authenticated_identity
- sender_fields = ("from_profile", "from_handle", "from_connection")
- # A logged-in browser never relays for another connection; only the Desktop and server-internal callers do.
- if (any(params.get(k) for k in sender_fields)
- and _is_authenticated_identity(getattr(current_transport(), "auth_identity", None))):
- return _err(rid, 4095, "a logged-in client cannot name the sender of a relayed dm")
- author = delivery_turn_author(*(params.get(k) for k in sender_fields))
- if live_sid:
- # queued=True: a teammate's DM runs as the NEXT turn and never interrupts or steers a
- # turn in flight (the default busy mode does); arrivals queue in order.
- submit_params: dict = {"session_id": live_sid, "text": message, "queued": True}
- if author:
- submit_params["_turn_author"] = DeliveryAuthor(author)
- submitted = _methods["prompt.submit"](rid, submit_params)
- if "error" in submitted:
- return submitted
- reply = f"Delivered into @{resolved}'s open Bot Chat; the reply will appear there."
- return _ok(rid, {"reply": reply})
-
- def _detail(p) -> str:
- return (p.stderr or p.stdout or "").strip()[-500:]
-
- turn_env = delivery_env(author, live_home)
-
- fd, tmp = tempfile.mkstemp(prefix="hermes-relay-dm-", suffix=".txt", text=True)
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as f:
- f.write(message)
- # Per-profile turn lock serializes with any other delivery turn into this profile and
- # covers only the turn window. Worst-case hold is lock wait (bot_mode.turn_wait_seconds,
- # default 120s) + the 600s turn timeout, doubled on one retry — callers tolerate ~1320s.
- # Worst-case handler hold is lock wait (bot_mode.turn_wait_seconds, default 120s) + the 600s
- # turn timeout below — doubled when the retry policy grants one bounded re-run — so clients
- # calling bot_relay.deliver must tolerate ~1320s before assuming failure. See #93091.
- with acquire_turn_lock(root, resolved):
- proc = _run(resolved, tmp, turn_env)
- if proc.returncode != 0:
- # Retry policy: transient classes re-run the SAME session once; context_overflow
- # too — the retried turn's pre-API compaction pass compacts the over-threshold
- # transcript first (no fresh session is minted). Auth/quota/config never retry.
- # See #93091.
- from tools.bot_failure_reasons import (
- RETRY_NONE, classify_agent_error, retry_action)
- if retry_action(classify_agent_error(_detail(proc))) != RETRY_NONE:
- proc = _run(resolved, tmp, turn_env)
- finally:
- with contextlib.suppress(OSError):
- os.unlink(tmp)
- if proc.returncode != 0:
- from tools.bot_failure_reasons import classify_agent_error
- detail = _detail(proc)
- return _err(rid, 5092, f"delivery turn failed: {detail or proc.returncode}",
- data={"reason": classify_agent_error(detail)})
- # Use the same canonical whole-response predicate as live Bot Chat
- # completion. A marker remains a successful turn, but is never sent
- # back to the relay caller as visible prose.
- from tui_gateway.prompt_turn import _bot_mode_delivery_text
- reply = _bot_mode_delivery_text((proc.stdout or "").strip(), successful=True)
- return _ok(rid, {"reply": reply})
- except subprocess.TimeoutExpired:
- return _err(rid, 5093, "delivery turn timed out")
- except Exception as e:
- # 'target_busy' extends the structured refusal enum.
- return _err(rid, 5096 if getattr(e, "reason", "") == "target_busy" else 5094, str(e))
+ _delivery_id(params.get('id'))
+ profile = params.get('profile')
+ if not isinstance(profile, str) or not _HANDLE_RE.fullmatch(profile):
+ raise ValueError('invalid profile')
+ except ValueError:
+ return _err(rid, 4090, 'invalid_params', data={'reason': 'invalid_params'})
+ from tools.bot_relay import delivery_turn_author
+ from tui_gateway.methods_browser_control import _is_authenticated_identity
+ sender_fields = ("from_profile", "from_handle", "from_connection")
+ if (any(params.get(key) for key in sender_fields)
+ and _is_authenticated_identity(getattr(current_transport(), "auth_identity", None))):
+ return _err(rid, 4095, "a logged-in client cannot name the sender of a relayed dm")
+ author = delivery_turn_author(*(params.get(key) for key in sender_fields))
+ forwarded = {key: value for key, value in params.items() if key not in sender_fields}
+ if author:
+ forwarded["author"] = author
+ resolved = 'default' if profile.lower() == 'hermes' else profile
+ root = _root()
- home = root if resolved == 'default' else root / 'profiles' / resolved
++ # Same identity predicate as `profile list`: infra dirs and tombstones under profiles/ are
++ # not teammates (#99392), so a DM never targets one.
++ from tools.bot_mode_probe import _roster
++ home = dict(_roster(root)).get(resolved)
++ if home is None:
++ return _err(rid, 4092, f"no profile '{profile}' on this gateway", data={'reason': 'unknown_profile'})
+ try:
+ return _ok(rid, authority_delivery(home, {**forwarded, 'profile': resolved}))
+ except Exception as exc:
+ return _err(rid, 5094, str(exc), data={'reason': 'runtime_unavailable'})
@method("bot_relay.reply")
diff --cc tui_gateway/transport.py
index d3df8308d73,5051d6da51f..5f7fa3dadbe
--- a/tui_gateway/transport.py
+++ b/tui_gateway/transport.py
@@@ -227,13 -236,10 +241,14 @@@ class FanoutTransport
self._remove(peer)
return
- def write(self, obj: dict) -> bool:
+ def write(self, obj: dict, *, overflow: Callable[[Transport], Optional[dict]] | None = None) -> bool:
+ """Fan *obj* out. A peer whose bounded backlog is full loses its subscription; *overflow*
+ (called with its transport, under the membership lock) may return one final frame that
+ replaces the dropped backlog, so a socket that is still healthy learns it must resume
+ rather than silently continuing with partial history."""
- # Freeze the queued frame so a caller cannot mutate it after admission.
- encoded = json.dumps(obj, ensure_ascii=False)
+ # Freeze the queued frame so a caller cannot mutate it after admission. Same serialization
+ # guard as the single-peer transports: an unserializable frame reaches every peer as -32603.
+ encoded = serialize_frame(obj, "fanout", logger)
size = len(encoded.encode("utf-8", errors="surrogatepass"))
frame = json.loads(encoded)
with self._lock: