Skip to content

fix(workspace): the mic renders on speech-to-text capability, not key presence (#2695) - #2699

Merged
vybe merged 8 commits into
devfrom
fix/2695-stt-capability-probe
Sep 15, 2026
Merged

vybe merged 8 commits into
devfrom
fix/2695-stt-capability-probe

Conversation

@dolho

@dolho dolho commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

stt_available on the Workspace card was bool(tts_service.is_available()) — key presence. ElevenLabs permissions are per endpoint, so a key with Text-to-Speech but no Speech-to-Text rendered a mic that failed on every press with 401 missing_permissions, while voice replies played normally. GET /api/settings/elevenlabs reported key_configured: true, so the condition was only visible in the container log.

What changes

  • services/stt_capability_service.py (new) — one provider probe per key: a one-byte non-audio POST to /v1/speech-to-text. The provider authorises before it validates, so 401/403 → refused (with the provider's status word), any other definitive status → capable, transport error / 5xx → unknown. Costs no transcription minutes.
  • Cached, keyed on a digest of the key (stt:capability:<sha256[:16]>; 6h decided / 2min unknown; per-process fallback when Redis is down). A key change is a cache miss by construction — nothing to remember to invalidate, and get_elevenlabs_api_key() stays uncached (the --workers 2 rule).
  • Redis is the one authority (review follow-up) — the per-process _local is read only when Redis cannot be asked (no client / read raised); a Redis MISS returns None and evicts the local copy. Consulting it on a miss let worker B serve a refused that worker A's invalidate had deleted, for the rest of the 6h. Proven with a dict-backed fake Redis shared by two module instances (test_invalidate_on_one_worker_is_honoured_by_the_other + 4 siblings; 4 of 5 red against the pre-fix service).
  • Bounded + fail-soft — readers wait at most WAIT_BUDGET_SECONDS (4s); past it they get unknown and the probe fills the cache in the background. Only a definitive refusal withholds server-side dictation — resolveMicMode then falls back to the browser's own Web Speech engine where one exists, so the mic is hidden only where there is neither. One awaited O(1) read on the roster, not a fan-out (perf(workspace): the roster's latency floor is its slowest agent — defer briefing hydration off the critical path #2163 guard still green).
  • One gate — client_portal.service._stt_ready is read by the roster card, the agent page and transcribe_portal_audio, so the control a client sees and the endpoint it calls cannot disagree (bug: Workspace voice mode starts the mic and stops instantly, with every failure silent #2212's rule, kept). A real /stt 401 stores refused, so the reported symptom self-heals the cache even if the probe never ran.
  • Diagnosable — GET/PUT /api/settings/elevenlabs carry stt_capability / stt_detail / stt_checked_at beside key_configured; re-saving a key invalidates its row. Settings → Voice shows can transcribe / cannot transcribe — missing_permissions / transcription not verified next to the presence badge (utils/sttCapability.js, pure + tested).

Acceptance criteria

  • Server-side dictation is not offered when the key cannot transcribe (the mic itself is hidden only where the browser has no Web Speech engine either) — _row_to_card(... stt_ready=False) → stt_available=False; test_card_hides_the_mic_when_the_key_cannot_transcribe, test_roster_threads_the_capability_into_every_card
  • Capability by provider probe, not presence — probe() / classify_response(); test_provider_answers_partition_into_verdicts
  • Cached — test_verdict_is_cached_so_the_roster_does_not_probe_per_request
  • Invalidates on key change without a cross-worker cache — digest-keyed Redis row; test_cache_is_keyed_on_the_key_so_a_changed_key_is_a_miss
  • Fails soft — test_probe_that_cannot_complete_is_unknown_never_refused, test_a_slow_probe_answers_unknown_now_and_fills_the_cache_later, test_stt_ready_is_the_capability_verdict_and_fails_soft
  • Settings → Voice distinguishes configured from can-transcribe — sttCapability.spec.js
  • GET /api/settings/elevenlabs reflects it — test_settings_state_distinguishes_configured_from_can_transcribe

Coverage

Every test executes the changed path (the classifier, the cache, ensure_capability's bounded wait, get_roster, transcribe_portal_audio, the settings state builder) with the provider stubbed at httpx.AsyncClient. None reads source text.

Verification

pytest tests/unit/test_2695_stt_capability_probe.py tests/unit/test_2212_portal_stt_gate.py \
       tests/unit/test_2163_roster_latency_floor.py tests/unit/test_2160_agent_page_one_briefing.py \
       tests/unit/test_2196_roster_availability.py            → 125 passed
pytest tests/unit/test_*portal*.py test_ent117* test_2157* test_ent440* test_*settings* → 656 passed
vitest sttCapability.spec.js + rawColorRatchet.spec.js + settingsFieldStyles.spec.js   → 23 passed
vite build                                                                                → ok

Docs: docs/memory/architecture/backend.md (the #2212 sentence now states the capability gate), docs/memory/learnings.md entry.

Fixes #2695

🤖 Generated with Claude Code

https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

… presence (#2695)

`stt_available` was `bool(tts_service.is_available())` — a non-empty check on
the ElevenLabs key. ElevenLabs permissions are per endpoint, so a key granted
Text-to-Speech but not Speech-to-Text rendered a fully working-looking mic that
failed on every press with `401 missing_permissions`, while spoken replies
played normally on the same instance. Nothing in the UI or the admin panel could
say so: `key_configured` was honestly true.

New `services/stt_capability_service.py`: one provider probe per key — a
one-byte non-audio POST to `/v1/speech-to-text`, which authorises before it
validates, so 401/403 is `refused` (with the provider's status word), any other
definitive status is `capable`, and a transport error / 5xx is `unknown`. The
verdict is cached in Redis under a digest of the key (6h decided / 2min
unknown, per-process fallback when Redis is down), so a key change is a miss by
construction and the key resolver stays uncached across workers. Reads are
bounded (`WAIT_BUDGET_SECONDS`: a slow provider answers `unknown` now and the
probe fills the cache in the background) and fail soft: only a definitive
refusal hides the mic.

`client_portal.service._stt_ready` is now THE gate — the roster card, the
agent page and `transcribe_portal_audio` all resolve it, so the control a
client sees and the endpoint it calls still cannot disagree (#2212's rule). A
real `/stt` 401 stores `refused`, so the reported symptom heals the cache even
if the probe never ran.

`GET`/`PUT /api/settings/elevenlabs` carry `stt_capability`, `stt_detail` and
`stt_checked_at` beside `key_configured`; re-saving a key invalidates its row.
Settings → Voice renders "can transcribe" / "cannot transcribe — <reason>" /
"transcription not verified" next to the presence badge, via the pure
`utils/sttCapability.js` rule.

Tests execute every consumer of the verdict (classifier partition, cache
keying, bounded wait, roster threading, endpoint refusal, live-refusal
feedback, settings state) — none read source text.

Fixes #2695

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht
@dolho dolho added the ui PR touches the frontend UI — triggers Playwright e2e tests label Sep 11, 2026
dolho and others added 2 commits September 11, 2026 13:46
Resolve docs/memory/learnings.md: append-only log, both sides kept (dev's
2026-09-10 entries first, this branch's 2026-09-11 entry after).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht
…ace-model-choice)

The spec's own docstring says every box is taken from ONE render, but the
icon-button loop re-measured each button after `picker`/`send` were captured,
and skipped Send by coordinate (`box.x >= send.x`). The picker is a native
<select> sized by its widest option label, which re-measures ~150 ms after
paint when the web font lands (211 -> 199 px at 768 on a cold profile); a
Send read after that sits left of the earlier `send.x`, is mistaken for an
icon button, and fails 'an icon button sits right of the picker'. The race is
on dev too — instrumented: dev's picker drifts identically — this branch just
loses it more often (its unmocked requests shift the timing).

Wait for `document.fonts.ready` and for the picker to hold its box across two
consecutive reads before measuring anything, and skip Send by element
identity. 3/3 green locally at 375/768/1280 on this branch (was 2 of 5 failing
every run).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht
@vybe

vybe commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-11: not on this train — not a defect in the PR, a sibling collision. git merge-tree against the batch shows a src/ conflict that needs your intent, not a mechanical resolution:

src/frontend/e2e/workspace-model-choice.spec.js — #2714 (on this train) rewrites the spec to read every box in one page.evaluate under reduced motion and skip Send by element identity, fixing the same "an icon button sits right of the picker" flake your hunk fixes with a fonts-ready wait, a width-settle poll and an identity skip. Once #2714 lands, decide whether any of your hunk survives; most of it is the same race fixed twice.

Also flagging ahead of time: src/backend/client_portal/service.py _row_to_card gains stt_ready here and can_manage_canvases in #2619, on the same call sites. #2619 is not on this train either, so whichever of you lands second re-merges.

Merge dev after this train ships and resolve the spec. Rides the next train once re-merged.

@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

@github-actions

Copy link
Copy Markdown

⚠️ Live-instance suite skipped — merge conflict against dev.

Resolve by merging dev locally and pushing the result; the next nightly re-tests.

@vybe

vybe commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-12: not on this train — src/frontend/e2e/workspace-model-choice.spec.js conflicts with dev, and it's a real one. dev (at 682fce300→7a40408b4) already fixed the same flaky "no icon button left of Send" assertion by precomputing the button boxes; this branch fixes it differently (a document.fonts.ready + two-read width settle, then Send skipped by element identity). Both hunks (:80-100, :147-161 in the merged tree) are the same test, two ways — the train can't pick one for you. Likely the right merge keeps dev's loop and decides whether the font-settle wait is still needed on top of it.

docs/memory/learnings.md also conflicts (append collision, routine). Please merge origin/dev, resolve the spec, and push. Rides the next train once green.

@vybe

vybe commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-13: not on this train. The previous ejection (see the merge-train comment above) has no push after it — the branch head is unchanged — so the same finding stands. Rides the next train once addressed.

@vybe

vybe commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

merge-train: ejected this run — rides the next train once rebased. The branch conflicts with dev inside src/backend/client_portal/service.py (_row_to_card signature and the roster call at ~L982: ent#553's can_manage_canvases vs this PR's stt_ready), plus src/frontend/e2e/workspace-model-choice.spec.js and learnings.md. Sibling #2768 also edits client_portal/service.py and is on this train, so please merge dev after #2768 lands rather than before — one rebase instead of two. Stacked child #2702 targets this branch and will follow.

Three conflicts, resolved on their merits rather than by side:

* `docs/memory/learnings.md` — both sides appended a new entry at the top of a
  ledger. Kept BOTH; this is an append-only file and picking a side would delete
  someone's lesson.

* `client_portal/service.py` — `_row_to_card` gained `stt_ready` here and
  `can_manage_canvases` on dev, in the same signature and the same roster call.
  Kept both parameters and both kwargs; dev's `may_manage_canvases` comment is
  carried verbatim. Both call sites (the roster and the #2160 single-agent
  lookup) now pass both.

* `workspace-model-choice.spec.js` — took dev's version WHOLESALE, which makes
  this branch's `06b86be9` a no-op. Both commits fix the same flake: this branch
  waited for `document.fonts.ready` and the picker's width to settle, then
  skipped Send by element identity; dev's #2705 instead takes every box in ONE
  `page.evaluate` and emulates reduced motion. Dev's is strictly stronger — when
  all boxes come from one frame, a font re-measure cannot invalidate a relative
  assertion, so the coordinate Send-skip it keeps is sound again and no wait is
  needed at all. Two fixes for one race is worse than either; this one loses.

The two `--check` whitespace warnings (`hardeningGuide.js`, `test_voice_auth.py`)
are pre-existing on origin/dev and arrive with the merge — verified byte-for-byte
against `origin/dev` — so they are deliberately left alone rather than swept into
an unrelated branch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ
@dolho

dolho commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto dev — conflicts resolved, mergeable again.

Three conflicts, each decided on its merits rather than by picking a side:

docs/memory/learnings.md — both sides appended an entry at the top. Kept both: it is an append-only ledger and taking a side deletes someone's lesson.

client_portal/service.py — _row_to_card gained stt_ready here and can_manage_canvases on dev, in the same signature and the same roster call. Kept both parameters and both kwargs, with dev's may_manage_canvases comment verbatim. Checked the thing a "keep both" resolution usually gets wrong: both call sites — the roster and the #2160 single-agent lookup — now pass both, so neither capability is silently defaulted on one surface.

workspace-model-choice.spec.js — took dev's version wholesale, which makes this branch's 06b86be9 a no-op. Worth spelling out, because both commits fix the same flake:

  • this branch waited for document.fonts.ready and for the picker to hold its box across two reads, then skipped Send by element identity;
  • dev's frontend-e2e nightly @smoke suite is red on dev #2705 instead takes every box in one page.evaluate and emulates reduced motion per page.

Dev's is strictly stronger: when all boxes come from one frame, a font re-measure cannot invalidate a relative assertion, so the coordinate Send-skip it keeps is sound again and no wait is needed at all. Two fixes for one race is worse than either, so mine loses. The spec file no longer appears in this PR's diff.

Not swept in: git diff --check flags trailing blank lines in hardeningGuide.js and test_voice_auth.py. Both are byte-identical to origin/dev — they arrive with the merge and are not this branch's to fix.

Verified after the merge: vite build clean, frontend unit suite 130 files / 2913 tests green. The PR now contributes 9 files over dev (the STT capability service, its cache, the admin surface, and the two test suites).

@vybe

vybe commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-14: not on this train — one finding on the AC the issue underlined, needs a test the suite lacks. Lane B: /validate-pr READY, /review NEEDS-FIX. Verified against the PR ref by hand. Rides the next train once fixed.

Cross-worker staleness is still reachable — src/backend/services/stt_capability_service.py:137-139 and :148. read_cached falls through to the per-process _local whenever Redis returns nothing, i.e. on a miss, not only on a Redis error, and store writes _local unconditionally. invalidate pops _local in the calling process only. Sequence: admin fixes the key at ElevenLabs and re-saves the same key on worker A → A pops its local, deletes the Redis row, re-probes. If that probe lands unknown (2-minute TTL) or times out, the Redis row expires and worker B serves its stale refused from _local for the rest of the 6 h — mic hidden on B, shown on A. That is the "must not reintroduce cross-worker staleness" AC from #2695, and "re-saving a key invalidates its row" currently holds on one worker only. Every test stubs _redis to None (test_2695:33 autouse), so the Redis-present branch — r.get/r.set(ex=)/r.delete, from_json on a decoded row — never executes.

Fix: make _local a fallback for Redis unavailability only — after a successful r.get() that returns nothing, return None (or evict the local copy); consult _local only when r is None or the read raised. Add one fixture with a dict-backed fake Redis shared by "two workers" and prove a delete on it is honoured by the second reader.

Riders for the same push:

  • stt_capability_service.py:63-65 — comment says PROBE_TIMEOUT_SECONDS is "below the roster's patience (WAIT_BUDGET)"; it is 8.0 vs 4.0. Behaviour is right (reader stops at 4 s, probe runs on to fill the cache); the comment is inverted and invites someone to raise WAIT_BUDGET.
  • src/frontend/src/utils/sttCapability.js:30, PR body, backend.md:196 — "the Workspace mic is hidden" is browser-dependent: resolveMicMode falls back to speech on Chromium/Safari when serverStt is false, so a refused key hides the mic only where there is no Web Speech API. Say "the server-side dictation path is disabled; the browser's own engine, if any, remains."
  • backend.md — the mechanism is folded into the tts_service.py catalog line; give stt_capability_service.py its own ≤2-line entry.
  • CodeQL py/weak-sensitive-data-hashing at :103 — false positive, dismiss rather than change: a truncated SHA-256 of a ~128-bit API key used only as a Redis row name, never a verifier; same shape as db/mcp_keys.py:79. Do not switch to hmac(SECRET_KEY, …) — SECRET_KEY is per-process random when unset and would silently defeat the shared cache.

The rest traces end to end and is executed: _stt_ready → get_roster/get_agent_card → stt_available → PortalConversation.vue resolveMicMode; transcribe_portal_audio reads the same gate so card and endpoint cannot disagree; fail direction (allowed = verdict != refused) is the right one for a mic; portal receives only the boolean; 125 backend + 60 frontend tests green on the PR tree.

@vybe

vybe commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

merge-train: not on today's train — rides the next one once this is answered.

The cross-worker staleness finding from the 2026-09-14 review is unchanged on the branch, and it is the acceptance criterion #2695 states in its own words ("must not reintroduce cross-worker staleness").

stt_capability_service.py:137-139 — read_cached consults the per-process _local on a Redis miss, not only on a Redis error, and store at :148 writes _local unconditionally while invalidate pops it in the calling worker only. So: an admin re-saves the key on worker A, A deletes the Redis row and re-probes, and if that probe lands unknown (2-minute TTL) or times out, worker B keeps serving refused from its own _local for up to six hours. The mic is then hidden on B and shown on A, for the same customer, depending on which worker answers.

The shape of the fix is small — consult _local only when r is None or the read raised, and after a successful r.get() that returns nothing, return None and evict the local entry. It is out of the train's mechanical lane because it changes cache semantics and needs a test that does not exist yet: the whole Redis-present branch has zero executing coverage, since the autouse fixture stubs _redis to None (test_2695:31-33). A dict-backed fake Redis shared by two simulated workers would cover both the defect and the branch.

Everything else checks out and is worth saying so it does not get re-litigated: the probe is not per-card, it single-flights in-process with a 4s budget, it fails open on transport errors so the mic survives an ElevenLabs outage, presence stays fail-closed, the portal reads the capability off the roster payload rather than the get_current_user-gated feature-flags route, and no payload carries the key or the provider detail.

Three riders for the same push: the PROBE_TIMEOUT_SECONDS comment says it is below WAIT_BUDGET but it is 8.0 vs 4.0 (behaviour is right, the comment is inverted); the copy in three places says the mic is "hidden" when resolveMicMode actually falls back to Web Speech, so only server dictation is disabled; and the CodeQL py/weak-sensitive-data-hashing hit at :103 is a false positive worth dismissing rather than fixing — a truncated SHA-256 used as a Redis row name, same shape as db/mcp_keys.py:79. Do not switch it to an HMAC over SECRET_KEY: that is per-process random and would defeat the shared cache.

#2702 is stacked on this branch and is otherwise ready, so it lands right behind you.

dolho and others added 2 commits September 15, 2026 13:15
…en it cannot be asked (#2695)

Review finding on the AC the issue underlines ("must not reintroduce
cross-worker staleness"): `read_cached` fell through to the per-process
`_local` on a Redis MISS, not only on a Redis error, while `store` wrote
`_local` unconditionally and `invalidate` popped it in the calling worker
only. Sequence: admin re-saves the key on worker A → A pops its local,
deletes the Redis row, re-probes; if that probe lands `unknown` (2-minute
row) or times out, the row expires and worker B serves its stale `refused`
from `_local` for the rest of the 6 h — mic withheld on B, offered on A,
for the same customer.

`read_cached` now treats Redis as authoritative whenever it ANSWERS: a hit
is returned, a miss returns None AND evicts this worker's local copy (a
corrupt row is a miss too, never a fall-through); `_local` is read only
when there is no client or the read raised. `store` still writes both, so
the outage fallback stays warm.

Tests: the Redis-present branch had zero executing coverage (the autouse
fixture stubs `_redis` to None). A dict-backed `_FakeRedis` shared by two
module instances (= two uvicorn workers, each with its own `_local`) now
pins: TTLs reach the wire and rows decode; an invalidate on A is honoured
by B and B's local copy is evicted; the review's 6 h sequence (unknown row
expires) is a miss; the local copy is used only while the read raises; a
corrupt row is a miss. 4 of the 5 are red against the pre-fix service.

Riders from the same review:
- `PROBE_TIMEOUT_SECONDS` comment said it sits BELOW `WAIT_BUDGET`; it is
  8.0 vs 4.0 and deliberately above — the reader stops at 4 s, the probe
  runs on to fill the cache. Comment now says why.
- "the Workspace mic is hidden" (service log, docstring, Settings hint,
  backend.md) is browser-dependent: `resolveMicMode` falls back to Web
  Speech when `serverStt` is false, so a refused key disables server-side
  dictation and hides the mic only where the browser has no engine.
- `stt_capability_service.py` gets its own catalog entry in backend.md
  instead of riding the `tts_service.py` line.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@dolho

dolho commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in beae04995, then origin/dev merged (bf0a7fd40, clean).

Cross-worker staleness — fixed as proposed. read_cached now treats Redis as the one authority whenever it answers: a hit is returned; a miss returns None and evicts this worker's _local copy (a corrupt row is a miss too, never a fall-through); _local is read only when there is no client or the read raised. store still writes both so the outage fallback stays warm. Comment/docstring say why.

The Redis-present branch now executes. A dict-backed _FakeRedis shared by two module instances — importlib loads stt_capability_service.py a second time, so worker B has its own _local/_inflight and the same Redis — pins:

  • TTLs reach the wire (ex= 6h decided / 2min unknown) and rows decode via from_json
  • invalidate on A is honoured by B, and B's local copy is evicted, not merely skipped
  • the review's exact 6 h sequence (A re-probes unknown, that row expires) → B misses
  • _local is used only while the read raises; when Redis answers empty again → miss
  • corrupt row → miss, local evicted

Mutation-checked: 4 of the 5 are red against the pre-fix service (the TTL/decode one is pure branch coverage and passes on both). 33/33 in test_2695, 150 across the roster/portal/stt neighbours, 40/40 frontend.

Riders, same push:

  • PROBE_TIMEOUT_SECONDS comment inverted → now states it is deliberately above WAIT_BUDGET_SECONDS and why (reader stops at 4 s, probe runs on to fill the cache).
  • "the Workspace mic is hidden" → "server-side dictation is disabled; the browser's own engine, if any, remains" in the service log + docstring, sttCapability.js hint, backend.md, and the PR body (two lines).
  • backend.md: stt_capability_service.py has its own catalog entry; the tts_service.py line keeps a one-sentence pointer.
  • CodeQL py/weak-sensitive-data-hashing at :103: already dismissed as false positive on 09-11 (alert 356), and the entry above records why an HMAC over SECRET_KEY must not replace it.

#2702 is stacked on this branch — it will need a rebase onto the new head.

…ot a bare sys.modules write (#2695)

Both red checks on this PR were the same two lines.

`_load_worker` builds a second instance of the module to stand in for a second
uvicorn worker. The synthetic name has to be in `sys.modules` while
`exec_module` runs — `@dataclass` resolves the class's module BY NAME during the
module body — and that was done with a bare assignment plus a `finally` pop:

    sys.modules[name] = mod
    try:
        spec.loader.exec_module(mod)
    finally:
        sys.modules.pop(name, None)

`tests/lint_sys_modules.py` exists to stop exactly that, because one leaked
entry is a module every later test in the session imports instead of the real
one. It failed twice over: the `lint (sys.modules pollution check)` job
directly, and `regression diff`, whose sole new failure was the pytest mirror of
the same rule (`test_lint_sys_modules::test_committed_baseline_matches_current_repo_state`).

`monkeypatch.setitem(sys.modules, name, mod)` is the fix the lint names, and it
is available here because the only caller is a fixture. It is also stronger than
the hand-rolled pair: pytest removes the entry at teardown even if `exec_module`
raises before the `finally` is reached.

The entry now lives until teardown instead of being popped immediately. Harmless
and deliberate — the name is unique per fixture instance and nothing after
`exec_module` resolves it.

Not a baseline regeneration: the violations are gone, so the committed baseline
(0 for this file) is satisfied as written.

Verified: `python tests/lint_sys_modules.py` → "no new violations"; the two
affected test files pass under all three CI seeds (12345 / 67890 / 99999), 58
tests each.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VpvcfgWkmQPD7DrDLmATTf
`_row_to_card`'s new `stt_ready` parameter carried `= None`, and an
omitted value resolves to the PRE-FIX presence behaviour
(`stt_ready if stt_ready is not None else True`). The guard that exists
to forbid exactly that — `test_row_to_cards_capability_arguments_have_no_defaults`,
whose own docstring says "a default would let a call site keep compiling
while silently serving the wrong card" — pinned only `is_platform`,
`runtime` and `model_context`, so the fourth capability argument slipped
past it.

Not a live bug: both production call sites (`get_agent_card`,
`get_roster`) pass it explicitly. But a third call site added later
would silently un-fix #2695 with the whole suite green, which is the
regression the guard was written to make impossible.

Drops the default, adds `stt_ready` to the guard's tuple, and passes the
neutral `True` at the four older call sites that relied on it — `True`
reproduces exactly what the bit meant before the capability probe
existed, so no assertion changes meaning.

Also corrects the field docstring in `client_portal/models.py`, which
still defined `stt_available` as "an ElevenLabs key resolves" — the
pre-#2695 gate this PR replaced.

Verified: reintroducing the default fails the guard; reverting the card
gate to presence-only fails 2 tests in the PR's own suite; 2081 related
unit tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@vybe

vybe commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

merge-train: a commit was pushed to this branch (2b966b415) — [validated for the 2026-09-15 train]. Nothing else was touched.

Validation result first

READY — and unusually well covered. Eight backend mutations plus one frontend one, every single hop goes red when reverted:

Mutation Result
card gate → bool(tts_ready) (the pre-fix presence gate) 2 failed
_stt_ready ignores the verdict 2 failed
read_cached falls back to _local on a Redis miss 4 failed
classify_response stops treating 401/403 as refusal 11 failed
record_live_refusal → no-op 1 failed
settings route drops the capability fields 2 failed
remove the wait_for bound 1 failed
/stt endpoint gate → presence only 1 failed
FE describeSttCapability unknown → "capable" 2 failed

The CRITICAL that ejected this from the 2026-09-14 train is genuinely closed — restoring the old Redis-miss fall-through turns 4 tests red, proven with a dict-backed fake shared across two module instances. And the mic gate correctly runs through the portal roster payload rather than GET /api/settings/feature-flags, so it avoids the #2128 class where a gate is dead for exactly the audience it targets.

What was pushed, and why

_row_to_card's new stt_ready parameter carried = None, and an omitted value resolves to the pre-fix presence behaviour (stt_ready if stt_ready is not None else True). The guard that exists to forbid precisely that — test_row_to_cards_capability_arguments_have_no_defaults, whose own docstring says "a default would let a call site keep compiling while silently serving the wrong card" — pinned only is_platform, runtime and model_context, so the fourth capability argument slipped past it.

Not a live bug: both production call sites pass it explicitly. But a third call site added later would silently un-fix #2695 with the suite green — the exact regression the guard was written to make impossible. This was the one finding across the whole batch that could quietly revert its own issue.

The commit drops the default, adds stt_ready to the guard's tuple, and passes the neutral True at the four older call sites that relied on it. True reproduces exactly what the bit meant before the probe existed, so no assertion changes meaning. Also corrects client_portal/models.py's field docstring, which still defined stt_available as "an ElevenLabs key resolves" — the pre-#2695 gate this PR replaced.

Verified: reintroducing the default fails the guard; reverting the card gate to presence-only fails 2 tests in your own suite; 2081 related unit tests pass.

Two follow-ups for you (neither blocks the merge)

  1. can_manage_canvases: bool = False has the same gap and is not in the guard either. Pre-existing (ent#553, not this PR), so I left it alone — but it is the same one-line fix and the same failure mode if a call site forgets it.
  2. A 4s provider await is now on the roster's critical path. get_roster:933 / get_agent_card:861 can wait up to WAIT_BUDGET_SECONDS = 4.0 on an outbound ElevenLabs call on a cache miss. perf(workspace): the roster's latency floor is its slowest agent — defer briefing hydration off the critical path #2163 exists to remove a ~5s Workspace first-paint floor, and this adds one of the same order. Mitigated (Redis-shared, 6h/2min TTLs, single-flighted), but the timeout path deliberately does not store, so during a slow-provider window every roster load in the first 8s pays up to 4s. Worth knowing: test_2163_roster_latency_floor.py structurally cannot catch this — its fixture has no ElevenLabs key, so _stt_ready short-circuits on tts_ready=False and never probes. If the latency matters, the zero-cost shape is a cache-only roster read (miss → fire-and-forget probe, return unknown), keeping the bounded wait for the admin Settings read where an operator is explicitly asking.

Minor, not pushed: stt_checked_at has no frontend consumer (reads as intentional API-level diagnostics), and the ElevenLabs key is resolved twice per roster load — two uncached DB reads + two AES-GCM decrypts where ensure_capability(api_key=...) already accepts the key.

@dolho

dolho commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

/review — head 2b966b41 vs merge-base eb41896f5

Files: 13 (+999/−15) · Scope: CLEAN — the diff is #2695's capability probe, its cache, the three gate sites (_row_to_card, transcribe_portal_audio, the Settings panel) and their tests; nothing outside the issue.
Plan completion: the 2026-09-14 finding (cross-worker cache staleness) is DONE — read_cached now treats a Redis miss as a miss and evicts _local (stt_capability_service.py:131-150), pinned by test_a_redis_miss_is_a_miss_even_when_a_local_copy_exists / test_invalidate_on_one_worker_is_honoured_by_the_other over a two-worker fake Redis. The 13:34 train note already validated this head; this pass is a second read, not a re-run.

Critical

None.

Informational

[I1] A 401/403 that is not a permission verdict is still a 6-hour refused (Confidence 6/10)
stt_capability_service.py:171-183 — classify_response maps any 401/403 to VERDICT_REFUSED, falling back to detail="http_403" when the body carries no provider detail. The module's own rule is "only a definitive provider refusal hides it", and a 403 from an edge/WAF challenge (HTML body, no detail) or a key that was just rotated at the provider is not that verdict — yet it hides the mic on every worker for TTL_DECIDED_SECONDS (6 h), and record_live_refusal (service.py:1597) feeds the same path from a live /stt call. Recovery exists (re-save the key → invalidate) but is only discoverable via the Settings badge.
Suggestion: treat 401/403 as refused only when the body parses to a provider status word (missing_permissions, invalid_api_key, …); an unparseable 401/403 → unknown with detail="http_403", so it re-asks in 2 min instead of sitting refused for 6 h. One branch in classify_response, one parametrized case in test_provider_answers_partition_into_verdicts.

[I2] Settings PUT now blocks on the probe (Confidence 5/10)
routers/settings.py:3109 — update_elevenlabs_settings invalidates and then awaits ensure_capability(), so a save waits up to WAIT_BUDGET_SECONDS (4 s) for the provider before returning. Intentional (the admin gets the verdict on the same response) and bounded — noting it because it is the only write path in the file with an outbound HTTP wait.

Clean

  • Auth: no new route; GET/PUT /elevenlabs keep assert_admin; the portal gate is unchanged in shape (agent_on_roster still first).
  • Credential exposure: the key reaches only the xi-api-key header of a fixed HTTPS URL; the cache key is sha256(key)[:16]; describe() and the log lines emit verdict/status word only. stt_detail is bounded [:120] and rendered as text.
  • Concurrency: _inflight single-flights per key per process with a strong ref + done-callback; wait_for(shield(task)) keeps the probe alive past the reader's budget. Redis is the cross-worker authority.
  • Fail direction: allowed = verdict != refused — unknown/unconfigured/transport error all render the mic; the probe never raises.
  • Tests execute the changed path: test_roster_threads_the_capability_into_every_card and test_endpoint_refuses_when_the_key_cannot_transcribe cross the service boundary; the two-worker fake-Redis suite covers the staleness AC. Frontend rule is pure (sttCapability.js) with its own spec; the ent#403 no-defaults guard now includes stt_ready.
  • Docs: architecture/backend.md + learnings.md updated in-diff.

Verdict: READY — I1 is a tightening, not a blocker.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge-train: validated on #2820 (batch of 6, full suite green). Lane B — /validate-pr + /review; coverage mutation-proven at all 8 backend hops plus the frontend helper. The 2026-09-14 train's CRITICAL is confirmed closed (restoring the Redis-miss fall-through turns 4 tests red). Mic gate correctly runs through the portal roster payload, not the get_current_user-gated feature-flags endpoint, so it avoids the #2128 class. One mechanical commit pushed to this branch (2b966b4) — the no-defaults guard now covers stt_ready; details in the comment above.

@vybe
vybe merged commit 09388a4 into dev Sep 15, 2026
28 checks passed
dolho added a commit that referenced this pull request Sep 16, 2026
… provider-error branch

Re-applied after rebasing onto dev: #2699 squash-merged with its own final
wording of this bullet, so the branch's copy of the paragraph conflicted
and dev's was taken; this is #2696's one addition to it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VpvcfgWkmQPD7DrDLmATTf
vybe pushed a commit that referenced this pull request Sep 16, 2026
…ue 422 (#2696) (#2702)

* fix(workspace): the /stt provider error says why, instead of one opaque 422 (#2696)

`transcribe_portal_audio` mapped every non-200 from ElevenLabs onto
`422 "Could not transcribe the audio"`. A missing endpoint permission, a
rejected key, exhausted credits, a provider rate limit and a rejected audio
container all read identically, while the actionable status word sat in a
backend WARNING one line above — a live instance cost an operator with
container access a full round-trip to answer a question the system already
knew.

`stt_capability_service.classify_stt_failure()` (pure) maps a provider answer
onto a named category with its own client status and sentence:

  permission / auth / quota   401·402·403 by status word  → 503, operator-actionable
  rate_limit                  429                          → 429, the existing retry wording
  audio                       400·413·415·422              → 422, "the recording could not be read"
  provider                    5xx                          → 502, the existing transport wording
  unknown                     anything else                → 502, still says who failed

No arm returns the old string; a test sweeps every status 300-599 to pin that,
so an unrecognised provider answer cannot regress to it. The client sentence
never carries the provider body. `record_live_failure` keeps the status word +
category for THIS key (`stt:last_failure:<digest>`, 24h; per-process fallback)
and still feeds #2695's capability cache on a 401/403, so the mic hides on the
next load. `GET /api/settings/elevenlabs` (admin-only) carries it as
`stt_last_failure`, and Settings -> Voice renders "Last voice-input failure:
<why> (HTTP <status> <word>) — <time>" under the capability badge.

Fail-soft is unchanged: every branch raises ClientPortalError, never a 500,
and the client can always type instead.

Fixes #2696

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* fix(stt): a quota word in the provider's prose is not a quota verdict (#2696)

Review finding, reproduced by driving the classifier: a 401 whose body carries
no status token was classified `quota` whenever its SENTENCE happened to contain
one of `_QUOTA_WORDS`.

    401 {"detail":"Invalid API key for your plan"}                 -> quota
    401 {"detail":{"message":"…not valid for this subscription"}}  -> quota

Both are ordinary auth failures. The client was told "the account is out of
credits or not on a plan that allows it" and the admin panel said the same, so
an operator whose key simply needed replacing was sent to a billing page. That
is worse than the opaque 422 this issue replaces — it is confidently wrong in a
direction someone acts on.

The cause is that `provider_status_word` collapsed two different things:
`det["status"]`/`det["code"]`, which are machine tokens the provider documents,
and `det["message"]`/a bare string detail, which is prose written for a human.
The comment above `_QUOTA_WORDS` already claimed matching happened on "the
status token"; the code matched whatever came back.

`provider_status_parts(body) -> (token, prose)` keeps them apart, and
`classify_stt_failure` matches ONLY the token. A 401/403 carrying prose alone is
now `auth` — the honest reading of "the key was rejected and the provider did not
say why". `provider_status_word` stays as the operator-facing display value
(token else prose), so nothing is lost from the panel: the prose still shows,
it just no longer votes.

Verified in the backend image: 38 passing in this suite (5 new table rows + 3
new tests), 66 with #2695's alongside it, and the portal/settings sweep has the
identical non-passing set on this branch and on its base — no new failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

* docs(architecture): the stt_capability_service bullet carries the #2696 provider-error branch

Re-applied after rebasing onto dev: #2699 squash-merged with its own final
wording of this bullet, so the branch's copy of the paragraph conflicted
and dev's was taken; this is #2696's one addition to it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VpvcfgWkmQPD7DrDLmATTf

* fix(stt): the last-failure row obeys the verdict's cross-worker rule, and invalidate forgets it (#2696)

The /review on #2702 (I1): `read_last_failure` fell through to this worker's
local copy on a Redis MISS — the pre-#2695-fix shape of `read_cached`, which
that PR was held for. After the rebase the two readers in one module
disagreed about what a miss means; now they share the rule (Redis answers
⇒ authoritative, miss evicts the local copy; local only when Redis cannot
be asked). `invalidate` also drops the key's last-failure row, so re-saving
a fixed key does not show the operator the pre-fix failure for 24h beside a
fresh `capable` verdict. Mutation: restoring the fallthrough turns the new
two-worker test red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VpvcfgWkmQPD7DrDLmATTf

* merge-train: the operator-facing stt detail is scrubbed of the key (#2702) — mechanical, per the merge-train note on the PR

`record_live_failure` stores the provider's status word / prose as the
operator `detail` for 24h and the Settings panel renders it. The client
half is a constant, so this row is the only place a provider body reaches
any surface; the panel promises the key is never echoed, so enforce it here
with `scrub_secret` instead of assuming it of the provider. One test drives
a body carrying the key and asserts neither the returned failure nor the
stored row contains it (mutation: scrub removed → red).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VpvcfgWkmQPD7DrDLmATTf

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ui PR touches the frontend UI — triggers Playwright e2e tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants