`raft agent bridge` was a plain Popen child of the gateway. A SIGKILLed or OOM-killed gateway
reparented it to init, where it kept polling Raft and posting wakes to a channel endpoint nobody
serves, forever. The next gateway starts a second bridge beside it.
_spawn_bridge now starts it through process_identity.spawn_owned (its own group, handed to the
owner-death supervisor, recorded in the spawn ledger as "raft-bridge"), and _stop_bridge releases
the group once the bridge has exited (a bridge it failed to stop stays covered).
Measured on Linux, real adapter _spawn_bridge with a stand-in `raft` CLI, owner SIGKILLed,
6 s settle: origin/main 1 of 1 survived; this commit 0 of 2 descendants (bridge + supervisor).
New kill -9 / live-owner case and a _stop_bridge release test; reverting spawn_owned to the
main-era Popen turns the kill -9 case red. test_raft_adapter's multiplex test now patches the
adapter's spawn_owned seam.
The bridge is spawned detached (start_new_session, via windows_detach_popen_kwargs) so a container
stop reaches it directly (#127047). Detached also meant a SIGKILLed or OOM-killed gateway left it
running forever: still holding the port and the logged-in WhatsApp session, serving a /messages
queue nobody polls. The next gateway's connect() only recovers it if the bridge reports the same
session, script hash and read-receipt config; otherwise it kills it through the pidfile or port path,
or with a foreign profile on that port refuses to start.
The bridge now starts through process_identity.spawn_owned (_spawn_bridge_process): it still
leads its own session, and its group goes to the per-process owner-death supervisor, so it dies the
moment the gateway dies, however it dies. disconnect() releases the group once the bridge has exited.
A bridge it failed to stop stays covered. Windows keeps its detach flags (windows_detach_flags)
and its taskkill tree kill unchanged. The pidfile / port reaping for bridges left by older versions
stays: it covers bridges this process never owned.
Measured on Linux, real node bridge stand-in, owner SIGKILLed, 6 s settle:
origin/main 1 of 1 bridge survived; this commit 0 of 2 descendants (bridge + supervisor).
tests/hermes_cli/test_owned_agent_subprocs.py: a real kill -9 owner and a live control owner
through _spawn_bridge_process (child + same-group grandchild gone in 15 s, the live owner's tree
untouched), plus disconnect() releasing the group. Reverting spawn_owned to the main-era Popen turns
the kill -9 case red. Existing connect / stale-bridge tests now patch the adapter's spawn_owned
seam instead of the global subprocess.Popen, which also starts the supervisor.
Greptile "Long replies still show markers": at stream end the overflow
split ran on the raw buffer, so a reply just under the limit split right
before its closing NO_REPLY and the bare remainder went out as its own
message. Drop the closing marker from the display buffer before any split
(seal-overflow and first-send paths); the transcript keeps it.
The Discord adapter reads `approvals.discord_prompt_timeout` (default
300). The Discord docs tell users to raise it, but the key was missing
from DEFAULT_CONFIG. `hermes config` never showed it, and migration
never added it.
It is now registered with its 300 s default, next to
`approvals.timeout`. The reader, its clamping and its behaviour are
unchanged. config_defaults.py may not grow, so a three-line comment
that repeated the block comment above (why `timeout` defaults to 300)
is dropped. The approvals key table in the security guide gains a row
for it.
New invariant test: the default appears through `load_config`, and a
value written to the profile's config.yaml reaches both `load_config`
and the Discord views' reader. It fails before this commit.
Raised by review of #145948.
The gateway's timeout notice looked up the Discord-only
`expire_exec_approval` on the adapter's type by name and called it to
strip the card's buttons. That method duplicated `edit_message`'s
channel lookup, formatting and truncation.
Since #145948, every Discord approval card with a request id registers
a settle observer. A card whose request had already ended is retired
right after it is sent. On timeout, the observer's `retire("timeout")`
removes the buttons, so the notice only needs to replace the text.
`_edit_card` now always uses `edit_message`, and
`DiscordAdapter.expire_exec_approval` is gone. A timed-out card
therefore gets one button-removing edit instead of two, and core no
longer probes for a platform method by name.
`edit_message` is the streaming editor: content over the platform's
limit is truncated in place behind a dangling "(1/N)" marker, and the
adapter keeps a saturated-preview entry for it until a final edit that a
card never gets. After the timeout the card's text is the only record of
the command, so the body now gives the command whatever room the
adapter's per-chat limit leaves, measured in the platform's own units
(`max_message_length_for_chat` with `message_len_fn_for_chat`, so
Telegram's UTF-16 count is honoured). `_ea_fit`'s own copy of the
prefix bisection becomes `fit_prefix` in `gateway/platforms/base.py`, a
suffix-adding wrapper over the existing `_custom_unit_to_cp`, shared by
both. A run of three or more backticks in the
command would close the card's fence and let Discord's formatter rewrite
a table after it into a longer bullet list, so such runs are split with
zero-width spaces. The body is built inside `_edit_card`'s guard, so a
failure there still falls back to sending the notice.
The lifecycle test that races the timeout notice against `retire` now
drives the notice through `edit_message`; both orders still end with
the notice text and no controls. A new test drives the real
path, `_post_timeout_notice` → `_edit_card` → Discord's `edit_message`,
with a 5,000-char command, a heredoc holding fenced Markdown tables and
a run of seven backticks: one in-place edit that fills the message
exactly, only the card's own fence, no "(1/" marker, no preview entry,
no new message. Another fills a UTF-16-counting adapter with ASCII and
with emoji, and one whose limit lookup raises still gets the notice as a
new message. Removed the two tests of the deleted method; the two notice tests' fake adapters gain
`max_message_length_for_chat` and `message_len_fn_for_chat`.
Raised by review of #145948. `expire_exec_approval` and the probe came
from 4f86e97791 (Gille, 2026-10-27, #145948).
_drop_remote_media (main, 538755f) strips an uncached remote URL from
media_urls/types/inlined so the rest of the message is admitted. Relay
keeps a public URL whose download failed together with its original
name, so the new media_filenames list stayed one longer than media_urls
and the length check refused the whole message again.
Relay inbound attachments are localized to random relay_media_<x> temp
files, and that random basename was the only name left. The wire
media[].filename was dropped, Content-Disposition only contributed its
extension, and the document note showed the random basename as the
user's filename.
- MessageEvent.media_filenames: per-attachment original name, parallel
to media_urls with the same invariant as media_types ("" = unknown).
- _event_from_wire fills it from media[].filename by URL lookup. Older
connector payloads without the field still parse.
- RelayMediaClient.download_with_name returns (path, name). It prefers
suggested_name, then Content-Disposition parsed with the stdlib MIME
parser (quoted values, RFC 5987 filename* preferred over filename).
download() keeps its path-only signature. Storage stays a random temp
name, so duplicate names never collide.
- _localize_inbound_media carries (url, mime, name) triples, so a failed
download never shifts a neighbour's type or name.
- Document, audio and video notes use the original name when known. A
relay temp file with no known name is labelled
"(original filename unknown)" instead of its random basename. Native
cache paths (doc_<id>_<name>) render exactly as before.
- Names are untrusted: basename only, control/format characters
dropped, 255-char cap, and the existing note regex replaces quotes
and brackets.
- The names survive pending-message merges, text batching, /queue and
the native admission envelope. The envelope omits the field when no
name is known, so existing admissions keep their fingerprint.
A labelled mention such as <#C1|dev_ops_alerts> or <!subteam^S1|@eng_team_x>
was split by the italic regex on its underscores before the leaf mention
split ran, so Slack showed the token literally with a stray italic run.
The label is dropped from the element anyway, so drop it up front.
rich_text does not interpret mrkdwn, so <@U…>, <#C…>, <!subteam^S…> and
<!here|channel|everyone> tokens inside lists, quotes and table cells were
emitted as text and rendered literally. Split them into user/channel/
usergroup/broadcast elements at the emphasis leaf so surrounding bold/
italic/strike spans survive.
Fixes#133315. Squashed from #133323 (095821f, 53c8268, fcf7c97, 9fd0327).
A scheduled heartbeat muted interim messages by rewriting the turn's display
settings, and the agent build read that muted value to freeze the session's
delegation mode. Heartbeats run under the user's session key, so on a cold
agent cache a heartbeat built (and cached, and pinned) an inline agent for an
interim-on chat, and the user's later turns ran inline. The heartbeat rewrite
no longer touches interim: TurnRunner already drops interim messages for a
heartbeat turn, and the TurnContext keeps the chat's configured value, which
is what a fresh agent's delegation.gateway_mode reads.
A fresh agent restored its session's tools[] pin (schema bytes) but kept the
build-time inline flag, so the next rebuild from fresh definitions
(compaction boundary, /reload-mcp, Bot Chat refresh) re-derived the other
variant and flipped the chat mid-conversation. restore_agent_tool_prefix now
re-freezes the flag from the restored delegate_task, making the pin
authoritative.
Docs: inline turns past the notify interval still get the long-running
notice (display.long_running_notifications); the stability sentence now
names compaction, /reload-mcp and heartbeats, and the post-update exception;
a deferred delegate_task (tool_search.defer) stays background.
Tests: heartbeat-first turn with an agent cache (interim on stays
background, control, interim off stays inline), a composed cell with agent
cache + real SessionDB pin + heartbeat + restart, and pin restore followed by
a compaction or /reload-mcp refresh in both directions.
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.
New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.
How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
when it builds a session's agent (gateway/session_execution.py), and the
agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
path already uses: "results return in this tool call", no live-control
parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
(session_joins_delegation), so schema and behaviour cannot disagree. The
schema rides the session's tools[] pin: a config change applies from the
next session (/new), as delegation.backend does, and a cache eviction or
restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
parent, so /stop and an interrupting follow-up stop them; the per-child
heartbeat keeps the parent's activity fresh for the inactivity watchdog;
the async completion registry is not used. Nested and one-shot delegation
are unchanged.
Refs #95522.
A drain cancelled while on_processing_start is awaited left the typing refresh running and the
row's bracket in producer_turns, because producer_turn's finally was not entered yet. Release both
before re-raising.
A relay chat message has been admitted natively since the session authority shipped (e75bc52f50,
first released in 0.22.3; e3fdebbf87 moved it into gateway/relay/inbound_admission.py):
RelayAdapter._on_inbound commits it through admit_producer and the authority's drain runs it.
The typing refresh and on_processing_start/on_processing_complete only ever ran in
BasePlatformAdapter._process_message_background, which that path never enters. So a relay
message got no in-progress reaction, no typing / Slack "is working" status, and no outcome
reaction; only tool progress re-sent typing, so a turn without tools showed nothing. Slash
commands still go through handle_message and kept theirs.
The turn executor now brackets producer-admitted turns (relay and webhook deliveries; a messaging
admission's own adapter task already brackets it):
- admit_producer marks the event it commits; SessionAuthority._admitted records a freshly queued
row in the commit's own tracked task. A re-send of a row already running or settled is not
marked again, and a cancelled queued row drops its mark (_settle_cancelled).
- execute_admission opens the bracket when the row starts executing, not when it commits: a
message queued behind a running turn is acknowledged when it runs, as the in-band queue does
(run_turn_followup_ack) and as 0.22.2's drain task did. It starts the adapter typing refresh
with the event's thread metadata and runs on_processing_start.
- Typing lives as long as execution and stops before the reply is sent (#117300 pauses it there).
- The outcome is reported once: an interrupted turn as CANCELLED and a failed one (exception, or a
failed result) as FAILURE when execution ends; a completed one after settlement, from the
reply's send in deliver_settled (deliver_response now reports whether it delivered), or as
FAILURE when settlement dropped the reply.
- Adapters that render neither typing nor processing hooks (webhook) get no bracket; scheduled
wakes and heartbeats are not producer admissions, so they stay silent.
pre_gateway_dispatch still fires once at admission, admission stays off the transport reader and
the ACK semantics are unchanged: the bracket lives entirely on the execution side.
Baileys reports the delivery status of messages Hermes sends
(`messages.update` with `update.status` in 1:1 chats, a per-recipient
`message-receipt.update` in groups), but the bridge only handled poll
updates there, so operators could not see whether a reply was delivered
or read.
The bridge now queues a `delivery_status` event for status changes of its
own sends (tracked IDs only, so messages typed on the linked phone are
never reported). The adapter logs one gateway.log line per change and
never dispatches it as an inbound message.
Reuse an eligible housekeeping reply before output transforms, persistence
and receipt generation when the local host requires a reply. Keep permitted
silence and marker-only warnings unchanged.
Reconcile recovered stream finals with their own delivered segment,
including transformed text and split previews. Treat short recovered
answers as successful replies and sanitize them before persistence.
Cover local gateway composition, output hooks, recovery, receipt identity,
stream transports and the unchanged silence controls.
The reaps now wait out a SIGTERM grace (up to 6s each) with time.sleep, and
connect() called them inline on the loop every platform shares, freezing
Telegram/Discord/etc. while a slow WhatsApp bridge exited. Run them via
asyncio.to_thread. The psutil-fallback test reads /proc of every process,
which names files under the real Hermes home on a box running Hermes, so
it opts out of the home write guard.
main's lint now rejects time.sleep in async tests (ruff ASYNC251, health HX013).
Block on the server's FIN like main's own TIME-WAIT test in test_whatsapp_multiplex.py.
The port-free wait used a plain bind probe, which Linux refuses while the
previous bridge's closed connections sit in TIME_WAIT (up to 60s). node's
listen sets SO_REUSEADDR and succeeds then, so a normal restart failed with
whatsapp_bridge_port_busy after 10s and waited for the reconnect backoff.
Probe with SO_REUSEADDR on POSIX so only a live listener blocks the spawn.
connect() SIGTERMed the previous bridge, slept a blind 1s and spawned the
new one regardless. A bridge that was slow to exit (or ignored SIGTERM)
still held 127.0.0.1:<port>, so the new bridge died on EADDRINUSE and the
reconnect loop retried the same race forever.
- _kill_port_process / _kill_stale_bridge_by_pidfile wait out a SIGTERM
grace, then SIGKILL survivors after re-checking identity (a PID recycled
inside the window is never signalled).
- connect() replaces the blind sleep with a bounded bind-probe wait for the
port and fails with a named retryable whatsapp_bridge_port_busy instead
of spawning onto a busy port. A holder that is not our bridge is still
never killed.
- Listener discovery falls back to psutil when neither lsof nor ss is
installed; without it the scan was silently empty and nothing was reaped.
- A bridge that dies during the post-spawn health wait no longer leaves a
dead-PID bridge.pid; disconnect() waits for a force-killed bridge to exit.
- bridge.js handles the listen error and exits with a clear EADDRINUSE
message instead of an unhandled stack trace.
Review finding P2 on #146120: cancelling the hot-serve's bare asyncio.to_thread
await left the reservation worker retrying. Once the transient holder let go it
took the profile's gateway.lock flock AFTER the canceller's ownership cleanup,
with no coroutine left to build the authority or release it (the gateway stop
cancels the reconcile watcher, then releases reservations).
reserve_waiting_out_transient_holders takes a cancel Event: checked before each
attempt, its waits wake on it, and a grant that lands after it is set is
released at once (ReservationCancelled). reserve_profile_home_in_worker runs
the hot-serve reserve with that Event; on CancelledError it sets it, waits for
the worker to finish (absorbing further cancels), undoes a reservation the
worker completed first, then re-raises. Boot's reserve runs synchronously on
the loop before any task can cancel it, so it needs no wrapper.
The flock is never bypassed: one gateway per host, two gateways never both own
a profile.
The running multiplexer's hot-serve reserved a new profile's gateway.lock with one non-blocking
attempt (run_runtime.reserve_profile_home); a client discovery probe holding the flock in that
instant made it OwnershipConflict, and the profile was parked as "home owned by another gateway"
and only retried on an explicit control-socket rescan.
The bounded retry from the boot reserve moves into one shared helper,
runtime_ownership.reserve_waiting_out_transient_holders, used by both the boot reserve and
hot-serve: a contender that is gone by the re-check (a probe) is retried after a 15 ms backoff, a
browse reconcile or unpublished record is waited out, a live foreign owner still refuses at once,
and one fixed deadline bounds it all. Every grant is a real reserve. Hot-serve runs the reserve
in a worker thread so a wait never blocks the event loop.
Tests use real flocks held by a separate process (probe and live owner) through the real
_serve_profile_runtime, plus a persistent-flicker case that still refuses at the deadline; the
boot control asserts refusal well before the deadline instead of an absolute wall-clock bound.
Discovery (`gateway ensure`, every client's liveness check) answers "is a reservation pending?"
by taking gateway.lock's flock for an instant (gateway.status._probe_lock_file). A booting
gateway whose non-blocking reserve landed in that instant re-checked which homes conflict, found
none (the probe had already let go) and still raised: `Cannot reserve gateway profiles`, exit 1,
and the client that started it reported runtime_exited. _conflicting_homes' own docstring already
promised "a home freed meanwhile is simply not listed; the next reserve attempt takes it".
- run_bootstrap._reserve_waiting_out_browse_reconcile: an empty conflict set retries (still
bounded by the existing deadline); a positively identified foreign owner still refuses at once.
- runtime_ownership.lock_record_unpublished: a record naming the CALLER is its own rolled-back
all-or-nothing attempt, so a probe holding that home during the re-check is not an owner.
Fixes the CI flake in test_multiplex_hot_serve_live::
test_named_profile_ensure_during_multiplexer_downtime_starts_the_multiplexer.
CanonicalHostedRoomService's status dropped every service retry row and its
retry_room_task only knew deferred attempts, so on the gateway route the
stalled room showed no Retry and groups.retry answered stale_generation. Keep
the prepare:<room_id> row and hand that task id to the shared service, so both
routes answer the same. The stall test now runs on both routes.
Review of #145981 (P2): after a Send is stored, a room preparation that keeps
failing (a member whose profile was deleted, a full room log) retried on every
driver pass forever, and the error only overwrote the process-wide driver
last_error that no client renders. The user saw "sent" and no member answered.
Now each room counts consecutive preparation failures (contention and
ownership moves never count). The third one appends ONE member.unavailable
event to the room ("Members could not be woken: <reason>"), which Desktop and
the Webapp already render, using the control headroom so a full room can still
say why. The room's status lists a Retry row (groups.retry, task_id
prepare:<room_id>) and a per-room last_error, and the driver stops preparing
that room until the next Send or Retry. A failed Retry stays stalled and is the
RPC's error, without a second notice.
Refs #145977
A room the gateway took over from the standalone backend
(hosted_rooms_gateway_import) refused every groups.send with
invalid_params after storing the message, and no member was woken.
The handoff commits two authority transfers: the standalone copy's fence
(authority.lost, install -> install:gateway-store, epoch 2) and the
gateway store's claim (authority.claimed, gateway-store -> install,
epoch 3). The history reader and the work-record lineage took span
boundaries from authority.claimed rows only, so the chain started at the
gateway store and the epoch-3 claim did not extend it: "authority claim
does not extend its predecessor" from every prepare_room, on Send and on
each driver pass.
authority.lost is the outgoing owner's committed record of the same
transfer (same system actor, same previous/next/epoch payload), so both
readers now count it as a span boundary under the same checks. The chain
reads install@1 -> gateway-store@2 -> install@3. Nothing is rewritten:
rooms users already imported (state.db epoch 3, shared-state.db epoch 2)
work as they are. A fork (a claim whose previous owner is not the
recorded holder, a skipped epoch) is still refused.
Send also stops reporting a stored message as failed: once the user
event commits it is the Send's result, and a failure preparing the room
afterwards is logged and left to the room driver, which runs the same
preparation on its next pass (#143239).
Mechanism: the shared daemon() fixture starts gateway daemons in a fresh
HERMES_HOME with no models.dev disk cache. Probes whose first session.create
or turn reaches a provider lookup (tool availability -> vision check ->
is_routing_aggregator -> get_provider -> fetch_models_dev) download
https://models.dev/api.json in the foreground with only a per-read timeout,
so a slow runner network stalls the probe by the download time. The stall
lands under rpc()'s 20 s deadline in test_managed_worker_images (CI job
122625883308) and under longer waits in the other probes that reach it.
Repro: a sitecustomize.py at a scratch tree root (the daemon's PYTHONPATH)
that logs every getaddrinfo('models.dev') found exactly four daemon-backed
files fetching on main (test_managed_worker_images, test_session_hosted_daemon
incl. its profiles/two daemon, test_handoff_completion_parent_context,
test_local_review_without_cached_agent). Stalling that lookup 21 s fails
test_managed_worker_images 6/6 on main with the CI shape.
Fix: daemon() writes a fresh models_dev_cache.json (one unknown provider, so
lookups stay as empty as an unreachable registry) into the child's
HERMES_HOME and every pre-made profiles/* home when none exists. Stage 3 of
fetch_models_dev serves a fresh disk cache without a request. config.yaml is
untouched (test_session_authoring_commands asserts it byte-for-byte), and a
test's own seeded cache wins. The per-test models_dev.url pin in
test_managed_worker_images is dropped; the fixture covers it.
Mechanism: the probe's daemon runs in a fresh HERMES_HOME with no models.dev disk cache. Its first
session.create builds the session inventory, whose tool-availability pass
runs check_vision_requirements -> routed_model_rejects_vision_tool_messages
-> is_routing_aggregator('custom') -> get_provider -> fetch_models_dev, a
foreground requests.get to https://models.dev/api.json with timeout (5, 10)
(per read, so a trickling multi-MB body has no total bound). On a runner
with a slow network that one fetch outlasts the probe's 20 s rpc() deadline:
CI job 122625883308 failed test_admitted_images_reach_managed_worker
[image-fixture-normal] and [image-fixture-safe] with TimeoutError inside
rpc(ws, 'session.create').
Repro: a sitecustomize.py in a scratch tree that makes
getaddrinfo('models.dev') stall 21 s fails all 6 cases on base with the CI
shape (session.create TimeoutError at 20.0 s); a 6 s stall makes
session.create take 6.5 s instead of 0.7 s.
Fix: the test's config pins models_dev.url to a refused loopback port
(http://127.0.0.1:9/api.json, the offline pattern tests/e2e, the ACP
conftest and test_session_busy_controls already use), so the fetch fails at
once and the probe stays on loopback. Under the same 21 s injection all 6
cases pass with session.create at ~0.6 s and zero non-loopback connects.
The pin is per test, not in the shared daemon() fixture: rewriting configs
there broke test_session_authoring_commands, which asserts that config.yaml
is byte-for-byte unchanged.
The salvaged handler awaited the worker_lost board write (a fresh connection plus BEGIN
IMMEDIATE on the cross-profile board, minutes of busy retries at worst) first in
execute_managed's except arm, with nothing after it guarded: a contended board delayed
settling the admission without bound, and a cancellation during the wait (a drain) skipped
lose_admission_worker and left the admission started.
The order stays (the note must land first: the submitter exits on the settled 'unknown' and the
crash sweep then books the bound interpreter, so a later write is dropped and an exit-0
worker_result reads as a protocol violation), but _settle_lost now waits for the note at most
LOSS_RECORD_WAIT_S (10 s; the write carries on as a tracked mutation, which retirement joins)
and settles in a finally, so a cancellation during the wait still settles. On the
pre-reservation path nothing is bound and the drain settles the admission itself, so the note is
not waited for there. record_worker_loss's policy parse moved inside its try, so it really
never raises; a cancellation is skipped by type, not by matching the class name as a reason
string.
Tests, through the real execute_managed with a lost child: the note lands before the
settlement even when the write is slower; a cancellation while the board write is held still
settles the admission 'unknown'. Each fails on the matching mutation (no wait; no finally).
Also the wiring through _record_lost_attempt (a Stop, a superseded generation and a
cancellation record nothing; a real loss records one event the next tick books), and the
superseded-run drop proves a write happens before it proves one is dropped.
Follow-up to the two salvaged redial changes. Review against a real owner (gateway.run with
a faked model) showed the premise holds: after a dropped socket, a new connection's
prompt.receipt returns the live receipt, and a repeated kanban.run for the same attempt (one
request id per card run) returns the same session and admission with one turn. Three gaps
remained:
- Dial failures during recovery still ended the worker, and the owner then killed the turn:
a refused connection ("Gateway connection failed"), a bootstrap identity change or
timeout during a restart, and a raw OSError from the ticket fetch. Now every transport
error (GatewayClientError that is not an owner refusal, ConnectionClosed, OSError,
TimeoutError) retries.
- A socket lost while waiting for kanban.run's answer still exited 1, although the owner may
have admitted the claim. Without an admission id the worker now asks kanban.run again.
- A runtime_draining refusal on the first connection after kanban.run answered re-called
kanban.run through a stale local; the admission now lives in one dict the next
connection reads, and runtime_retired (a stale connection to a retired authority) joins
runtime_draining as a retryable owner answer.
The four overlapping pieces of state (admission, deadline, redial_deadline, progress) collapse
into that dict plus the monotonic time of the owner's last answer: the worker gives up once
the owner has been silent for OWNER_WAIT_S, and says so ("Kanban owner unreachable for 180s")
instead of claiming the owner retains the attempt (the owner ends it once this worker exits).
Retries use jittered exponential backoff (agent.retry_utils.jittered_backoff, 1 s to 8 s plus
jitter) instead of a fixed 1 s, so a gateway restart does not get every worker's redial in the
same second. _submit_claim splits into _await_receipt and _exit_code so an "unknown" verdict
is raised after the connection loop and is never retried as a transport loss.
Tests are rewritten against a clock that moves only when the client sleeps or a scripted step
advances it (the salvaged ones depended on the exact number of monotonic() calls). 9 of 10
cases fail on main; 4 fail on the salvaged head (the dial failures, the lost kanban.run
answer, and the honest give-up message).
The owner-recovery probe (tests/gateway/fixtures/kanban_recovery_probe.py) now waits for the
worker to exit before stopping its owner. A worker still polling when the owner stops now
redials instead of exiting, and that redial starts a replacement owner, as a client's first
dial does. Under the probe's strace -f, that replacement kept the traced worker tree alive past
the probe's deadline.
Not changed: a graceful gateway restart still interrupts the turn (#144397); the worker now
reads that interrupted verdict instead of failing the redial.
When a click records the answer but Discord rejects the interaction
edit, the view was stopped but the card kept its pending embed and
dead buttons. The settle observer skips cards whose click owns the
edit, because `_backend_settled` was already set.
Now a failed edit after a recorded answer clears `_backend_settled` and
retires the card through its message: buttons removed, "already
resolved" footer. The retire runs under the same lock as the
observer's, so only one of them edits. The edit error is still raised,
as before. A failed edit on a no-op click (nothing recorded) is
unchanged.
Tests:
- The edit-failure case of test_click_stops_view_even_if_interaction_edit_fails
now asserts the card is retired.
- A new test fires the observer during the failing edit (the usual
order, since the waiter wakes before Discord answers). The observer
skips, and the click's own retire stamps the card.
Both fail on the previous commit. The new test also fails with only
the retire call removed.
Reported by Greptile on #145948.
Item 1 of the review is only partly fixed by the stale-click commit
before this one. Clearing `_backend_settled` lets the settle observer
retire the card, but the click still edited the same card with
"Approval expired — command was not run" through its own interaction
response. Nothing serializes that edit with the observer's. If the
click's edit lands last, it hides the real outcome and reattaches the
disabled controls. Discord serializes the interaction payload before
awaiting the response, so a later embed change can't repair it.
When a click on a card with a request id resolves nothing, that request
has already settled through another path. Since the earlier commits, its
observer is always registered (it is registered before the send, and a
request gone before that already retires the card). So the click now
only answers the clicker privately ("no longer pending") and leaves the
card edit to the observer.
A click whose lookup raises recorded nothing, and its request may still
be pending. It used to stamp the card "expired — not run" and disable it
for good, and that edit could race the observer too. Now it re-opens the
card for a retry, tells only the clicker ("Couldn't record your choice.
Click again, or answer with /approve or /deny." — a new string in every
locale), and leaves the final edit to the observer. A card without a
request id has no observer, so its no-op click keeps the old "expired"
edit.
Tests:
- The stale-click regression now asserts that the click never edits the
card. It fails on the previous commit.
- A new test drives a failed lookup on a really pending request with its
observer attached: the card stays live, and a later text answer
retires it with the real outcome.
- A third test pins the expired edit on a card with no request id.
Raising the `discord_prompt_timeout` cap to the platform-safe maximum
makes a gap much larger. Slash-confirm, update and clarify views never
called `stop()` when answered; only exec approvals did. discord.py keeps
an unfinished view registered after the answering edit, and its timeout
task sleeps until expiry with no upper bound.
So every answered prompt stayed registered for the whole configured
timeout, now up to a year. When the timeout finally fired, the base
`on_timeout` stamped "Prompt expired — no action taken" over "Approved
by X". The overwrite already happened on main within 900 s; the higher
cap only delays it.
`_finalize_embed` (slash confirm, update, exec approval) and the clarify
`_finish` now stop the view in a `finally`, after the answering edit, so
an edit failure still releases it. The exec view's own `finally: stop()`
is now covered by `_finalize_embed` and goes away.
New parity test: an authorized answer on each of the three views (and
the clarify "Other" hand-off) leaves the view finished. All four cases
fail on the previous commit. Exec cards stay covered by
test_discord_approval_lifecycle.
The card registered its settle observer only after `channel.send`
returned. If the request ended during the send (wait timed out, /stop,
session closed, withdrawn), the registration found no entry and the card
retired with the default reason "resolved". The card then said "This
approval has already been resolved" for a command that never ran.
Build the view first and register the observer before sending. A reason
that arrives while the card is still in flight is held on the view
(`pending_retire`) and applied as soon as the card exists. Only a
request that was already gone before the card was built still has an
unknown outcome. That card now says "⌛ This approval is no longer
pending (it timed out or was answered elsewhere)", a new outcome-neutral
string, translated in every locale. It no longer claims either
"resolved" or "not run".
Building the view outside `_build` also removes the `view_holder` list
that only existed to get the view back out. The view never depended on
the channel.
The test now covers the three orderings (after, during, before the send)
and asserts the footer. Two of them fail on the previous commit.
The runner tunnelled the approval request id to Discord as a private
`_approval_request_id` key inside the platform metadata dict. That dict
goes to every adapter that renders approval buttons. The relay adapter
forwards it verbatim, so the private key reached the external connector
in every approval prompt frame.
Add an optional `request_id` to `send_exec_approval` and to
`ExecApprovalPrompt`, have the runner pass `approval_data["request_id"]`,
and have Discord read `prompt.request_id`. The metadata passed to the
adapters is back to the thread routing it carried before the PR (`None`
in a plain chat). The always-true `"timeout_s" in approval_data` guard
goes with it.
Native-button adapters render through `_send_exec_approval_prompt`,
whose signature is unchanged. The only `send_exec_approval` override,
`LocalSessionAdapter`, takes `**kwargs`, as does every test double, so
no other adapter or double changes.
A stale button click that resolves zero gateway approvals must not mark the backend settled and suppress the already queued resolved observer. Cover the external-answer to stale-click race through the real component gate.
Review follow-ups on #145566:
- Policy checkpoint: turn.deferred receipts (explicit user retries) are bounded on
their own, so a discussion configured to its full max_rounds no longer stalls when
a deferred turn is retried while it runs.
- Both routes run a member's file preparation through prepare_before_submit: a file
the member can never take (over gateway.max_inbound_media_bytes, unbound, expired)
settles the turn as failed; a transient failure is proven not admitted and is
requeued with backoff. Neither pauses the room as uncertain execution.
- Ink TUI: the backends' "not available on this Hermes backend" answer is no longer
read as version skew; it renders a translated methodUnavailable line. The
invalid-params skew warning and older backends' bare wording are unchanged.
Refs #144648 (WA-20)
Since the unified gateway, session.mutate(compress) always summarized with a
fresh native ContextCompressor and published the rewrite. A plugin context
engine (context.engine: <plugin>) was never asked to compress and never saw
the compaction boundary, so the next agent's engine re-stored the retained
replies it had already stored (LCM-X: 10-11 surplus rows per forced
compaction).
prepare_compress now compresses with the session's own engine when it is a
plugin: the resident agent's engine, else the one the frozen policy names,
selected and bound the way agent init does. After the receipt commits (and
before the boundary eviction), the gateway sends the agent path's
post-commit notification: on_session_start(boundary_reason="compression")
plus the relay/metrics segment hand-off, which the native gateway path also
skipped. A cold session's one-off engine then gets on_session_end, the same
boundary a resident agent's eviction gives. The revision/generation fences
and publication ownership are unchanged.
Fixes#143587
The importer tests called it directly, so unhooking it from _ensure_hosted_service went unnoticed.
This drives the real start with a SessionDB and writer epoch (only the transport install stubbed)
and checks the gateway store lists and binds the standalone room.
Review of #145629:
- The import skips every room id the gateway store has ever known, held or
reserved in hosted_room_retired_ids, so a room disbanded in the gateway is
not copied back from its fenced standalone source once the tombstone is
pruned. Handed rooms are also recorded in the source
(hosted_room_gateway_handoffs) and never offered again.
- A standalone backend writes locally only when no gateway serves the
profile (absent, or an incompatible one that never imports). A starting or
restarting gateway is waited for (20 s bound), any other present one is a
retryable refusal. The gateway imports once more right after ready, off
the loop, in the owning profile's scope.
- Room calls go to the store that holds the room: standalone-only rooms run
locally, rooms handed to the gateway go to the root gateway (the only one
that imports), everything else to the selected profile's gateway.
groups.list merges them, so a named-profile gateway never hides an
existing room.
A native Desktop on a standalone `hermes serve`/`hermes dashboard` (no session
authority) kept rooms in the root shared-state.db with its own driver, so they
never appeared in the gateway's list that the Webapp and gateway-backed Desktop
share.
- tui_gateway route: when a ready gateway serves the profile, the Desktop's
groups.* calls go to it (owner_forward.forward_rpc, the path prompts already
use); with no gateway they run locally as before. RoomLink peer methods stay local.
- gateway: on hosted-service start the root home's gateway fences each
standalone room in shared-state.db (authority.lost to `<install>:gateway-store`,
so the standalone driver stops binding it and every write there is refused),
then copies the fenced rooms it lacks into its state.db and claims them
(authority.claimed, owner = host owner). Idempotent and crash-safe; the source
rows are kept.
- gateway-less standalone list hides rooms already handed over.
Refs #144648 (WA-19)
Refs #145184
After the rebase onto main f9ef116cfb, profile_serve_signature keeps main's always-digest
file_cache_version for config.yaml on the file backend (#111105, f09d03dfe2) and takes the
backend version only when the backend has no config file (supports_file_tooling() False).
The fake remote backend in the test now says so.
puts back what that build deliberately left for the remote backend, on
main's seam shape:
- RemoteBackend implements main's protocol (read_user_doc, probe_readable)
and is not a FileBackend; _route returns (backend, home) and explicit
files go through _ExplicitFile, so the is_layer branches are gone.
- One bootstrap: _ensure_bootstrap_env / bootstrap_deployment select the
backend from the process env, the launch home's .env and the managed .env.
#134362's _dotenv_backend_override did not survive its file-only refactor,
so nothing stacks; its rules are now tests (stale shell remote + .env file
boots file; empty .env value resets to file; .env-only remote selects
remote; an absent key keeps the shell value).
- The file-tooling gates main removed (backup/import/snapshot restore,
config edit, migration write-back, config backups, profile clone and
distribution install, raw config editor, xAI migration, gateway --config).
- profile_serve_signature uses the backend version for config.yaml.
- restore_config_model_settings_if_rewritten is a no-op without file tooling.
- PM's dependency runtime reads a home's selection from the local file it
publishes to (config_backend.local_file_layer), so a remote deployment
never needs the plane there or fails PM closed.
- Ratchet: _container_slots/_validate_quoted_containers move to
config_value_checks, _count_cron_jobs to backup_restore, the gateway
--config load to gateway/config_loader.
Main's e5a86d08d3 pinned a TUI Bot Chat stamped with a structured login subject
(auth:v1:[...]) as refused (not_found) for the owner's cron delivery, waiting for a
peer ticket carrying that subject. Under the single-user ruling this PR implements,
a signed-in Webapp login IS the machine owner, so that row is the owner's: the
delivery adopts it in place with its history, like a host-identity row. Only this
assertion changes; the row is still never moved aside.
Maintainer ruling: an owner restriction on self-hosted OIDC adds no real protection, because
anyone the login provider lets in already gets the agent and terminal as you on main. Remove the
first-sign-in owner pin (owner_pin.py, dashboard-auth/self-hosted-owner.json) and the
dashboard.oauth.self_hosted.owner check; the self-hosted provider is back to main's code. Who may
sign in is decided by the login provider's app configuration, and the docs now say so.
The hosted-room daemon test signs in two different IdP accounts again (as on main); both act as
the owner and share one Group Chat list.
Review of #145598 (comment 6448254020):
- Chats a Webapp tab imported before the upgrade open again: session_history_mount._reader read the
import binding by string equality while the sidebar (authorize_history) used the owner rule, so
the sidebar listed the chat and the open refused it. Both now ask binding_names().
- An old chat a Webapp tab edited is adopted again: bind_legacy_target compared the binding exactly.
- gateway.owner_identity.same_owner is now the one owner rule (owns_row_stamp folded into it), and
every comparison of a stored owner/binding/principal with a caller in gateway/ goes through it.
- Local stamps match this machine's account only.
- hosted_auth_probe: restore the refused groups.create over another tab's room id and the
'FORBIDDEN' never reaching the model, adapted to the single-owner contract.