The video-note support added a second, line-for-line copy of the video
branch in _observed_media_source and _handle_media_message, differing only in
the attribute read and the log label. Take `msg.video or msg.video_note` once
in each place instead, keeping the "video note" label for circles, and rejoin
the video_note entry of the _media_message_type table onto the next line.
adapter.py is over the 2,000-line cap, where units may only shrink: this
brings the file back to its origin/main line count (7380), so the PR adds
no lines to it. Behaviour is unchanged; the video and video-note cases of
test_native_video_is_cached and test_reply_to_a_video_note_caches_it still
pass, and each still fails with its branch removed.
group_reply_expected treats an uncaptioned voice note or audio file as spoken
(its words are not in the message text), so it returns None and the silence
notice stays. Video notes now reach the agent too, and a circle without a
caption is the same case: the question is in the audio. Without this it came
out reply_expected=False, so in a group with require_mention off a spoken
question in a circle could vanish behind a bare silence marker.
Tests: the new video-note row of
test_reply_expected_follows_who_the_group_message_addresses fails without the
change (False != None) and passes with it. Docs updated in the same sentence
that lists voice notes and audio files.
The video-note branch passes the label "video note" to
_surface_media_cache_failure, which translates the chat reply through
_MEDIA_KIND_KEYS. The label had no entry there, so a German or Japanese user
whose circle failed to download got a translated sentence with the English
words "video note" in it. Map it to the existing kind_video key ("video file"
in every catalog). The agent-visible note keeps the English "video note".
Scope: no new catalog key; a circle is reported as a video file in the reply,
which every locale already translates.
Test: test_video_note_failure_reply_is_localized (added with the test fold
later in this stack) fails with this entry removed.
Follow-up to the cherry-picked setup-text fix (salvage of #147215).
- Wizard step 4 and the plugin's security hint now share the same lines.
Before this they had drifted: only the wizard said where on the page
the ID is. Step 4 now says what the step is for instead of opening
with "the profile dialog does not show your user ID".
- Add a route for non-admins: a logged-in browser tab can open
/api/v4/users/me with its session cookie and get the user's own ID.
Mattermost reads the session cookie on API requests and only checks
CSRF on non-GET requests, so a plain GET works.
- The allowlist help text points back at step 4 again rather than
repeating one of the lookups.
- Docs (en + zh-Hans): indent the curl block under its list item so the
list no longer splits in two, add the browser route, note that
`mmctl user list` needs `--all` past 200 users, and use the canonical
docs URL (the .html form redirects).
- Move the plugin setup test into tests/gateway/test_mattermost_plugin_setup.py
next to the existing plugin setup tests and its _patch_setup_io helper,
so it no longer writes a real .env. Drop the assertions that pinned the
new wording; keep the ones that pin the old, wrong advice and the two
documented lookups.
Both setup tests fail on origin/main and pass here.
TelegramError is absent from the shared Telegram test stubs, so the import
broke test_slash_confirm_forum_callback_followup_keeps_existing_thread_behavior
with an ImportError. NetworkError covers the same transient cases (timeouts
and network failures subclass it in python-telegram-bot); BadRequest is still
caught first and keeps the decision-only fallback.
Review nit: edit_keeping_prompt suppressed every exception and fell back to the decision-only text, so a transient network error after an edit that went through replaced the kept prompt. Only a BadRequest falls back now.
Review finding: _send_interactive_card read card elements and stripped the approval deadline line on every card, including update-prompt cards. _send_exec_approval_prompt now builds the stored body from prompt.text and passes it as extra state.
Review finding: every button's data carried the 2000-char command preview, so a long CJK command made a ~30 KB card, over Teams' ~28 KB limit, and the send fell back to the plain-text prompt. The preview now stays in the adapter keyed by a per-prompt id (bounded to 256 entries); the buttons carry only that id. Cards sent before a restart still read cmd/desc from their button data.
- Timeout edit: the card now keeps why the command was flagged next to the
command (the reason was dropped; the command was already kept).
- Teams: button data carries the card's own command preview instead of a
200-char stub, so a resolved or expired card shows the whole command.
- Telegram, Slack and Feishu resolved cards drop the "If you don't answer
within N minutes it will NOT run" line, which no longer applies once
someone decided (Teams never carried it; timed-out cards already replace
the body).
Clicking a button on an approval card replaced the whole message with only
the decision ("✅ Approved once by Ana"), so a shared chat lost the record
of WHAT was approved. Discord and Slack already kept the body.
- Telegram: exec-approval and slash-confirm resolutions keep the prompt's
own rendering (Message.text_html rebuilds it from the entities, code
block included) and append the decision; a prompt with no readable body,
or one the appended line pushes past the length cap, still gets the
decision alone so the buttons never stay live. New sibling module
telegram_resolved_prompt.py; the adapter facade does not grow.
- Feishu: the card body is kept in the per-card state at send time and
rendered above the decision on the replacement card.
- Teams: a click after the approval ended replaced the card with only
"expired"; it now keeps the command and reason like the resolved card.
The lookup moved before the opt-in wait and its except was narrowed; an
unexpected `lines` shape then raised AttributeError and aborted setup before
access was configured. Catch AttributeError/TypeError again, as main did.
The live opt-in row reused list_users' 30 s timeout, so a black-holed API stalled
`hermes photon status` (previously offline-only) for 30 s. Thread a timeout through
list_users/find_user_by_phone and use 5 s for the status row only.
routing_live defaulted to True, so skipping the phone prompt still printed
"Photon setup complete. Start the gateway" although nothing can route. Start from
False (only an opted-in number flips it) and give the no-phone path its own ending
naming the command that finishes setup.
A user row without assignedPhoneNumber started a 5-minute wait that told the user only
"text the line Photon assigns": the dedicated-line lookup ran after the wait. Look the
line up first; with still no line, skip the wait and say how to finish (text the line
once it shows up, then `hermes photon status`).
The opt-in step let setup end on "✓ Photon setup complete" even when the
wait timed out, was interrupted with Ctrl-C, or was skipped on a non-TTY
run, so the user was told to start the gateway for a number Photon still
refuses ("Target not allowed for this project").
- setup: when the number is not opted in, the closing line says the setup
was saved but routing is NOT live, names the line to text, and points at
`hermes photon status`; exit code stays 0 (config was written).
- wait_for_opted_in_user: add a wall-clock deadline next to the attempt
cap, so slow list calls (30 s HTTP timeout each) cannot stretch the
advertised 5-minute wait to half an hour.
Photon's delivery plane only routes numbers whose user row carries
meta.opt_in, and that flag is set server-side when the human sends ONE
message from their phone to the row's assignedPhoneNumber. A registered
row without it looks configured everywhere but never sends or receives:
outbound fails with 'Target not allowed for this project'. Client-supplied
meta is ignored on create, so the API cannot produce the flag.
- auth.py: user_opted_in(), find_routable_user() (an opted-in duplicate
wins over list order; find_user_by_phone uses it, so setup re-runs and
status refreshes reuse the routable row), wait_for_opted_in_user() poll
(rides out transient list failures).
- cli.py setup step [4/5]: prints the assigned line to text and waits for
the opt-in to land (Ctrl-C skips; non-TTY runs skip the wait).
- status: live 'routing' row (opted in / not opted in, with the line to
text), emitted from auth.py like the credential summary.
In channels where people answer by reacting instead of replying, the
thread-context block the agent sees on a cold start dropped reactions, so a
message with twelve check-marks and no replies read as "nobody responded".
conversations.replies already returns each message's reactions array under
the history scopes the adapter requires: no extra API call, no new scope.
Each context line now ends with a compact marker such as
"[reactions: ✅x12 👀]" (up to 8 distinct emoji, then
"+N more"). Emoji names are reduced to Slack's emoji-name charset so a
crafted name cannot forge context structure, and the marker stays out of
parent_text, which drives mention wake checks.
The helper lives in the adapter_reactions_context sibling so the adapter
facade only gains the call site. Read-side only: it does not route
reaction_added events (#10583).
Telegram fills from_user with a service account (777000 for a linked
channel's auto-forward, GroupAnonymousBot for an anonymous admin) and sets
sender_chat on posts signed by a chat. Those counted as replies to another
member, so in a discussion group with require_mention off a question
commenting on a channel post (including the bot's own channel's post) came
out reply_expected=False and could vanish behind a bare silence marker. A
reply to a chat-signed post is now treated like a reply to an unknown author
(None, the notice stays). Only a reply to another known member is chatter.
_replies_to_other_member had a single caller whose earlier branches already
settle its reply-to-bot and unknown-author checks, so the reply decision is
now one branch in group_reply_expected; _quoted_reply gains its return type.
Behaviour for every existing test row is unchanged.
Tests: the channel auto-forward and anonymous-admin rows fail on the previous
commit and pass here (68 passed with test_telegram_thread_fallback.py).
A group reply whose quoted message has no from_user was not counted as a
reply to another member, but then fell through to the chatter rule, so a
statement like "agreed" came out reply_expected=False and a bare silence
marker sent nothing. The Telegram docs (and the WhatsApp rule in #133672)
promise the notice whenever the quoted author is unknown. Such replies now
return None before the chatter rule. The forum-topic-root check moves into a
small _quoted_reply helper both paths share; reply-to-bot and topic-root
behaviour is unchanged.
Found by the automated review on this PR. Test: the new statement row fails on
the previous commit and passes here; the existing "agreed?" row passed on both
because the question rule hid the gap.
group_reply_expected judges the message text or caption, and a voice note or
audio file without a caption has none: no "?", so it came out
reply_expected=False. In a group with require_mention off, a spoken question
to the bot could then vanish behind a bare silence marker. Voice and audio
without a caption now return None (the notice stays); a captioned one is
judged by its caption, and photos, stickers, documents and locations are
unchanged.
Tests: the voice-note and audio-file rows fail on the previous commit and pass
here; the captioned-voice and uncaptioned-photo rows are controls.
Review follow-ups from a standards audit:
- A reply whose quoted author is unknown is no longer treated as a reply to
another member, so a question there keeps the notice, as in #133672.
- A command with leading whitespace counts as addressed to the bot, matching
how the gateway parses commands.
- _merge_into_pending keeps the original seed semantics (get/None) instead of
setdefault, while staying at the adapter's line cap.
- The photo-batch test now runs the merged turn through the runner's delivery
path: unaddressed silence is not sent, the addressed batch gets the notice.
- Docs note the unknown-identity, unknown-author and forum-root cases.
The Telegram adapter never set MessageEvent.reply_expected, so silence_allowed()
always saw None and every bare [SILENT] / NO_REPLY on a group message became the
"returned only a silence marker" notice, posted to the whole group (#120051).
group_reply_expected (telegram_context.py) sets the per-message signal from #123271,
with the same rule the WhatsApp adapter gets in #133672:
- True for DMs and for a group message addressed to this bot: @mention, reply to
the bot, wake word (mention_patterns) or /command, in text or a caption. The
#110952 fallback stays.
- False for a group message addressed to someone else (a reply to another member,
or one that opens by @mentioning someone else) and for plain chatter. A forum
topic's root anchor is not a reply to a person.
- None for channel posts, an unknown bot identity, and an unaddressed message with
a "?", which may be a question for the bot.
Photo bursts and albums merge through absorb_reply_expected, so a batch that
includes a photo addressed to the bot stays True.
The agent can write cache/ and runtime/, so a file there may be a link or a
forged record. Hermes now deletes a Bitwarden or 1Password cache in cache/, or
a Photon sidecar record in runtime/, on first use without reading it, and
reads and writes only the copy at the top of the profile home. All four stores
are regenerated on use.
- Remove utils.adopt_legacy_file and the paths built on it.
- home_data_layout: split SECRET_CACHE_STORES into SECRET_CACHE_FILES and
LEGACY_SECRET_CACHE_PATHS.
- Backups leave out the four top-level names; the old slashed entries never
matched a root entry.
- The dashboard Files API takes its hidden names from the shared list.
A switch or cancel in the Discord /model picker set `resolved` but never
called `stop()`. discord.py kept the view registered and its 120 s timeout
running, and when that timeout fired it replaced the "Model Switched" or
"cancelled" card with "Selection expired — no model change" (#143851).
Since #145948 the other prompt views stop when answered, and
ChoicePickerView already did.
`_switch_selected_model` and `_on_cancel` now call `self.stop()` as soon
as they set `resolved`, before any await. A slow switch therefore can't
run into the timeout, and the view leaves discord.py's store at once.
The `on_timeout` guards from the previous commit still handle a timeout
discord.py had already queued when the click landed (stop() can't cancel
that task); both now carry a comment saying so.
Test: the two picker answers join `test_answered_view_is_released`, which
asserts the view is finished.
Fix proposed in #143851 by @jimstratus; the same guard was first
submitted in #69685 by @tuancookiez-hub.
Co-authored-by: Jim Stratus <116782964+jimstratus@users.noreply.github.com>
A Discord button view keeps running its timeout after a click resolves it.
_HermesView.on_timeout and ModelPickerView.on_timeout did not check
`resolved`, so the timeout overwrote the "Approved/Denied by ..." footer
(or the switched-model embed) with "expired" on a prompt that was already
answered. ChoicePickerView already had this guard; this applies it to the
base view (slash-confirm, update, clarify) and the model picker.
Move _resolve_exec_approval_admin_gate into adapter_config_readers.py
(re-exported from adapter.py) to offset the facade's line growth.
[Salvage, rebased onto main: since #145948 slash-confirm, update and clarify
stop() when answered, and the exec card has its own on_timeout (retire,
guarded by _backend_settled), so its test case is dropped. The base guard
still covers a timeout discord.py dispatched in the same tick a click
landed: stop() cannot cancel an on_timeout task that is already queued.]
The Bitwarden and 1Password disk caches (bws_cache.json, bws_cache.enc.json,
op_cache.json) and the Photon sidecar runtime record (photon-sidecar.json) now
live directly in the profile home instead of cache/ and runtime/. A sandbox
that hides credential files by path can only hide them safely at the top of
the home: the agent can rename a folder it writes, such as cache/ or runtime/,
and read a hidden file below it at the new path.
The first read moves a copy from the old path with a rename, so the file keeps
its permissions. When both copies exist, Hermes removes the old one; when the
move fails, Hermes keeps reading and writing the old copy, so only one copy is
ever live. Clearing a cache or deleting the record removes both locations.
SECRET_CACHE_STORES in hermes_cli/home_data_layout.py lists these stores at
both locations, and every guard that keeps a list of credential stores uses
it: PROFILE_CREDENTIAL_PATHS (profile export and distribution), the file
tools' read and write denies, and the gateway's media-delivery deny. The
1Password cache was missing from all of them. The dashboard Files API blocks
the new basenames, backups leave the top-level stores out, and the flat-install
.gitignore ignores them.
A new test takes each store's path from its writer and checks that every guard
covers it at the current and the old location.
Review (nits 5, 10): the ddgs worker's marker and comment said its 30 s cap kills the worker's
group; _terminate_and_reap signals the worker pid only. The WhatsApp adapter still described
adopting a crashed gateway's bridge, which no longer survives its gateway (it is spawn_owned);
adoption now only meets a bridge a pre-update gateway or another process left, and needs no
re-pair. Comments only.
Review (W6): RaftAdapter._stop_bridge runs from async disconnect() and ended with
release_process_group_once_empty at its default 1 s timeout, against the API's own rule
(timeout=0 for async callers). proc.terminate() signals only the leader, so any child left in the
bridge's group made disconnect stall the loop for the full second (main: 0 s). It now probes once
(timeout=0), like the WhatsApp adapter and LSP; a group with a live member stays covered either
way. The dashboard's WhatsApp pairing stop runs on the event loop too and gets the same.
Test: stopping a bridge whose helper survives TERM returns well under the old 1 s wait and keeps
the group covered; fails with the default timeout.
Same class as the router fix: nine stop paths released their group from the owner-death supervisor
as soon as the leader exited, but members that ignore TERM or outlive the leader keep the group
alive. Releasing it let those members survive a later kill -9 of this process.
Lightpanda, real-profile Chrome, embedded cua-driver, the TTS command provider, dashboard WhatsApp
pairing, the raft and WhatsApp bridges, verify's app server, agent-browser session groups, and
Browser Use harness daemons stopped by --reload now go through release_process_group_once_empty.
New test stops a raft bridge whose TERM-ignoring helper survives. It fails when raft releases
unconditionally, and the group stays covered with the fix. Test seams moved from the per-module
release_process_groups name to the shared helper.
Reported by Greptile on #137057 (thread on the router).
The detached-spawn check (scripts/check_detached_spawns.py, from the owned-child API) flags every
start_new_session outside spawn_owned. Five sites in this family are deliberately not owned. Each
now carries a `detached-spawn: ok — <why>` marker, so the check passes without a baseline entry:
- iron-proxy daemon: meant to outlive the CLI that started it; `hermes egress stop` ends it
through the pidfile + nonce.
- google_meet bot: reached through files across turns and stopped by meet_leave (pid in
.active.json).
- photon sidecar: exits on stdin EOF (PHOTON_SIDECAR_WATCH_STDIN). kill -9 probe with that exact
watch block: 0 of 1 survived; the same probe with the watch off: 1 of 1 survived.
- ddgs search worker: awaited under a 30 s cap that kills its group. Blocked reading its request
on a stdin pipe, it exits when the owner dies (kill -9 probe: 0 of 1 survived).
- secret_sources command helper: awaited under a hard timeout (default 3 s) that kills its group.
Comments only; no behaviour change.
`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.
`ExecApprovalView.retire` repeated `_HermesView._expire_embed`: grey
the first embed, stamp the footer, edit the message. The only
differences were that retire removed the controls (`view=None`) and
logged a failed edit.
`_expire_embed` now takes `keep_controls` (default True, so the other
views' timeouts look the same as before), and retire calls it with
False. A failed stamp is now logged at debug instead of silently dropped, for
every view that stamps through it (approval, slash confirm, update,
clarify; the model and choice pickers have their own timeout edit).
Raised by review of #145948. The copied block came from 39b2158afc
(Gille, 2026-10-27, #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).
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).
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.
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.
Replaying the branch onto main linearly resurrected port_accepts_listen, the
duplicate helper the branch dropped when it merged main (#140186 already
gives port_is_free the bridge's SO_REUSEADDR semantics). Restore the merged
tree: one helper, one contract.
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.
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.
adapter.py was already far past the 2,000-line limit, and this stack
grew it from 7,414 to 7,512 lines. AGENTS.md lets a unit that is
already over the limit only shrink. The file's FILE_LINES allowance
covers an earlier platform-table move, not the approval code.
ExecApprovalView now lives in adapter_exec_approval_view.py. Its body
moved verbatim: build_exec_approval_view(discord, base, unauthorized=...)
returns the class, and _define_discord_view_classes assigns it to the
same module global as before. The one change inside the body: the
failed-lookup log now carries its traceback (exc_info=True), which the
health check requires of a catch-all in a new file. A builder is needed because discord.py
can be installed lazily after the adapter is imported, and the other
views are defined the same way. adapter.py ends at 7,374 lines, 40 below
main.
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.