Skip to content

feat(workspace): voice as a conversation, not two controls (ent#440) - #2379

Merged
dolho merged 10 commits into
devfrom
feature/ent440-workspace-voice-conversation
Aug 27, 2026
Merged

dolho merged 10 commits into
devfrom
feature/ent440-workspace-voice-conversation

Conversation

@dolho

@dolho dolho commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

What

The Workspace already had both halves of a voice conversation and neither of them was one: hold-to-dictate (#2212) and a speaker toggle (#2157) — two manual controls the client drove turn by turn. One control now closes the loop: the mic listens, the utterance becomes an ordinary Workspace turn, the reply is spoken, the mic reopens. No mode switch, no second surface.

The one decision: what a voice turn IS

A spoken utterance is submitted through the same path a typed one takes — submitUserText → deliver → POST .../chat/stream:

mic ──► /stt ──► submitUserText(text) ──► deliver() ──► POST .../chat/stream
                                                              │
                        the same portal session ◄─────────────┤
                        the same resumed Claude session       │
                        the same enterprise_portal_messages   │
                                                              ▼
                              reply text ──► spokenReply() ──► /tts ──► speaker

Every acceptance criterion follows from that line rather than from machinery built to satisfy it:

AC Why it holds
Start from the Workspace, no mode switch One header control on the conversation that is already open
Shares context with the text conversation It is the text conversation — same thread, same cached_claude_session_id
Voice turns appear in history like text turns The row is the same row; nothing marks it as spoken
Canvas + deliverables reachable during a session The loop is inline in the composer, never modal
Interruption works Sustained speech over a narrating agent stops playback and reopens the mic; explicit Stop ends the loop
Degrades with a named reason, never a dead control See the table below — the composer keeps working in every row
Permissions and exposure match the text surface No new route, so no new gate: /stt, /tts, /chat/stream are already roster-scoped and rate-limited per (client, agent)

Why not the platform's Gemini Live session

routers/voice.py (VOICE-001) already runs a real-time voice session, and porting it in was the obvious-looking move. Rejected, because the reason is the premise:

  • A different model answers. It holds a summarised copy of the thread as a system prompt and writes its transcript back when the session ends — a parallel conversation wearing the same page.
  • A summary is not the session. The agent's tool memory and mid-skill state live in the resumed Claude session, so a bypassing voice session cannot use the agent's tools, files or canvas — "reachable during a session" would need rebuilding on the other side.
  • It cannot authenticate here. Its WebSocket takes a platform JWT and resolves a users row; a Workspace client holds a portal session token and has no users row at all.

The issue asks to consolidate rather than replace the existing voice work: this uses the platform's own STT/TTS layers (shared with channels since ent#117) and lets the agent answer as itself.

Where the rules live

src/frontend/src/components/portal/voiceConversation.js — pure, no Vue, no DOM. vitest.config.js is environment: 'node' with no component-mount harness, so a rule expressed inside a .vue file is a rule no test can execute. The component is a dispatcher over the machine.

        start                utterance          transcript         reply
 off ──────────► listening ────────────► transcribing ──────► thinking ──────► speaking
                    ▲  ▲                      │                                   │
        silence ────┘  │  transcript-empty ───┘                    narration-ended │
                       └───────────────────────────────────────────────────────────┘
                       ▲                                    barge-in (stop narration + capture)
   stop / error  ──►  off   (always: release the microphone)

Properties pinned by tests, each because the obvious implementation gets it wrong:

  • start is idempotent — a second press while live must not open a second recorder on one device.
  • Every event is inert in off — a /stt answer or an onstop callback arriving after teardown must not restart a loop the user ended.
  • transcript sends from exactly one state — a slow transcription answering after the state moved on cannot dispatch the same words twice.
  • Every exit releases — stop/error from any state emit release, plus stop-capture / stop-narration for the state they left.
  • silence is accepted from transcribing, not just listening — it is raised after the recorder has stopped, so the narrower edge (which is what I wrote first) wedged the loop with the mic open and nothing to advance it. There is now a test asserting every live state has at least one advancing edge.

Utterance boundaries and the interrupt

No recognition — a level meter. An AnalyserNode on the shared mic stream sampled every 100 ms, reduced to RMS, turned into continue / end / idle:

  • end — speech heard, then 1.2 s of pause (or the 30 s cap). Transcribe and send.
  • idle — 15 s open having heard nothing: the conversation ends with a sentence. A hot mic left open on a client's own device is the failure mode this must not ship.
  • Room tone re-opens the mic instead of spending a transcription.

Interruption reads the same meter while the agent speaks. Two details are load-bearing rather than tuning: the interrupt threshold is higher than the listening threshold and capture requests echoCancellation — without both, the mic hears the agent's own narration through the speakers and the agent interrupts itself on every reply; and the 350 ms hold means a cough does not cut it off.

What gets spoken

spokenReply() cleans a reply for the ear before synthesis: code fences become one spoken sentence, links read as their text and never their URL, markdown furniture is dropped, long replies are cut at a sentence boundary with "The rest is in the chat." Reading a fenced diff aloud is unlistenable and burns the TTS character cap. The rendered message is untouched.

Degradation (never a dead control)

Condition What happens
No microphone / insecure origin Control does not render; a click through a stale capability answers with the microphone reason
Platform has no STT provider Control does not render (the mic button's own rule)
Agent has no configured voice The loop runs; replies arrive as text and the status line says so
Transcription fails / provider outage Loop stops with /stt's own user-facing message in the existing voice-error line
Synthesis fails mid-conversation Named, and the loop advances to listening rather than hanging on audio that never plays
Turn fails Renders on its own message bubble with a retry; the loop stops rather than talking over an error

Scope

No backend change, no new endpoint, no migration. Frontend only.

OSS-core by decision (ent#440): deliberately ungated — no requires_entitlement, logic stays in the OSS tree. Recorded explicitly in the docs because CLAUDE.md's default for an enterprise-tracker feature is gated unless ruled otherwise, so the ruling must never be inferred later from the mere fact that it merged (the ent#326 / ent#384 / ent#392 discipline). The Workspace is already OSS-core (ent#356) and this consumes only surfaces that shipped there.

Testing

  • src/frontend/tests/unit/portalVoiceConversation.spec.js — availability ladder, the full transition table (incl. the wedge regression and the "no live state without an advancing edge" property), utterance/barge-in thresholds, the spoken-text rewrite, plus source assertions scoped to what only source can answer: dispatch goes through the machine (one state writer), a spoken turn uses the same submit path, no double narration, echo cancellation requested, mic released on unmount.
  • npm run check:tokens passes; raw-color scan shows 0 non-gray / 0 hardcoded for the touched file; the SFC compiles.
  • Not run locally: vitest and vite build — this clone's node_modules is root-owned and incomplete (mermaid missing, npm install fails EACCES), which is pre-existing and unrelated. Every pure assertion in the spec was executed locally against the module through a plain-node harness and passes; CI runs the real suite.

Known limits (stated, not hidden)

  • The ~350 ms of speech that establishes a barge-in is not captured (the recorder starts once the interrupt is confirmed), so an interruption's first word can be lost.
  • Utterance boundaries are energy-based, so a very noisy room ends turns early. Recognition-based endpointing needs a streaming STT surface Trinity does not have.
  • Narration is per-reply, not streamed: a long answer is spoken once the turn completes (the ent#286 live activity trail still renders throughout).
  • Rooms (PortalRoom.vue) are out of scope — turn-taking with several agents is a different problem.

Docs

  • docs/memory/requirements/public-access.md §48.3 (FR-1…FR-9 + limits)
  • docs/memory/feature-flows/workspace-voice-conversation.md (+ index row and changelog entry)
  • docs/memory/architecture.md — Workspace section

Related to Abilityai/trinity-enterprise#440

🤖 Generated with Claude Code

@dolho
dolho requested a review from obasilakis August 24, 2026 09:17

@obasilakis obasilakis 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.

Reviewed against /validate-pr + a read of the state machine and the dispatcher. The pure module is genuinely good — the transition table, the off-inertness rule, the voiceStarting/voiceStartToken pair covering both re-entrancy shapes, and dispatch-before-stopUtterance() in monitorTick are all correct and correctly reasoned. Docs, requirements, feature flow and the OSS-core ruling are all in place.

One blocking item.

Narration can start after the loop has already left SPEAKING

narrateReply() awaits speak(spoken), and speak() sets speaking.value = true, awaits store.synthesizeTts(...) (a real 1–3 s round trip), then unconditionally does audioEl.value.src = url; await audioEl.value.play().

During that await voiceState is already SPEAKING, so monitorTick is evaluating barge-in at a 350 ms hold. Two reachable outcomes:

  • Barge-in during synthesis — the machine goes SPEAKING → LISTENING, ACT_STOP_NARRATION pauses an element that has no new src yet, the mic reopens, and then the pending speak() assigns src and plays. The agent narrates over the user's fresh utterance.
  • Explicit Stop during synthesis — state OFF, hardware released, and then the audio plays anyway. That contradicts the PR's own AC row: "explicit Stop ends the loop".

narrateReply's trailing if (!speaking.value && voiceState.value === VOICE_SPEAKING) guard only suppresses the dispatch, not the playback — the audio element is already committed by then.

Suggested fix, mirroring the shape you already use for startup: a generation token checked inside speak() after the await, before src = url. voiceStartToken is the precedent and releaseVoiceHardware() already bumps it, so this may be as small as reading it in narrateReply and re-checking after await speak(...) — though it needs to be inside speak, since that is where the commit happens.

Worth noting where this sits: the module is well covered, and this defect lives in the dispatcher — the layer the "rules live in a pure module because vitest has no mount harness" split deliberately leaves untested. Not an argument against the split, just where the remaining risk concentrates.

Non-blocking

  • releaseVoiceHardware() does not call stopSpeaking(). Safe today only because the machine emits ACT_STOP_NARRATION on the SPEAKING exit; combined with the above it is the second half of the same hole. Cheap belt.
  • No stall guard in THINKING — utteranceVerdict's idle timeout is only consulted in LISTENING, so a turn that never resolves leaves the mic stream live with no status change. Bounded in practice by deliver's wait budget; worth a line under Known limits if you'd rather not fix it.
  • stopVoiceConversation({ reason: VOICE_IDLE_STOP_REASON }) writes the graceful idle end into voiceError, so a normal end renders in the error line with a Dismiss button. voiceNotice is the natural channel but releaseVoiceHardware clears it — noting it rather than asking for a change.
  • spokenReply's /(\*\*|__|\*|_|~~)/g strips underscores anywhere, so snake_case identifiers are spoken concatenated. Cosmetic.

Process

The body says "Related to Abilityai/trinity-enterprise#440" rather than Fixes. Cross-tracker never auto-promotes either way, so this is only about making the intent explicit — but ent#440 will need a manual status-in-dev bump at merge regardless.

@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.

@dolho
dolho force-pushed the feature/ent440-workspace-voice-conversation branch from 6c95991 to a62a083 Compare August 25, 2026 10:38
@dolho

dolho commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Code review — re-review at a62a083

Re-reviewed after the narration-token fix. The generation guard is correct and closes the reported hole: speak() takes a token at entry and re-checks it after the synthesizeTts await before assigning src, stopSpeaking() bumps it, and releaseVoiceHardware() now tears narration down itself instead of relying on the machine emitting ACT_STOP_NARRATION on the SPEAKING exit. Barge-in and explicit Stop can no longer be overtaken by a synthesis that was already in flight.

Five findings remain, all in the dispatcher — the layer the "rules live in a pure module because vitest has no mount harness" split deliberately leaves untested. That is not an argument against the split; it is where the residual risk keeps landing.

Medium

1. PortalConversation.vue:1536 — transcribing has no timeout, so the loop can wedge with the mic hot indefinitely.

stopUtterance() is a no-op when convRec.state === 'inactive', so onstop never fires and finishUtterance never runs. Reachable two ways: the mic device is unplugged or permission is revoked mid-conversation, so the recorder auto-stops while the machine is still listening (finishUtterance returns immediately because the state isn't transcribing), then the next monitorTick sees sawSpeech still true and msSinceSpeech >= 1200 → voiceDispatch('utterance') → transcribing → stopUtterance() no-ops → nothing can advance the machine. store.transcribeStt also has no axios timeout, so a hung /stt arrives at the same state.

In both cases convStream's tracks stay live — browser mic indicator on — forever. The 15 s NO_SPEECH_TIMEOUT_MS guard covers listening only, and this PR's own stated invariant is that "a hot mic left open on a client's own device is the failure mode this must not ship". The status line stays at "Got it…" with Stop as the only recovery.

2. PortalConversation.vue:1565 — the voice path dispatches a turn without send()'s sending guard, so two deliver() calls can run concurrently.

send() opens with if (!text || sending.value) return; runVoiceTurn → submitUserText has no such check. While the loop is listening the textarea and Send button are both enabled, so a user who types and sends, then speaks, puts the utterance into a second concurrent deliver().

They share elapsedTimer (the second clearIntervals the first; whichever finishes first clears it for both), sending (the first terminal re-enables Send while the other turn is still running), attachments (cleared by whichever succeeds first), and awaitPersistedReply's baseline assistant count — so the second turn's poll sees the first turn's reply cross the baseline and returns the wrong answer. lastAssistantReply is a single shared ref written by both, so runVoiceTurn can also narrate the typed turn's reply.

Low

3. PortalConversation.vue:1475 — failVoice has no generation guard, so a stale turn's failure tears down a freshly restarted conversation.

failVoice dispatches 'error' unconditionally, and nextVoiceState handles stop/error before the state === VOICE_OFF short-circuit, so it always returns OFF + ACT_RELEASE. Scenario: the user speaks, the agent is slow, the user presses Stop (off), then presses the voice button again (listening, new stream + timer). The abandoned turn's submitUserText finally resolves res.ok === false → failVoice(...) → the new conversation is released, with an error about a turn the user already abandoned.

Same shape at finishUtterance's catch (:1560 — the success arm re-checks voiceState !== VOICE_TRANSCRIBING, the catch does not) and at convRec.onerror (:1530), where an orphaned recorder's error kills the current loop. The success paths already use a state re-check as the guard; the failure paths need the same, or the start-generation token speak/startVoiceConversation already carry.

4. PortalConversation.vue:932 — Stop mid-turn can still get the raw markdown reply spoken, via the #2157 branch.

if (voiceMode.value && ttsEnabled.value && data.response && !voiceConvLive.value) speak(data.response) is evaluated after the turn's await. If the client had the speaker toggle persisted on (voiceMode is read from localStorage) and presses Stop while the agent is thinking, voiceConvLive is already false by the time this line runs — so the un-cleaned reply (code fences, URLs, markdown) is synthesized and played. It contradicts "explicit Stop ends the loop", and the user could not have muted it: the speaker button is hidden (v-if="ttsEnabled && !voiceConvLive") for the whole duration of the conversation.

5. voiceConversation.js:157 / PortalConversation.vue:1521 — the machine permits ACT_CAPTURE from listening, which would install a second recorder over a live one (latent).

The silence edge accepts VOICE_LISTENING and emits [ACT_CAPTURE] with no paired ACT_STOP_CAPTURE, and startUtterance() overwrites convRec without stopping whatever is already recording. Unreachable today — the only raiser (finishUtterance) is gated on transcribing — but the machine explicitly permits it and the spec pins it (nextVoiceState(VOICE_LISTENING, 'silence')), so a future raiser wired from listening orphans a live MediaRecorder whose ondataavailable then pushes into the new utterance's convChunks, mixing two clips into one transcription. Cheap fix: have startUtterance stop/discard first, or drop the unreachable LISTENING arm from the silence edge.

Confirmed fixed

The blocking item from the previous review: narration can no longer commit playback into a loop that left SPEAKING during synthesis, in either direction (barge-in or explicit Stop), and the catch arm is gated on the same token so a superseded synthesis cannot overwrite voiceError for a conversation that already ended.

🤖 Generated with Claude Code

@obasilakis obasilakis 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.

Re-reviewed at a62a0837. The branch was rebased since the last review, so I diffed the reviewed tip (6c95991e, now unreferenced but still fetchable) against its rebased equivalent (73a3c0ed) to confirm the rebase carried no content changes to this PR's own files, and then read 73a3c0ed..a62a0837 as the only new code. I also re-read voiceConversation.js and the voice half of PortalConversation.vue in full rather than reading the fix in isolation, and checked the capability wiring, the mic lifecycle, the portal STT/TTS rate limits, and the raw-color scan against dev.

Earlier findings

Narration can start after the loop has already left SPEAKING — fixed. a62a0837 puts a narrationToken generation check inside speak(), immediately after the synthesizeTts await and before src is assigned, which is where the commit actually happens. I traced the four cases: barge-in mid-synthesis now discards and revokes the URL and leaves narrateReply's trailing guard correctly inert because the state is LISTENING, not SPEAKING; explicit Stop mid-synthesis reaches the same discard with the state at OFF; a normal success is unaffected; and a rejected play() still advances the loop through the catch. The ordering detail matters and is right — the token check sits above the !url arm, so a superseded failed synthesis cannot write TTS_FAILED_MESSAGE into voiceError for a conversation that already ended. speaking.value is also never left stale-true, because every path that bumps the token either clears it (stopSpeaking) or is a fresh speak() that sets it.

releaseVoiceHardware() does not call stopSpeaking() — fixed. It now tears narration down itself rather than depending on the machine happening to emit ACT_STOP_NARRATION on the SPEAKING exit.

No stall guard in THINKING — not addressed and not documented. Restating it with a sharper edge than I gave it last time. utteranceVerdict's idle timeout is consulted only in the LISTENING branch of monitorTick, and the shared convStream is held for the whole conversation by design, so during THINKING the microphone stream stays open with the browser's recording indicator lit and no path that can end it. The bound is deliver's wait budget, which #2214 made the agent's own execution_timeout_seconds (clamped at 7200s). A hot microphone on a client's own device is the exact failure mode NO_SPEECH_TIMEOUT_MS exists to prevent, and the 15s rule does not reach this state. I am not asking for a fix, but it belongs under Known limits in workspace-voice-conversation.md alongside the four that are already there.

Idle stop writes into the error line; spokenReply strips underscores anywhere. Both unchanged. Both were raised as observations rather than requests and I am not re-raising them.

New finding

Blocking — a voice turn can enter deliver() while another turn is already in flight

send() guards on sending.value and retry() and reattach() both guard on it too, but deliver() itself does not, and runVoiceTurn → submitUserText → deliver is a new caller that inherits no guard. The loop has no notion of "a turn is already running": ACT_SEND fires purely on transcript arriving in TRANSCRIBING.

Two reachable orderings, both without contrived user behaviour:

  • Open a thread whose turn is still running. loadThread calls reattach (line 452), which holds sending for the duration of that turn. Start a voice conversation and speak. The transcript dispatches ACT_SEND and enters deliver alongside the reattached turn.
  • Type and send while the loop is LISTENING. send() succeeds because the loop is not itself sending; the mic is still open, and the next utterance dispatches concurrently.

The consequences are all from shared single-slot state in deliver:

  • elapsedTimer is one module-level handle — the second call clears and reassigns it, resetting the first turn's counter.
  • sending is one flag — whichever call reaches its finally first clears it, so the pending-turn indicator disappears while a turn is still running.
  • currentSessionId is read at dispatch. On a brand-new chat both calls carry null, the server mints two portal sessions, and session-adopted is emitted twice with different ids. What the client experienced as one conversation lands in two threads — which is the "second conversation wearing the same thread" the design memo at the top of voiceConversation.js says this feature exists not to be.
  • lastAssistantReply is last-writer-wins, so voiceDispatch('reply', lastAssistantReply.value) can narrate the other turn's reply.
  • streaming and liveActivity are shared, so the ent#286 activity trail interleaves two turns.

This is a narrower window than the last blocker and nothing is double-billed for the same message — the two turns are genuinely different messages. I am still holding on it because the thread fork is user-visible breakage on a client-facing surface, and because runVoiceTurn is the single unguarded entry point, so the fix is small.

On shape: putting a bare if (sending.value) return in runVoiceTurn would drop the utterance silently, which is the one outcome to avoid — the user spoke and nothing happened. The loop needs to do something it can say: re-listen, or stop with words the way failVoice does. Alternatively the guard lives in submitUserText so both callers inherit it and runVoiceTurn reads the refusal off the returned outcome. Author's call, but it has to live in the dispatcher — the machine has no in-flight state to hang it on, and this is the same untested layer the previous blocker was in.

Non-blocking — a thread switch on the same agent does not stop the loop

The watcher at line 1204 stops a live conversation when props.agent.name changes, with the right reasoning: a conversation belongs to the agent it was started with. The separate watcher at line 538 fires on [props.agent.name, props.sessionId] and calls loadThread, which replaces messages.value — but it does not touch the loop. So switching threads on the same agent while the loop is in THINKING or SPEAKING leaves the agent narrating thread A's reply over thread B, with that reply no longer rendered anywhere on screen. Sending the next utterance into thread B is arguably what the user meant, so I am not claiming the loop should stop outright; the in-flight turn straddling the switch is the part that reads wrong. Worth either handling or naming under Known limits, since the analogous case one level up is handled explicitly.

What I checked and found correct

  • The two capability bits are not collapsed. voiceConversationMode requires stt_available for available and reads voice_available only into narrates. A key-but-no-effective-voice agent therefore gets a running loop with VOICE_TEXT_REPLIES_NOTICE rather than a dead speaker, and the standalone speaker toggle stays gated on ttsEnabled so it does not render for that agent at all. Dictation is not hidden either: the mic button keeps its own resolveMicMode ladder, so an instance with no stt_available but a browser SpeechRecognition still renders it in speech mode while the conversation control correctly does not render.
  • No second capability channel. Both bits come off props.agent, i.e. the roster payload. There is no feature-flags or entitlement read anywhere in the new code, which is the constraint #2128 established for this surface.
  • Fail direction is closed. The control renders only on conversationMode.available, and startVoiceConversation re-reads conversationMode at click with a named reason, because the roster can refresh between render and press.
  • Rate limiting. portal_stt and portal_tts both call rate_limiter.enforce(..., 20, 60) keyed on (email, agent_name), and transcriptionErrorMessage has a dedicated 429 string, so a throttled loop stops with words rather than spinning.
  • Mic lifecycle. onBeforeUnmount → cleanupVoice → releaseVoiceHardware stops the tracks, clears the 100ms timer, stops the recorder and closes the AudioContext. The startup token/flag pair from 003c8bf8 covers both the overlapping-press and the released-while-awaiting shapes, and a superseded start stops the tracks it just acquired rather than trusting a teardown that already ran. recorderErrorMessage distinguishes NotAllowedError/SecurityError from NotFoundError/OverconstrainedError from NotReadableError, so permission-denied, no-device and device-busy are three different sentences.
  • Design system. Running scan-raw-colors.mjs against the head version of PortalConversation.vue gives 0 raw non-gray and 0 hardcoded, matching dev; the added gray classes sit on the ink ladder the contract prescribes (gray-600/gray-300 for secondary, gray-500/gray-400 for tertiary, never gray-500 as dark meta text). The pulse is motion-safe:-scoped.
  • Accessibility. Loop state is carried by text inside a role="status" aria-live="polite" region, not by the dot colour alone; both the toggle and Stop are real buttons and the toggle carries aria-pressed plus a state-dependent aria-label.
  • Scope. Every AC in ent#440 is met by the "a voice turn is an ordinary turn" decision rather than by parallel machinery, and the rejection of the Gemini Live path is argued on the authentication and session-identity grounds that actually apply here. Rooms are excluded explicitly.

Once the concurrent-deliver path is closed I expect to approve without another round.

dolho and others added 5 commits August 25, 2026 16:03
The Workspace already had both halves of a voice conversation and neither of
them was one: hold-to-dictate (#2212) and a speaker toggle (#2157), two manual
controls the client drove turn by turn. One control now closes the loop — the
mic listens, the utterance becomes an ORDINARY Workspace turn, the reply is
spoken, the mic reopens.

The load-bearing decision is what a voice turn is. It is submitted through the
same path a typed one takes (submitUserText -> deliver -> POST .../chat/stream),
so every acceptance criterion follows from that line rather than from machinery
built to satisfy it: the same portal session and the same resumed Claude session
(shared context), the same enterprise_portal_messages row with nothing marking
it as spoken (history parity), no new route and therefore no new gate
(permission parity), and an inline-not-modal loop so files, reports and the
agent page stay reachable mid-conversation.

Bridging the platform's Gemini Live session (VOICE-001) was rejected, and the
reason is the premise: it answers with a different model holding a summarised
copy of the thread and writes its transcript back afterwards — a parallel
conversation wearing the same page — it cannot reach the agent's own tools or
canvas, and its JWT-only WebSocket cannot authenticate a portal client, which
holds no users row.

Every decidable rule is pure in components/portal/voiceConversation.js, because
this project has no component-mount harness and a rule kept in a .vue file is a
rule no test can execute:

- Transition table. `start` is idempotent (no second recorder on one device);
  every event is inert in `off`, so a /stt answer arriving after teardown cannot
  restart a loop the user ended; `transcript` sends from exactly one state, so a
  slow transcription cannot dispatch the same words twice; every exit releases
  the microphone. `silence` is accepted from TRANSCRIBING as well as LISTENING —
  it is raised after the recorder has already stopped, and a LISTENING-only edge
  wedged the loop with the mic open and nothing to advance it.
- Utterance boundaries from an RMS level meter: 1.2s silence hold, 30s cap, and
  15s with no speech at all ends the conversation WITH A SENTENCE rather than
  leaving a hot mic open on a client's own device. Room tone re-listens instead
  of spending a transcription.
- Interruption at a HIGHER threshold than listening, held for 350ms, with
  echoCancellation requested on capture. Without both, the mic hears the agent's
  narration through the speakers and the agent interrupts itself on every reply.
- spokenReply() cleans a reply for the ear (code fences become one spoken
  sentence, links read as their text, long replies cut at a sentence boundary
  with "the rest is in the chat") while the rendered message is untouched.

Degradation is named at every step and the composer keeps working throughout:
the control renders only where the loop can run, an agent with no configured
voice still converses in text and says so, and each runtime failure stops the
loop with the provider's own user-facing sentence.

OSS-core by decision: deliberately ungated, recorded explicitly because the
default for an enterprise-tracker feature is gated-unless-ruled-otherwise. No
backend change, no new endpoint, no migration.

Related to Abilityai/trinity-enterprise#440

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ophones (ent#440)

Two things, both surfaced after the first commit.

**CI — the #2157 source guards.** `portalVoiceModePersistence.spec.js` pins the
narration gate and the agent-switch watcher as literal source, and ent#440
legitimately changed both: the gate gained `&& !voiceConvLive.value` (a live
conversation narrates through its own state machine, so this branch must not
also speak — it would say every reply twice, once raw and once cleaned for the
ear) and the watcher gained a line ending any live conversation on an agent
switch. The guards are updated to match, deliberately WITHOUT loosening what
they guard: the gate is now asserted term by term rather than as one string, so
it still fails if `voiceMode`/`ttsEnabled`/`data.response` stops gating it, and
the watcher window is widened while still requiring `loadVoiceMode()`.

**Review finding — startup re-entrancy.** The loop is not live until
`getUserMedia` resolves, and a permission prompt can sit open for seconds. In
that window a second press, a press after Stop, or a nav-away would install a
SECOND stream and a second 100 ms timer while the first pair was still owned by
nobody — a microphone left hot with no control pointing at it, which is exactly
the failure mode this feature must not ship. `voiceStarting` rejects the
re-entry; a token invalidates a start whose hardware was released while it was
awaiting (`releaseVoiceHardware` bumps it), and a superseded start stops the
tracks it just acquired rather than trusting a teardown that already ran.

Related to Abilityai/trinity-enterprise#440

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…term source guards (ent#440)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ed on (ent#440)

`speak()` awaits a real 1-3 s `synthesizeTts` round trip and then
unconditionally assigns `src` and plays. The machine is already in SPEAKING
during that await, so `monitorTick` is evaluating barge-in at a 350 ms hold and
Stop is one click away. Two reachable outcomes, both wrong:

- barge-in mid-synthesis: SPEAKING → LISTENING, `ACT_STOP_NARRATION` pauses an
  element that has no new src yet, the mic reopens, and the pending `speak()`
  then plays — the agent narrates over the user's fresh utterance;
- explicit Stop mid-synthesis: state OFF, hardware released, audio plays
  anyway — contradicting "explicit Stop ends the loop".

`narrateReply`'s trailing `!speaking.value && voiceState === SPEAKING` guard
suppresses only the DISPATCH; by the time it runs the element is committed. So
the check belongs where the commit happens.

`narrationToken` is the same shape as `voiceStartToken`: `speak` takes a
generation at entry and re-checks it after the await, before `src` is assigned,
discarding (and revoking) audio it is no longer entitled to play. `stopSpeaking`
bumps it — a pause cannot reach audio that has not been assigned yet — so
barge-in and agent-switch abandon an in-flight synthesis for free. The `catch`
arm is gated on the same token so a superseded synthesis cannot overwrite
`voiceError` for a conversation that already ended.

`releaseVoiceHardware` now tears narration down itself instead of relying on the
machine happening to emit `ACT_STOP_NARRATION` on the SPEAKING exit — the second
half of the same hole: a safety property held by a fact somewhere else.

The defect lives in the dispatcher, the layer the pure-module split deliberately
leaves untested, so it is pinned by source assertion like the rest of that file.

Related to Abilityai/trinity-enterprise#440
…three races the dispatcher lost (ent#440)

Four findings, all in the dispatcher — the layer the pure-module split leaves
untested, which is exactly where the residual risk keeps landing.

**`transcribing` had no ceiling, so the loop could wedge with the mic hot.**
`stopUtterance()` is a no-op on an already-`inactive` recorder, so `onstop`
never fires and `finishUtterance` never runs. Reachable two ways: the mic is
unplugged or permission revoked mid-conversation (the recorder auto-stops while
the machine is still `listening`, then the next tick dispatches `utterance` into
a recorder that cannot stop), and a hung `/stt`, since `transcribeStt` carries
no transport timeout. Either way the tracks stay live — browser mic indicator on
— with Stop as the only way back, which is the one failure this feature says it
must not ship. The 15s no-speech guard covers `listening` only.

A watchdog now bounds it (45s — generous, because firing early costs a real
utterance), re-checks that we are still waiting before acting so it stays a
backstop rather than a competing terminal, and is cleared on every legitimate
exit.

**The voice path dispatched a turn without `send()`'s in-flight guard.** The
textarea stays enabled while the loop is `listening`, so a user who typed and
sent, then spoke, put the utterance into a SECOND concurrent `deliver()`. They
share `elapsedTimer`, `sending`, `attachments` and — worst — `awaitPersistedReply`'s
baseline assistant count, so the second turn's poll sees the first turn's reply
cross the baseline and returns the wrong answer. The spoken turn now yields.

**`failVoice` had no generation guard.** `nextVoiceState` handles `stop`/`error`
BEFORE its `state === VOICE_OFF` short-circuit, so it always returned OFF +
ACT_RELEASE. A user who pressed Stop on a slow turn and then restarted the loop
had the NEW conversation released when the abandoned turn finally rejected —
with an error about a turn they had already abandoned. It takes the same
`voiceStartToken` the success paths already re-check.

**Stop mid-turn could still get the raw reply spoken.** The #2157 branch is
evaluated after the turn's await, so `voiceConvLive` was already false by the
time it ran and the un-cleaned reply (code fences, URLs, markdown) was
synthesized and played — contradicting "explicit Stop ends the loop", and
unmutable, since the speaker button is hidden for the whole duration of a
conversation. A flag set when the hardware is released mid-turn, and cleared at
the next dispatch so it describes exactly one turn.

The fifth finding — the machine permitting `ACT_CAPTURE` from `listening` — is
left as recorded: unreachable today, and the honest fix is to drop that arm from
the transition table, which is a change to the pure module's contract rather
than a dispatcher bug.

Related to Abilityai/trinity-enterprise#440
@dolho
dolho force-pushed the feature/ent440-workspace-voice-conversation branch from a62a083 to 535144b Compare August 25, 2026 13:06
…he literal (ent#440)

`portalVoiceModePersistence.spec.js` asserted the exact source text of the
#2157 branch, so adding the `!voiceLoopEndedDuringTurn` term to close the
speak-after-Stop hole broke it. The assertion now matches the rule — narration
requires client narration on, an agent that can be narrated, and no live voice
loop — plus the new term as its own line, so a future edit to the wording does
not fail the build while a change to the RULE still does.

@obasilakis obasilakis 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.

Re-review at 6ae6d29e

I separated the rebase from the real change first: a62a0837..a401f2dd is pure rebase noise — the PR's own delta is byte-identical across the base move (36877bd5..a62a0837 and 88efbe7d..a401f2dd produce identical added/removed line sets), and ac5124f4/8aa74a61/49ac8983/a401f2dd are renamed-only replays of the round-2 commits. Only 535144b2 and 6ae6d29e are genuinely new. I then re-read voiceConversation.js and the voice half of PortalConversation.vue in full rather than reading the fix in isolation. CI is green except a pending pytest; frontend-build passed, so the new specs run.

Prior findings — verdicts

A. Concurrent deliver() — FIXED, and fixed in the shape I asked for. PortalConversation.vue:1639-1643: runVoiceTurn captures voiceStartToken, then if (sending.value) { failVoice("I couldn't send that — a message was already on its way…", token); return }. The refusal is perceivable rather than a silent drop — failVoice writes voiceError (:1515), which renders in the always-visible danger line (:185-198), and dispatches error, taking the loop to OFF and releasing the mic. deliver() itself is still unguarded, but all four callers now guard (send :1139, retry :1190, reattach :502, runVoiceTurn :1640), and only microtasks separate each check from deliver's sending.value = true (:840), so a setInterval-driven monitorTick cannot interleave. Worth stating the trade you chose: the loop stops rather than re-listening, and restarting it while the abandoned turn is still in flight refuses again immediately.

Round-2 fixes intact. speak()'s generation check sits at :1271, above the !url arm at :1274 — the ordering that keeps a superseded failed synthesis from writing TTS_FAILED_MESSAGE into an ended conversation. releaseVoiceHardware calls stopSpeaking() itself at :1532.

B. No stall guard in THINKING — still open, and now contradicted by the PR's own requirement. The new watchdog bounds TRANSCRIBING, not THINKING: monitorTick's THINKING path is still the bare else { bargeSince = 0 } at :1710. The only bound remains awaitPersistedReply's resolveWaitBudgetMs (:1064), i.e. the agent's execution_timeout_seconds, up to 7200s, with convStream tracks live throughout. It is also not documented: Known limits in workspace-voice-conversation.md:162-173 is unchanged, and public-access.md:857-860 FR-9 enumerates the release triggers as "a stop, an error, an agent switch and unmount" while asserting that "a hot mic left open on a client's own device is the failure mode this feature must not ship". Right now the requirement and the code disagree.

C. Thread switch on the same agent — still open, and worse than I described last round. The [props.agent.name, props.sessionId] watcher (:550-555) calls loadThread and never touches the loop; only the props.agent?.name watcher (:1231-1237) stops it. Beyond the narration problem I raised: deliver's tail pushes into the current messages.value (:940), which loadThread has already replaced (:439), so thread A's reply is rendered into thread B and then narrated, and :954-956 resets currentSessionId back to thread A and re-emits session-adopted. This is pre-existing for typed sends — :958-962 acknowledges the outliving closure — but hands-free dispatch makes it routinely reachable. Not in Known limits either.

D. Observations, unchanged, not re-raised as asks. Idle stop still writes VOICE_IDLE_STOP_REASON into voiceError (:1502), so a graceful end renders in the red danger line with a Dismiss button. spokenReply's /(\*\*|__|\*|_|~~)/g (voiceConversation.js:241) still strips single underscores anywhere, so snake_case is spoken as one word.

Blocking

NEW-1 — the transcribe watchdog is disarmed immediately before the call it claims to bound

armTranscribeWatchdog() has exactly one call site, :1695 in monitorTick, fired just before stopUtterance(). finishUtterance then opens with clearTranscribeWatchdog() at :1606 — and only after that awaits store.transcribeStt(...) at :1620. transcribeStt (stores/clientPortal.js:957-967) rides portalHttp = axios.create() (:61) with no timeout, i.e. axios's timeout: 0.

So the watchdog covers only the recorder-cannot-stop window. The hung-/stt cause — which 535144b2's message names explicitly as one of the two it fixes — is completely unbounded: voiceState stays TRANSCRIBING showing "Got it…", convStream tracks stay live and the browser mic indicator stays on, until the user presses Stop. That is the same hot-mic outcome as B, reached by a different path.

The spec pins the defect rather than the fix — portalVoiceConversation.spec.js asserts /async function finishUtterance\(\) \{\s*clearTranscribeWatchdog\(\)/. Fix shape: move the clear past the await (or re-arm around it), or give transcribeStt a transport timeout.

B and C, restated as one ask

I am not asking for both to be fixed. But FR-9 (public-access.md:857-860) is now a shipped requirement that enumerates the mic-release triggers and declares a hot mic the failure mode this feature must not ship, while THINKING (up to 7200s) and a same-agent thread switch both sit outside that enumeration. Either handle them, or add them to Known limits and amend FR-9's enumeration so the requirement and the code agree. Requirements is the document future readers will trust.

Non-blocking

NEW-2 — one async failure path missed the generation token. convRec.onerror = (e) => failVoice(recorderErrorMessage(e?.error || e)) at :1573 passes no token, so failVoice's new guard (:1514) is skipped. releaseVoiceHardware nulls convRec (:1535) but never clears its handlers, so a late error event from a torn-down recorder tears down a restarted loop with a message about the abandoned one — exactly the class 535144b2 fixed for finishUtterance (:1627) and runVoiceTurn (:1641, :1647). Capture voiceStartToken in startUtterance and pass it.

NEW-3 — voiceLoopEndedDuringTurn is set for turns the loop did not dispatch. releaseVoiceHardware:1523 sets it on any sending.value, so ending the loop while a typed turn is in flight silently suppresses that turn's #2157 narration at :952-953. The user cannot recover it, because the speaker button is v-if="ttsEnabled && !voiceConvLive" (:75) and the loop was live when the turn started. Bounded to exactly one turn (cleared at :839).

NEW-4 — the voice spec greps un-stripped source. portalVoiceConversation.spec.js:51 reads the raw .vue, while its sibling portalVoiceModePersistence.spec.js:25 strips comments with a header stating exactly why: a comment explaining the rule necessarily contains the strings a text scan looks for. Several new guards would pass on a declaration or a comment alone — toContain('armTranscribeWatchdog()') matches the function armTranscribeWatchdog() { declaration even if nothing calls it, which is close to NEW-1's failure mode.

On 6ae6d29e ("pins the rule, not the literal") — partial. It is not a tautology; it does assert a conjunction of four named terms guarding speak(data.response). But it added to the literal rather than replacing it: :58 still contains 'if (voiceMode.value && ttsEnabled.value && data.response', :63's regex still pins the exact order and && spelling of the first three terms, and :64's /!voiceLoopEndedDuringTurn\) speak\(data\.response\)/ is the most literal of the three — it pins !voiceLoopEndedDuringTurn as the last term with an exact closing paren, so adding a fifth term breaks it. "A future edit to the wording does not fail the build" holds only for whitespace between terms.

Design-system ratchet. At head, scan-raw-colors.mjs reports raw_nongray 0 and hardcoded_colors 0, but raw_gray grows 63 → 72 against base 88efbe7d, which is strictly against the "per-file counts may only shrink" rule in CLAUDE.md. It is unchanged from round 2 — the new commits touched <script> only — and the ratchet is measurement-only (scan-raw-colors.mjs:37), so noting rather than asking.

Confirmed still correct

The two capability bits are not collapsed (voiceConversation.js:53-63 — available needs canRecord && secureContext && serverStt, narrates reads voiceAvailable only). No second capability channel: :1415-1422 reads only props.agent.stt_available and voice_available, and the file's only store.* capability read is multiAgentChatAvailable, the unrelated rooms gate. Fail direction closed (v-if="conversationMode.available" at template :60, re-read at click :1456-1460). Portal STT/TTS rate limits intact at client_portal/router.py:721,742. Unmount teardown :584 → cleanupVoice → :1387-1394. Accessibility: role="status" aria-live="polite" on both regions (:188-189, :207-208), real buttons, aria-pressed (:65).

Verdict

Requesting changes, on NEW-1 and on the FR-9 disagreement. Both are small. The blocking finding from round 2 is genuinely closed, in the shape that avoids the silent-drop outcome I flagged, and the round-2 fixes survived the rebase intact.

Process: the body still ends "Related to Abilityai/trinity-enterprise#440" rather than a closing keyword, and ent#440 is open with status-in-progress, so it needs a manual status-in-dev bump at merge either way.

…uth (ent#440)

NEW-1 (blocking) — the watchdog was disarmed on finishUtterance's FIRST line,
so it bounded only the recorder-cannot-stop window, and `transcribeStt` rides an
axios instance created with no `timeout` (i.e. timeout: 0). A hung /stt left
voiceState in TRANSCRIBING showing "Got it…", the mic tracks live and the
browser's recording indicator on, until the user pressed Stop — the same hot mic
FR-9 forbids, reached by the exact cause the watchdog was added for.

Two layers now. The clear moved past the await (and onto both early exits, which
are no longer waiting for a transcript), and /stt got a 60s transport timeout —
comfortably above a real transcription of a 30s-capped utterance. A promise that
can never settle is the wrong primitive to hand a UI regardless of who is
watching it.

The spec assertion that pinned this defect — finishUtterance must OPEN with the
clear — is replaced by a structural one: there must be a clear AFTER the await,
and any clear before it must belong to an early exit.

B and C — taking the 'or' branch, deliberately. Neither is fixed here, so both
are now written where a future reader will look: FR-9's enumeration names them
(THINKING is bounded only by execution_timeout_seconds, up to 7200s, with the
mic live; a thread switch on the SAME agent does not stop the loop, so a
dispatch in flight lands in the thread the user left), and Known limits carries
each with its reasoning. The requirement and the code agree again.

NEW-2 — convRec.onerror now captures and passes the generation token, like the
other two async failure paths. releaseVoiceHardware nulls convRec but never
clears its handlers, so a late error from a torn-down recorder was tearing down
a RESTARTED loop with a message about the abandoned one.

1294 frontend tests passed.

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

dolho commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

Re-review — ent#440 (fresh pass over 88efbe7d..11485c94)

Reviewed the full merge-base diff, not the base tip. Frontend suite run in a clean container:
Test Files 59 passed (59) · Tests 1294 passed (1294). The one red check (pytest (head, seed 99999), cancelled ~25m) is the known infra timeout (#2395) on a frontend-only PR — not treated as a finding.

No browser and no microphone here. Nothing below rests on interactive verification; everything is read from source. What I explicitly cannot confirm is stated at the end.


Verdict on the prior findings

NEW-1 (hot mic on a hung /stt) — FIXED, both layers, verified.
The clear now sits after the await, and the two early exits — the only pre-await clears — are the paths that are genuinely no longer waiting for a transcript:

  if (voiceState.value !== VOICE_TRANSCRIBING) { clearTranscribeWatchdog(); return }
  if (!heard || blob.size < MIN_RECORDING_BYTES) {
    clearTranscribeWatchdog(); voiceDispatch('silence'); return
  }
  try {
    const text = await store.transcribeStt(props.agent.name, blob)
    clearTranscribeWatchdog()

and the transport layer is bounded too ({ headers: this.authHeader, timeout: 60000 }). I also checked the arming side: TRANSCRIBING is entered from exactly one place (nextVoiceState allows utterance only from LISTENING), and that call site arms unconditionally —

      voiceDispatch('utterance')
      armTranscribeWatchdog()
      stopUtterance()

— so there is no route into TRANSCRIBING that skips the watchdog. The spec's ordering assertion is now structural (index of the clear vs. index of the await) rather than "opens with", which was the assertion that pinned the defect. Good fix.

B and C (THINKING unbounded; thread switch on the same agent) — NOT fixed, and now genuinely documented. Claim verified.
I read both files rather than taking the PR description's word for it. requirements/public-access.md FR-9 carries:

Two windows this enumeration does NOT cover, stated so the requirement and the code agree (review, ent#440): (a) while the agent is THINKING the only bound is the agent's own execution_timeout_seconds, up to 7200s, and the mic tracks stay live throughout … (b) switching to a DIFFERENT THREAD on the SAME agent does not stop the loop — only an agent change does …

and feature-flows/workspace-voice-conversation.md Known limits carries the same two as its last two bullets. The requirement and the code now agree on these two. Accepted.

NEW-2 (recorder onerror with no generation token) — FIXED.

  const recorderToken = voiceStartToken
  convRec.onerror = (e) => failVoice(recorderErrorMessage(e?.error || e), recorderToken)

with failVoice(message, token = null) returning early on token !== voiceStartToken. Correct.


New findings

1. MEDIUM — SPEAKING is the one live state with no timer, and it awaits the same untimed axios instance NEW-1 was about. The docs assert the opposite.

portalHttp is still axios.create() with no timeout (i.e. timeout: 0), and synthesizeTts did not get NEW-1's treatment:

        const { data } = await portalHttp.post(
          `/api/enterprise/client-portal/agents/${agentName}/tts`,
          { text },
          { headers: this.authHeader, responseType: 'blob' }
        )

That call is awaited while the machine is already in SPEAKING and the shared mic stream is live (one stream for the whole conversation, released only on ACT_RELEASE):

async function narrateReply(text) {
  const spoken = spokenReply(text)
  if (!spoken) { voiceDispatch('narration-ended'); return }
  await speak(spoken)

A /tts request that never settles therefore parks the loop in SPEAKING — status line reading "Speaking — say something to interrupt" with nothing playing, mic tracks live, browser recording indicator on — with no timer of any kind. This is strictly better than NEW-1 (barge-in is a real advancing edge here, and Stop works), so I am not calling it blocking. But it is the same primitive the PR itself just rejected on principle: "a promise that can never settle is the wrong primitive to hand a UI regardless of who is watching it." Unattended, it is a hot mic that no clock ever reclaims.

What makes it a finding rather than a nit is that the docs now claim it is covered. workspace-voice-conversation.md:

THINKING is bounded only by the agent's own timeout. Every other live state has a timer — the utterance cap, the silence hold, the no-speech idle stop, and (since the review) a watchdog spanning the /stt call plus a transport timeout on it.

Those four timers cover LISTENING and TRANSCRIBING. None covers SPEAKING. FR-9 likewise says "Transcription is bounded twice" and says nothing about synthesis. So the requirement and the code disagree again — the specific objection this round was raised to settle.

Cheapest honest fix is the one already applied one endpoint over: { headers: this.authHeader, responseType: 'blob', timeout: 60000 }. (A narration watchdog would additionally cover a playback that stalls without firing error, but a blob-URL stall is remote enough that I would not ask for it.) Failing that, name SPEAKING in FR-9's enumeration alongside THINKING — but silently leaving the sentence as written is the outcome to avoid.
Confidence: high on the code (quoted); high on the doc mismatch (quoted).

2. MEDIUM — finishUtterance captures a generation token and then checks it only on the failure path; the success path's guard is generation-blind

  const transcribeToken = voiceStartToken
  …
    const text = await store.transcribeStt(props.agent.name, blob)
    clearTranscribeWatchdog()
    if (voiceState.value !== VOICE_TRANSCRIBING) return
    if (text) voiceDispatch('transcript', text)
    else voiceDispatch('transcript-empty')
  } catch (e) {
    clearTranscribeWatchdog()
    failVoice(transcriptionErrorMessage(e), transcribeToken)
  }

The token is used in the catch and nowhere else. voiceState.value !== VOICE_TRANSCRIBING answers "is some loop waiting for a transcript?", not "is this loop still the live one?" — which is exactly the distinction failVoice's own fix was introduced to make (its comment: "A user who pressed Stop on a slow turn and then restarted the loop had the NEW conversation torn down…"). The success path has the mirror-image bug and no guard:

  • utterance A goes to /stt (now bounded at 60s, so the stale window is up to a minute);
  • user presses Stop → releaseVoiceHardware() → voiceStartToken++; user restarts and speaks;
  • the new loop reaches TRANSCRIBING (it returns there every single turn, so the window recurs);
  • A's /stt resolves → state check passes → voiceDispatch('transcript', <A's words>) → THINKING → runVoiceTurn sends the abandoned conversation's utterance as a real turn.

Two aggravators, both from the same root cause — finishUtterance reads module-scope state at call time rather than capturing it when its recorder stopped:

  const type = resolveRecordingMimeType(convRec?.mimeType, convChunks)
  const blob = new Blob(convChunks, { type })
  convChunks = []

A stale run that gets past the state check reads the current recorder's mimeType, uploads the current utterance's chunks, and then empties the live buffer — so the real utterance also loses its audio. And its post-await clearTranscribeWatchdog() disarms the live loop's watchdog, re-opening NEW-1's window (now backstopped only by the 60s transport timeout).

One line closes all three: if (transcribeToken !== voiceStartToken) return immediately after the await, before the clear. I did not push it — it is narrow enough (needs a slow /stt plus a stop/restart straddling it) that I would rather you decide than have me add a commit mid-review.
Confidence: high that the guard is generation-blind (quoted); medium on real-world frequency.

3. LOW — the agent-switch teardown does not cover the startup window

watch(() => props.agent?.name, () => {
  if (voiceConvLive.value) stopVoiceConversation()
  stopSpeaking(); voiceError.value = ''; voiceMode.value = loadVoiceMode()
})

voiceConvLive is false for the whole of startVoiceConversation — the loop only becomes live at its last line (voiceDispatch('start')), after getUserMedia and the AudioContext resume. A permission prompt can sit open for seconds. Switch agents during that window and the watcher takes no action and does not bump voiceStartToken, so the in-flight start finds its token current, installs the stream, and opens a live loop bound to the new agent — whose stt_available / voice_available were never re-evaluated (the mode was computed for the old one). releaseVoiceHardware() in the watcher (or an unconditional voiceStartToken++) would close it; the unmount path already does the right thing via cleanupVoice. Narrow, and the same class of window the file already reasons about carefully elsewhere.
Confidence: high on the mechanism; low on frequency (first-grant only, on most browsers).

4. LOW — voiceLoopEndedDuringTurn is armed by any in-flight send, not only the loop's own

  if (sending.value) voiceLoopEndedDuringTurn = true

sending is shared with typed sends, and the composer stays enabled while the loop is LISTENING (deliberately, per FR-6). So: loop live → user types and sends → user presses Stop → that typed turn's reply is silently not narrated, even though the #2157 speaker toggle is on and the loop is over by the time the branch runs. One missed narration, self-correcting on the next turn. Gating on "this turn was dispatched by runVoiceTurn" would be exact.
Confidence: high (quoted); impact cosmetic.

5. NIT — stale narrateReply can cut a restarted loop's narration short

narrateReply takes no generation token and guards its trailing dispatch with if (!speaking.value && voiceState.value === VOICE_SPEAKING). A speak() abandoned by narrationToken returns without resetting speaking, which stopSpeaking() has already set false — so a stale narrateReply resuming while a restarted loop happens to be in SPEAKING would dispatch narration-ended and cut the new narration to LISTENING. Very narrow; noted only because every other async path in this file now carries a token and this one does not.

6. NIT (tests) — three source assertions are pinned to shape rather than to rule

The #2157 rewrite is a genuine improvement — term-by-term, with the widened window justified in a comment, and the learnings entry captures the lesson. Three assertions still break on a harmless edit:

    expect(component.match(/voiceState\.value = [^=]/g) || []).toHaveLength(2)
    expect(component.match(/await submitUserText\(/g) || []).toHaveLength(2)
    expect(CODE).toMatch(/!voiceLoopEndedDuringTurn\) speak\(data\.response\)/)

The first two encode "exactly one writer" / "voice shares the submit path" as a count, so a third legitimate caller fails them for the right-sounding wrong reason; the third pins byte adjacency, so moving speak(...) to its own line breaks it. The sibling regex above it already pins that rule with a window, so the literal is redundant. Not blocking — flagging because this is the exact brittleness class the PR's own learnings entry warns about.


Checked clean, and what proved it

  • Every live state enumerated for an advancing edge. OFF — n/a. LISTENING — monitorTick at 100 ms + utteranceVerdict, capped by MAX_UTTERANCE_MS 30 s / SILENCE_HOLD_MS 1.2 s / NO_SPEECH_TIMEOUT_MS 15 s → idle stop with a sentence. TRANSCRIBING — watchdog (45 s) + transport timeout (60 s), armed at its single entry point. THINKING — bounded only by the agent's own timeout: known, documented, accepted (finding B). SPEAKING — barge-in and Stop only, no timer: finding 1.
  • Start re-entrancy. if (voiceConvLive.value || voiceStarting) return with voiceStarting = true set synchronously before the first await, plus const token = ++voiceStartToken; a superseded start stops the tracks it just acquired (token !== voiceStartToken → getTracks().forEach(t => t.stop())), and nextVoiceState makes start idempotent while live. No path opens two streams or two 100 ms timers within a single mount. The only gap found is the agent-switch case above.
  • Teardown ordering. releaseVoiceHardware bumps voiceStartToken before it tears anything down, and calls stopSpeaking() itself rather than relying on the machine emitting ACT_STOP_NARRATION — so releasing hardware mid-synthesis cannot play after the fact. cleanupVoice (unmount) calls it first.
  • Double narration. voiceMode.value && ttsEnabled.value && data.response && !voiceConvLive.value && !voiceLoopEndedDuringTurn — the loop narrates through spokenReply, the bug(voice): agents tell Workspace clients the surface is text-only — portal TTS is never advertised, and the channel/portal voice gates disagree #2157 branch never does while a loop is live or after one it stopped; reset per-turn at the top of deliver. Pinned term by term.
  • Concurrent deliver(). runVoiceTurn opens with the sending.value guard (matching send()'s), so a spoken turn yields to a typed one rather than sharing elapsedTimer / attachments / awaitPersistedReply's baseline count.
  • Machine purity. nextVoiceState is the only writer of transitions; the component's two voiceState.value = sites are the dispatcher and the unmount reset. Every event is inert in off.
  • Docs. FR-9 §48.3, the feature flow, feature-flows.md and architecture.md all landed, and the two documented windows say what the PR says they say. The learnings.md entries are the right two lessons.

Unverifiable without a browser and a microphone

Echo-cancellation efficacy and whether BARGE_IN_RMS / SPEECH_RMS / BARGE_IN_HOLD_MS feel right in a real room; whether MediaRecorder.mimeType behaves as assumed on Firefox/Safari; whether <audio> reliably fires ended/error for these blobs; and the actual latency of a /stt → turn → /tts cycle. None of the findings above depend on any of it.

Summary

The three things I was asked to verify all hold: NEW-1 is fixed at both layers with the arming side checked too, NEW-2 is fixed, and the two accepted windows really are named in FR-9 and in Known limits. What I found fresh is one more instance of NEW-1's own root cause that the fix did not sweep — synthesizeTts on the same untimed axios instance, awaited in the one live state that has no timer, while the docs now assert every state but THINKING has one (finding 1) — and one generation-token hole where a token is captured but only consulted on failure (finding 2). Neither is a hot mic with no way out, so I would not re-block on them; both are small, and finding 1 in particular is a one-line change plus a sentence, which would let the "every other live state has a timer" claim stand as written.

…ed (ent#440)

Two review findings, both in the async paths.

1. A TRANSCRIPT FROM AN ABANDONED LOOP COULD BE SENT AS A REAL TURN.
   `finishUtterance` captured `transcribeToken` but consulted it only in the
   catch; the success path guarded on `voiceState !== VOICE_TRANSCRIBING`,
   which is generation-BLIND. Stop the loop, start it again, and the abandoned
   `/stt` — up to its 60s timeout — resolves into a NEW loop that is
   legitimately back in TRANSCRIBING. It would then dispatch the previous
   conversation's words as a real turn, clobber the live `convChunks`, and
   disarm the live watchdog. The generation check now runs FIRST, before
   anything that touches shared loop state.

2. SPEAKING HAD NO BOUND AT ALL. It is the one live state with no timer of its
   own — barge-in and Stop are its only exits — and it awaits `synthesizeTts`
   on the same `portalHttp` instance created with `timeout: 0`. A hung `/tts`
   therefore held the microphone open with nothing counting: the same hot-mic
   outcome FR-9 forbids that the `/stt` timeout was added to close, one state
   over. Same 60s bound, same reason.

The Known-limits entry claiming "every other live state has a timer" was false
once SPEAKING was examined — it has none, and now relies on a transport
deadline instead. Rewritten to enumerate what actually bounds each state, since
a requirement that disagrees with the code is precisely what the reviewer
objected to in the first place.

1296 frontend tests pass.

Related to Abilityai/trinity-enterprise#440

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

@obasilakis obasilakis 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.

Approving — this clears my earlier CHANGES_REQUESTED.

Both round-3 blockers are fixed and verified in head:

  1. Transcribe watchdog — clearTranscribeWatchdog() no longer fires at the top of finishUtterance; it now runs only on the two early exits and after the await, so it actually bounds the /stt call it claims to. stores/clientPortal.js adds timeout: 60000 on /stt (was timeout: 0), which was the other half. The generation-token check above the clear is a path I hadn't raised — good catch.
  2. FR-9's enumeration disagreeing with the code — I offered fix-or-document and the document arm is satisfied: public-access.md gains a named "Two windows this enumeration does NOT cover" block for the unbounded THINKING window and the same-agent thread switch, and workspace-voice-conversation.md carries both in Known limits with the reasoning.

Round-1/2 fixes re-verified intact: narrationToken sits above the !url arm, releaseVoiceHardware calls stopSpeaking() itself, and runVoiceTurn's if (sending.value) failVoice(...) guard is present.

Merge note: this conflicts with dev on docs/memory/learnings.md (EOF append only, no code). #2382 and #2386 conflict on the same file — first one in forces the other two to rebase.

Non-blocking, still open: NEW-3 (voiceLoopEndedDuringTurn set unconditionally in releaseVoiceHardware, so a typed turn's #2157 narration is suppressed when the loop didn't dispatch it); NEW-4 (the voice spec greps un-stripped source, so a comment can satisfy a toContain — partly mitigated by the structural index assertions); and PortalConversation.vue raw_gray 72 vs baseline 57.

dolho added 2 commits August 26, 2026 22:14
…ce-voice-conversation

# Conflicts:
#	docs/memory/learnings.md
…ce-voice-conversation

# Conflicts:
#	docs/memory/learnings.md
@dolho
dolho merged commit 17103e9 into dev Aug 27, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants