diff --git a/.changeset/live-coverage-count.md b/.changeset/live-coverage-count.md new file mode 100644 index 0000000000..9f72367447 --- /dev/null +++ b/.changeset/live-coverage-count.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +--- + +`historyCoverage` on `conversation_opened` and `LiveConversationSession` gains an optional `includedMessages`: how many prior chat and spoken messages the live startup context actually carried (completed results and gap markers are not counted). The server reports it for both built-in engines, and the live conversation's inline chat notice now reads "Started with the last {n} messages · Details", keeping the coverage-state wording for older hosts that omit the count. The count is host-only display data and never reaches the voice provider (#3699). diff --git a/.changeset/live-voice-field.md b/.changeset/live-voice-field.md new file mode 100644 index 0000000000..64e297c430 --- /dev/null +++ b/.changeset/live-voice-field.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-react": minor +--- + +Live conversation now draws its state in the tall voice field from `@schlessera/brain-ui-kit` (#3699). The field's colour, meter, icon and one word say who has the floor (Connecting, Listening, Thinking, Working, Speaking, Needs your tap, Muted, Reconnecting), with the service and the connected time beside it, and Mute, Interrupt and End sit on its raised controls. Interrupt is enabled only while a reply plays. A failure that withdraws capture shows "Live conversation stopped" with the client's reason, and Start again reopens the disclosure. Nothing stacks above the field any more: its body shows one message at a time (a held draft, then the tap-only refusal line, then reply audio off, then the client's notice), a held draft reads "Draft · not sent yet" with Send now and Discard draft in the controls row (taking Interrupt's place unless brain is speaking), Recover reply audio stays in the row while reply audio is off, and waiting for voice readiness reads "mic off". Incomplete startup-context coverage is an inline notice in the chat at the start of the live section, and background tasks leave the field for the chat. A blocked microphone now says to allow it, then Start again. The two diagnostic status lines ("● Listening · mic on", "Connected · chat: ok"), the provider-code details button and the Mute mic, Stop reply and Leave voice buttons are gone. The conversation client exposes its capture intent (`capture`: `idle`, `listening`, `muted` or `stopped`) and display-only meter readings (`levels()`); neither changes capture, recovery or permission behaviour. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index 839a754555..e8d2e6e01d 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -353,6 +353,7 @@ signatures (every public export and the types it is made of) token: number; connection: "Connecting" | "Connected" | "Reconnecting" | "Speech lost"; micOn: boolean; + capture: "idle" | "listening" | "muted" | "stopped"; interaction: "Listening" | "Sending soon" | "Review before sending" | "Working" | "Speaking" | "Checking whether the reply stopped" | "Answering question"; disclosureOpen: boolean; profile: ServerConversationOpened | null; @@ -1389,6 +1390,10 @@ signatures (every public export and the types it is made of) frame: (message: import("@schlessera/brain-ui-sdk").ServerMessage) => import("@schlessera/brain-ui-sdk").ServerMessage | null; historyOwnerFor: (key: string) => string | undefined; leave: () => void; + levels: () => { + input: number; + output: number; + }; loadDialogue: (key: string, older?: boolean) => void; mute(): void; permissions: { diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index da7cc34f4f..9b6bd7b28f 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -8563,6 +8563,7 @@ signatures (every public export and the types it is made of) historyCoverage?: { state: "complete" | "bounded" | "partial" | "unavailable"; tailOmitted: boolean; + includedMessages?: number; }; events: AsyncIterable; appendAudio(chunk: LiveConversationAudioChunk): void; @@ -11097,6 +11098,7 @@ signatures (every public export and the types it is made of) historyCoverage?: { state: "complete" | "bounded" | "partial" | "unavailable"; tailOmitted: boolean; + includedMessages?: number; }; historyGeneration?: number; historyOwnerId?: string; @@ -19868,6 +19870,7 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; epoch: z.ZodNumber; historyCoverage: z.ZodOptional; state: z.ZodEnum<{ bounded: "bounded"; complete: "complete"; @@ -23954,6 +23957,7 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; epoch: z.ZodNumber; historyCoverage: z.ZodOptional; state: z.ZodEnum<{ bounded: "bounded"; complete: "complete"; diff --git a/docs/decisions/design-kit/components-and-interactions.md b/docs/decisions/design-kit/components-and-interactions.md index 700012eb92..5985029036 100644 --- a/docs/decisions/design-kit/components-and-interactions.md +++ b/docs/decisions/design-kit/components-and-interactions.md @@ -1364,7 +1364,7 @@ implements them with the session store: | `settings/modules-tab.tsx` complete source values | `
` | Evidence: `Complete source values · {n} keys`. | | `settings/module-settings-fields.tsx` collapsible lists | `Surface` and `
` | Editable item: `ItemCard`. | | `voice/conversation-unassigned.tsx` | `
` "Optional voice review" | Optional control: `Callout` and "Review in composer". | -| `voice/conversation-strip.tsx` background tasks | `
` | Evidence: `Background tasks · {n} contextual requests`. | +| `voice/conversation-field.tsx` background tasks | `
` | Removed from the live field (#3699); each task is a `VoiceToolChip` in the chat (#3700). | | `voice/recordings-tray.tsx` header | raw `aria-expanded` button | Panel: `Tray`, `On this device · {n} recordings · {size}`. | | `graph/graph-maintenance.tsx` finding groups | `TextButton` and dot | Panel: `Tray` with the lens swatch; the label keeps the kind's name. | | `graph/graph-scene.tsx` `ClusterLegend` | raw `aria-expanded` row | Panel: `Tray`, `Topics · {n}`. | diff --git a/docs/extending/speech.md b/docs/extending/speech.md index d979f7450d..0b4f7012e5 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -388,9 +388,21 @@ capability limits, then select **Start**. With either built-in service, use **Send now** to commit recognized text. The ordinary transcript, tools and question/permission controls remain available while host work runs asynchronously. -Mute ends microphone capture until Unmute; Leave returns to the composer with -retained review text in its original draft. Stop reply cuts local audio while -capture and host work continue. Ordinary interruption retains initiating PCM and +While the conversation runs, the composer becomes the tall voice field. Its +colour, meter, icon and one word say who has the floor (Listening, Thinking, +Working, Speaking, Needs your tap, Muted, Reconnecting), with the service and +the connected time beside it. Mute ends microphone capture until Unmute; brain +may finish its current sentence. End returns to the composer with retained +review text in its original draft. Interrupt, enabled only while a reply +plays, cuts local audio while capture and host work continue. A failure that +withdraws capture shows "Live conversation stopped" with its reason; Start +again reopens the disclosure. Nothing stacks above the field: its body holds +one message at a time, in the order draft, refusal ("Tap Allow or Deny on the +card"), reply audio off, then the client's notice. A held draft reads "Draft · +not sent yet" with **Send now** and **Discard draft** in the controls row, where +it takes Interrupt's place unless brain is speaking. Incomplete startup context +is an inline notice in the chat at the start of the live section, with Details. +Ordinary interruption retains initiating PCM and uses bounded local output recovery; timeout exposes Recover reply audio without muting the microphone. Delayed old audio can occasionally play after recovery. Recoverable hide/disconnect/resync retain consent in the same disclosed scope and diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 27effbd893..5c4ff907da 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -660,7 +660,8 @@ carry an optional authorized, frozen chat snapshot, separately from native same-conversation resync. `LiveConversationSession.historyCoverage` and `conversation_opened.historyCoverage` optionally report the actual startup selection's `state` (`complete`, `bounded`, `partial`, `unavailable`) and -`tailOmitted`. This is data receipt/selection evidence, never a guarantee of +`tailOmitted`, plus, additively (#3699), `includedMessages`: the number of +prior chat and spoken messages actually sent. This is data receipt/selection evidence, never a guarantee of semantic recall. See the [package API](integration-contract/package-api.md#existing-chat-live-context-3178) and [wire behavior](integration-contract/wire.md#existing-chat-live-context-3178). diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 3d51ad75cb..30bfe177f3 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4824,6 +4824,18 @@ retires the reviewed input identities; late recognition cannot restore them. These actions and Mute cancel pending automatic review timers, while output recovery remains independent of microphone consent. +### Conversation capture intent and meter readings (#3699) + +Additive. The conversation client's state carries `capture`, the intent behind +`micOn`: `idle` before Start in an entry, `listening` while consent stands +(recoverable transitions restore capture on their own), `muted` after a manual +Mute until Unmute, and `stopped` when a genuine failure withdrew consent and only +a new Start resumes capture. Manual Mute stays `muted` across teardown and +reconnects. `levels()` returns display-only 0–1 readings, `{ input, output }`: +the newest microphone block while capture is open, and the 10 ms window of the +reply sounding now. Neither value gates capture, endpointing, output recovery or +permission routing. + ### Retained dialogue data (#3177) The SDK protocol exports `DialogueEvidence`, `DialogueRecord`, `DialoguePage`, @@ -4893,7 +4905,11 @@ recency is unknown. Partial coverage uses “may be missing” copy rather than claim about the exact newest item. These bounds never delete the display archive. `LiveConversationSession.historyCoverage?` exposes the adapter's actual bounded -historical selection as `{state, tailOmitted}`. Third-party providers may ignore +historical selection as `{state, tailOmitted, includedMessages?}`. The optional +`includedMessages` (additive, #3699) is the number of prior chat and spoken +messages the startup context actually carried; completed results and gap markers +are not counted, and it is 0 when no history block was sent. It is host-only +display data: it is never part of any provider-facing text. Third-party providers may ignore the additive history input but cannot thereby claim existing-chat continuity. The frozen provider prefix/tools/instructions are never rewritten within an epoch. diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 7360bdb195..6954e49947 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -2418,7 +2418,7 @@ request. Host terminal state reconciles unanswered requests without depending on Neither built-in adapter has a proven deterministic exact-copy permission audio path. The approved fallback therefore uses a local earcon, the existing card and -a 40px strip line. Permission scripts and confirmed outcome wording are visual +the live field's refusal line. Permission scripts and confirmed outcome wording are visual only: they are never submitted as model commentary or to a separate TTS service. Labels come only from bounded static registry labels (four words at most), with `An action` as the generic fallback. Payloads and unproven effect descriptions @@ -2850,8 +2850,14 @@ stops capture and exposes the unavailable tail honestly. ## Existing-chat live context (#3178) -`conversation_opened` optionally carries `historyCoverage: {state, tailOmitted}`, -with state `complete`, `bounded`, `partial` or `unavailable`. It describes selected +`conversation_opened` optionally carries `historyCoverage: {state, tailOmitted, +includedMessages?}`, with state `complete`, `bounded`, `partial` or `unavailable`. +`includedMessages` (additive, #3699) is a non-negative integer: exactly how many +prior chat and spoken messages the startup context carried, excluding completed +results and gap markers. The shipped client names it in the chat's coverage +notice ("Started with the last {n} messages") and falls back to the coverage +state when an older host omits it. It is display data for the client and never +enters the provider-facing conversation. It describes selected historical text at startup, independently of retained display history, generated speech and playback. Details disclose partial sources/order, context omissions and an omitted newest item without claiming the model understood the text. diff --git a/packages/ui-react/src/components/chat/chat-page.tsx b/packages/ui-react/src/components/chat/chat-page.tsx index 6532e1525f..ce5affc3bb 100644 --- a/packages/ui-react/src/components/chat/chat-page.tsx +++ b/packages/ui-react/src/components/chat/chat-page.tsx @@ -1,6 +1,6 @@ import { transcriptMessage, transcriptTimelineFor, transcriptRange } from "../../lib/transcript-timeline.js"; import { useStore } from "zustand"; -import { ConversationOutput, ConversationRecognitionRow, ConversationPermissionOutcomes, ConversationTaskContext, conversationEndLabel } from "../voice/conversation-outputs.js"; +import { ConversationCoverageNotice, ConversationOutput, ConversationRecognitionRow, ConversationPermissionOutcomes, ConversationTaskContext, conversationEndLabel } from "../voice/conversation-outputs.js"; import { replyToToolApproval } from "../../lib/tool-approval.js"; import type { AskUserFormAnswers } from "@schlessera/brain-ui-sdk/protocol"; import { useBrainUiRoot } from "../../root-context.js"; @@ -760,6 +760,7 @@ export function ChatPage() { {visibleEntries.map((entry) => { if (entry.kind === "history-notice") return

{entry.label}

; + if (entry.kind === "voice-coverage") return
; if (entry.kind === "speech") return ; if (entry.kind === "voice-boundary") return entry.label === "Voice ended" ?
diff --git a/packages/ui-react/src/components/chat/composer.tsx b/packages/ui-react/src/components/chat/composer.tsx index 6efd6f447c..5ea807731a 100644 --- a/packages/ui-react/src/components/chat/composer.tsx +++ b/packages/ui-react/src/components/chat/composer.tsx @@ -1,6 +1,6 @@ import { useStore } from "zustand"; import { ConversationUnassigned } from "../voice/conversation-unassigned.js"; -import { ConversationStrip } from "../voice/conversation-strip.js"; +import { ConversationField } from "../voice/conversation-field.js"; import { Button, Callout, InlineToast } from "@schlessera/brain-ui-kit"; import { useBrainUiRoot, useRootStore } from "../../root-context.js"; import { useState, useRef, useEffect, useLayoutEffect, useImperativeHandle, useReducer, type Ref } from "react"; @@ -946,7 +946,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void return ( <> - {conversation.active ?
queueMicrotask(focusField)} />
:
+ {conversation.active ?
queueMicrotask(focusField)} />
:
{/* Says where a taken suggestion went, since focus moves with it. */}
{insertNotice} diff --git a/packages/ui-react/src/components/voice/conversation-field.tsx b/packages/ui-react/src/components/voice/conversation-field.tsx new file mode 100644 index 0000000000..45fd6a22a1 --- /dev/null +++ b/packages/ui-react/src/components/voice/conversation-field.tsx @@ -0,0 +1,192 @@ +import { useEffect, useRef, useState } from "react"; +import { useStore } from "zustand"; +import { Button, Overlay, VoiceControlButton, VoiceField, VoiceNotice, VoiceText, type IconName } from "@schlessera/brain-ui-kit"; +import { useBrainUiRoot } from "../../root-context.js"; +import { conversationService, MUTED_NOTICE, READINESS_NOTICES, REVIEW_BOUNDED_NOTICE, REVIEW_TRIMMED_NOTICE, UNCLEAR_NOTICE, type ConversationClientState } from "../../voice/conversation-client.js"; +import { PERMISSION_PENDING_LINE } from "../../voice/conversation-permissions.js"; + +/** The live states the tall voice field draws (#3690); S5 is the Start sequence's Connecting. */ +type LiveFieldState = "S5" | "L1" | "L2" | "L3" | "L4" | "L5" | "L6" | "L7" | "L8" | "L9"; + +/** + * Maps the client's own state onto one live state. Every input is something + * the client knows: its connection, capture intent, the playing reply, host + * work and a pending approval card. `null` draws no field (before Start, or + * while the disclosure sheet asks for one). + */ +function liveFieldState(s: Pick, + o: { speaking: boolean; hostWork: boolean; approval: boolean }): LiveFieldState | null { + if (!s.active || s.capture === "idle" || s.disclosureOpen && s.capture === "stopped") return null; + if (s.capture === "stopped") return "L9"; + if (s.connection === "Connecting") return "S5"; + if (s.connection !== "Connected") return "L8"; + // V5: a muted microphone does not silence brain's current sentence. + if (o.speaking) return "L4"; + if (o.approval) return "L6"; + if (s.capture === "muted") return "L7"; + if (!s.micOn) return "S5"; + if (s.interaction === "Working" || s.interaction === "Answering question") return o.hostWork ? "L3" : "L2"; + if (s.outputRecovery === "speaking" || s.outputRecovery === "checking" || s.interaction === "Checking whether the reply stopped") return "L5"; + return "L1"; +} + +type Look = { tone: "you" | "brain" | "idle"; icon: IconName; word: string; meter: "level" | "sweep" | "flat" | "hatch" | "none"; spin?: boolean; outline?: boolean }; +const LOOKS: Record, Look> = { + S5: { tone: "brain", icon: "loading", word: "Connecting", meter: "none", spin: true }, + L1: { tone: "you", icon: "mic", word: "Listening", meter: "level" }, + L2: { tone: "brain", icon: "loading", word: "Thinking", meter: "sweep", spin: true }, + L3: { tone: "brain", icon: "working", word: "Working", meter: "sweep" }, + L4: { tone: "brain", icon: "speaker", word: "Speaking", meter: "level" }, + L5: { tone: "you", icon: "mic", word: "Listening", meter: "level" }, + L6: { tone: "idle", icon: "hand", word: "Needs your tap", meter: "none", outline: true }, + L7: { tone: "idle", icon: "mic-off", word: "Muted", meter: "flat" }, + L8: { tone: "idle", icon: "loading", word: "Reconnecting…", meter: "hatch" }, +}; + +/* The signed-off copy for the field's body and meta (#3699). */ +const DRAFT_META = "Draft · not sent yet"; +const REFUSAL_LINE = "Tap Allow or Deny on the card. Voice can’t approve or refuse with this service."; +const OUTPUT_MUTED_LINE = "Brain’s voice was paused after a dropout. Replies still arrive as text."; +const OUTPUT_MUTED_NOTICE = "Reply audio is muted. Recover reply audio to listen; the microphone is unchanged."; +const READINESS_LINE = "Waiting for voice to be ready. Nothing is heard until then."; + +function clock(seconds: number) { + const h = Math.floor(seconds / 3600), m = Math.floor(seconds / 60) % 60, sec = seconds % 60; + return `${h ? `${h}:${String(m).padStart(2, "0")}` : m}:${String(sec).padStart(2, "0")}`; +} + +/** Seconds spent connected in this entry. The clock holds while reconnecting (L8). */ +function useConnectedSeconds(running: boolean) { + const [seconds, setSeconds] = useState(0); + useEffect(() => { + if (!running) return; + const tick = setInterval(() => setSeconds(n => n + 1), 1000); + return () => clearInterval(tick); + }, [running]); + return seconds; +} + +/** The meter's reading, sampled only while a level meter shows. */ +function useLevel(read: (() => number) | null) { + const [level, setLevel] = useState(0); + useEffect(() => { + if (!read) { setLevel(0); return; } + const sample = setInterval(() => setLevel(Math.round(read() * 20) / 20), 80); + return () => clearInterval(sample); + }, [read]); + return level; +} + +/** + * The live conversation surface: the tall voice field and nothing above it. + * Its body holds one message, its controls row every action (#3699). + */ +export function ConversationField({ backend, onLeave }: { backend: string; onLeave: () => void }) { + const root = useBrainUiRoot(); + const client = root.connection.conversation; + const s = useStore(client.state); + const permission = useStore(client.permissions.state); + const chat = useStore(root.stores.connection, (state) => state.wsStatus); + const streaming = useStore(root.stores.chat, (state) => !!(s.sessionId === null ? state.draft : state.buffers[s.sessionId])?.isStreaming); + // A pending approval is the tool card's to answer, by tap only (L6). + const approval = useStore(root.stores.chat, (state) => !!(s.sessionId === null ? state.draft : state.buffers[s.sessionId])?.messages.some(m => m.toolCalls.some(t => t.status === "pending_approval"))); + // This hold is presentation only: PCM capture and interruption use the + // client's instantaneous playing state, never this display state. + const [replyToken, setReplyToken] = useState(null); + const canShowReply = s.active && s.connection === "Connected" && s.outputRecovery === "audible" && !s.disclosureOpen && s.interaction !== "Checking whether the reply stopped"; + const replyVisible = canShowReply && (s.playing || replyToken === s.token); + useEffect(() => { + if (!canShowReply) { setReplyToken(null); return; } + if (s.playing) { setReplyToken(s.token); return; } + const timeout = setTimeout(() => setReplyToken(null), 300); + return () => clearTimeout(timeout); + }, [canShowReply, s.playing, s.token]); + const hostWork = streaming || Object.values(s.work).some((work) => work.state === "queued" || work.state === "running"); + const state = liveFieldState(s, { speaking: replyVisible, hostWork, approval }); + const seconds = useConnectedSeconds(s.connection === "Connected" && (s.capture === "listening" || s.capture === "muted")); + const meter = state && state !== "L9" ? LOOKS[state].meter : "none"; + const [readInput] = useState(() => () => client.levels().input); + const [readOutput] = useState(() => () => client.levels().output); + const level = useLevel(meter !== "level" ? null : state === "L4" ? readOutput : readInput); + const frame = useRef(null); + const wasOn = useRef(false); + useEffect(() => { + if (s.micOn && !wasOn.current) frame.current?.querySelector('[aria-label="Mute"]')?.focus(); + wasOn.current = s.micOn; + }, [s.micOn]); + // Root-owned leases distinguish a true unmount from StrictMode or same-task + // remounts. Component cleanup must never impersonate a manual Mute. + useEffect(() => client.attachControls(), [client]); + if (!s.active) return null; + const profile = s.profile; + const disclosed = s.conversationProfile; + const coverage = s.connection === "Connected" ? profile?.historyCoverage : undefined; + const button = { minHeight: 44, minWidth: 44, flex: "1 1 0", width: "auto", padding: "0 6px", fontSize: 12 }; + const leave = () => { client.leave(); onLeave(); }; + const service = profile ? conversationService(profile.providerId) : disclosed ? conversationService(disclosed.providerId) : null; + const muted = s.capture === "muted"; + const draft = !!s.text; + const outputMuted = s.outputRecovery === "muted"; + const readiness = (state === "S5" || state === "L8") && (Object.values(READINESS_NOTICES) as string[]).includes(s.notice); + // The pending line is the field's own refusal copy; any other line (the request limit) is the client's. + const refusal = permission.line === PERMISSION_PENDING_LINE ? REFUSAL_LINE : permission.line; + // A line about the draft itself takes its words' place, as unclear audio does. + const aboutDraft = s.notice === UNCLEAR_NOTICE || s.notice === REVIEW_BOUNDED_NOTICE || s.notice === REVIEW_TRIMMED_NOTICE; + // Notices the field's word, meta or body already say. + const repeated = s.notice === MUTED_NOTICE || s.notice === UNCLEAR_NOTICE || s.notice === OUTPUT_MUTED_NOTICE; + // One message at a time, by priority: draft → refusal → output muted → client notice (#3699). + const body = draft + // Live draft words are `text` (the kit clamps them); every message is `children`, never clamped. + ?
{aboutDraft ? {s.notice} : }
+ : refusal ? {refusal} + : outputMuted ? {OUTPUT_MUTED_LINE} + : readiness ? {READINESS_LINE} + : s.notice && !repeated ? {s.notice} + : null; + const meta = draft ? DRAFT_META : outputMuted ? "Reply audio off" : readiness ? "mic off" + : [service, state === "S5" ? null : clock(seconds)].filter(Boolean).join(" · ") || undefined; + return
+
{s.announcement}
+ {state === "L9" + ?
+ : state &&
+ + + {/* Recovery stays manual and visible for as long as reply audio is off, even under a draft. */} + {outputMuted + ? + // R1: a held draft takes Interrupt's place unless brain is speaking. + : (!draft || state === "L4") && } + {draft && <> + + client.commit(s.token)} /> + } + + }> + {body} + +
} + +
+

{disclosed?.disclosure.voiceService ?? "Connecting to the configured voice service…"}

+ {disclosed?.disclosure.destinations.map((destination) =>

{destination}

)} +

Host relay: {typeof window === "undefined" ? root.apiBase() || "this application’s host" : new URL(root.apiBase() || "/", window.location.href).origin}

+

Independently selected agent backend: {backend}. API destination and retention: unknown unless documented by the host.

+ {disclosed?.capabilities.contextualTasks === "supported" + ?

Brain can start permitted background tasks from the conversation and share results while you keep talking. Actions that need confirmation use the same screen cards as typed requests. Recognition may be uncertain; speech cannot approve an action.

+ : disclosed?.capabilities.finalTranscript !== "supported" &&

Automatic tasks aren't available with this service. Review recognized text and use Send now.

} +

{s.durableAvailable || client.historyOwnerFor(s.sessionId ?? "") ? "Recognized speech and generated voice replies are saved as text with this chat. This feature does not save audio. Reopening text does not replay audio or prove the voice service received this history." : "Live recognition is temporary and may be unavailable after reload."}

+

Starting voice sends bounded prior chat text and completed results to this voice service, including when you switch services. Raw audio is not retained by this feature.

+ {coverage &&

{coverage.state === "complete" ? "Available prior text was included in startup context." : coverage.state === "bounded" ? "Some prior text was omitted to fit startup context." : coverage.state === "partial" ? "Some prior discussion evidence or its original order is unavailable." : "Prior discussion evidence is unavailable."} {coverage.tailOmitted && (coverage.state === "partial" ? "The newest prior item may be missing." : "The newest prior item was not included.")} This does not prove the service understood or recalled it.

} +

Spoken refusal is unavailable with the current voice services. Use Deny on screen.

+ {profile?.capabilities.exactPermissionSpeech !== "supported" &&

Permission decisions remain on screen; spoken announcements are unavailable.

} + {s.notice &&

{s.notice}

} +
+
+
+
; +} diff --git a/packages/ui-react/src/components/voice/conversation-outputs.tsx b/packages/ui-react/src/components/voice/conversation-outputs.tsx index e9fba74686..49ec013c06 100644 --- a/packages/ui-react/src/components/voice/conversation-outputs.tsx +++ b/packages/ui-react/src/components/voice/conversation-outputs.tsx @@ -1,4 +1,4 @@ -import { Button, SpokenTurn, UncertainWord } from "@schlessera/brain-ui-kit"; +import { Button, Callout, SpokenTurn, TextButton, UncertainWord } from "@schlessera/brain-ui-kit"; import { TranscriptQualifiers, TranscriptSymbols } from "@schlessera/brain-ui-kit/internal"; import type { TranscriptEntry } from "../../lib/transcript-timeline.js"; import { conversationService, type ConversationRecognition, type ConversationClientOutput } from "../../voice/conversation-client.js"; @@ -22,6 +22,23 @@ function RecognizedWords({ fragment }: { fragment: ConversationRecognition }) { return words ? <>{lead}{words}{trail} : <>{fragment.text}; } +/** + * R2 (#3699): a live conversation's startup-context coverage, inline at the + * start of its live section. It says only what `historyCoverage` reports: + * the host's count of messages sent, or, from an older host without one, the + * coverage state. Details opens the disclosure sheet while that conversation is live. + */ +export function ConversationCoverageNotice({ conversationId, coverage }: { conversationId: string; coverage: { state: string; tailOmitted: boolean; includedMessages?: number } }) { + const client = useBrainUiRoot().connection.conversation; + const live = useStore(client.state, s => s.active && s.profile?.conversationId === conversationId); + const n = coverage.includedMessages ?? 0; + const text = n > 0 ? `Started with the last ${n} ${n === 1 ? "message" : "messages"}` + : coverage.tailOmitted ? coverage.state === "partial" ? "Newest prior context may be missing." : "Newest prior context was not sent." : "Prior context is incomplete."; + return
+ {text}{live && <> · } +
; +} + /** Voice-generated words share Chat's scrolling transcript; they never replace backend progress. */ export function ConversationPermissionOutcomes({ sessionId }: { sessionId: string | null }) { const root = useBrainUiRoot(); diff --git a/packages/ui-react/src/components/voice/conversation-strip.tsx b/packages/ui-react/src/components/voice/conversation-strip.tsx deleted file mode 100644 index 30cdd597e7..0000000000 --- a/packages/ui-react/src/components/voice/conversation-strip.tsx +++ /dev/null @@ -1,108 +0,0 @@ -import { DraftSaveLine } from "../chat/draft-save-line.js"; -import { useMediaQuery } from "../../hooks/use-media-query.js"; -import { useEffect, useRef, useState } from "react"; -import { useStore } from "zustand"; -import { Button, Disclosure, Overlay, TextButton } from "@schlessera/brain-ui-kit"; -import { useBrainUiRoot } from "../../root-context.js"; - -/** The voice controls live below the ordinary transcript and its interactive cards. */ -export function ConversationStrip({ backend, onLeave }: { backend: string; onLeave: () => void }) { - const root = useBrainUiRoot(); - const client = root.connection.conversation; - const s = useStore(client.state); - const permission = useStore(client.permissions.state); - const shortScreen = useMediaQuery("(max-height: 580px)"); - const chat = useStore(root.stores.connection, (state) => state.wsStatus); - const needsScreen = useStore(root.stores.chat, (state) => { - const exchange = (s.sessionId === null ? state.draft : state.buffers[s.sessionId])?.askUser; - return !!exchange && !exchange.cancelled && !exchange.answers && !exchange.order && !exchange.formAnswers && (exchange.questions.length !== 1 || !!exchange.list || !!exchange.rank || !!exchange.form); - }); - // This hold is presentation only: PCM capture and interruption use the - // client's instantaneous playing state, never this display state. - const [replyToken, setReplyToken] = useState(null); - const canShowReply = s.active && s.connection === "Connected" && s.outputRecovery === "audible" && !s.disclosureOpen && s.interaction !== "Checking whether the reply stopped"; - const replyVisible = canShowReply && (s.playing || replyToken === s.token); - const interaction = replyVisible ? "Speaking" : s.interaction; - useEffect(() => { - if (!canShowReply) { setReplyToken(null); return; } - if (s.playing) { setReplyToken(s.token); return; } - const timeout = setTimeout(() => setReplyToken(null), 300); - return () => clearTimeout(timeout); - }, [canShowReply, s.playing, s.token]); - const frame = useRef(null); - const wasOn = useRef(false); - useEffect(() => { - if (s.micOn && !wasOn.current) frame.current?.querySelector('[aria-label="Mute mic"]')?.focus(); - wasOn.current = s.micOn; - }, [s.micOn]); - // Root-owned leases distinguish a true unmount from StrictMode or same-task - // remounts. Component cleanup must never impersonate a manual Mute. - useEffect(() => client.attachControls(), [client]); - if (!s.active) return null; - const profile = s.profile; - const disclosed = s.conversationProfile; - const coverage = s.connection === "Connected" ? profile?.historyCoverage : undefined; - const button = { minHeight: 44, minWidth: 44, flex: "1 1 0", width: "auto", padding: "0 6px", fontSize: 12 }; - const control = { ...button, padding: "0 2px" }; - const leave = () => { client.leave(); onLeave(); }; - const contextual = Object.values(s.work).filter(w => w.provenance === "contextual"); - return
-
{s.announcement}
-
-
-
{s.micOn ? "●" : "○"} {interaction} · mic {s.micOn ? "on" : "off"}
-
{s.connection} · chat: {chat === "connected" ? "ok" : "lost"}
-
-
- {coverage && coverage.state !== "complete" &&
{coverage.tailOmitted ? coverage.state === "partial" ? "Newest prior context may be missing." : "Newest prior context was not sent." : "Prior context is incomplete."}
} - {s.outputRecovery === "muted" &&
-
} - {contextual.length > 0 &&
- -
    {contextual.slice(-8).map(w =>
  • -

    Context: {w.recognized.slice(-160)}

    - Conversation task · {w.state} · {w.delivery === "returned" ? "result accepted by voice service; playback unknown" : w.delivery === "unknown" ? "result acceptance unknown; no automatic replay" : w.delivery === "pending" ? "result pending" : "result withheld"} - {w.reason &&

    {w.reason}

    } -
  • )}
-
-
} - {permission.line &&
{permission.line}
} -
-
- -
-

{disclosed?.disclosure.voiceService ?? "Connecting to the configured voice service…"}

- {disclosed?.disclosure.destinations.map((destination) =>

{destination}

)} -

Host relay: {typeof window === "undefined" ? root.apiBase() || "this application’s host" : new URL(root.apiBase() || "/", window.location.href).origin}

-

Independently selected agent backend: {backend}. API destination and retention: unknown unless documented by the host.

- {disclosed?.capabilities.contextualTasks === "supported" - ?

Brain can start permitted background tasks from the conversation and share results while you keep talking. Actions that need confirmation use the same screen cards as typed requests. Recognition may be uncertain; speech cannot approve an action.

- : disclosed?.capabilities.finalTranscript !== "supported" &&

Automatic tasks aren't available with this service. Review recognized text and use Send now.

} -

{s.durableAvailable || client.historyOwnerFor(s.sessionId ?? "") ? "Recognized speech and generated voice replies are saved as text with this chat. This feature does not save audio. Reopening text does not replay audio or prove the voice service received this history." : "Live recognition is temporary and may be unavailable after reload."}

-

Starting voice sends bounded prior chat text and completed results to this voice service, including when you switch services. Raw audio is not retained by this feature.

- {coverage &&

{coverage.state === "complete" ? "Available prior text was included in startup context." : coverage.state === "bounded" ? "Some prior text was omitted to fit startup context." : coverage.state === "partial" ? "Some prior discussion evidence or its original order is unavailable." : "Prior discussion evidence is unavailable."} {coverage.tailOmitted && (coverage.state === "partial" ? "The newest prior item may be missing." : "The newest prior item was not included.")} This does not prove the service understood or recalled it.

} -

Spoken refusal is unavailable with the current voice services. Use Deny on screen.

- {profile?.capabilities.exactPermissionSpeech !== "supported" &&

Permission decisions remain on screen; spoken announcements are unavailable.

} - {s.notice &&

{s.notice}

} -
-
-
-
; -} diff --git a/packages/ui-react/src/lib/transcript-timeline.ts b/packages/ui-react/src/lib/transcript-timeline.ts index eac63b05f3..c79f32057b 100644 --- a/packages/ui-react/src/lib/transcript-timeline.ts +++ b/packages/ui-react/src/lib/transcript-timeline.ts @@ -13,6 +13,8 @@ export type TranscriptEntry = /** From the retained end's host clock span. "Voice ended" comes only from retained evidence, so live and reloaded chats agree. */ durationMs?: number } | {key:string;sessionId:string|null;kind:"history-notice";label:string} + /** R2 (#3699): the startup-context coverage of one live conversation, at the start of its live section, when it names a sent count or is incomplete. */ + | { key: string; sessionId: string | null; kind: "voice-coverage"; conversationId: string; coverage: NonNullable["historyCoverage"]> } | { key: string; sessionId: string | null; kind: "recognition"; fragments: ConversationRecognition[] }; /** @@ -45,6 +47,7 @@ export function createTranscriptTimeline(chat: StoreApi, voice: Store return positions.get(key)!.arrival; }; const boundaries = new Map>(); + const coverages = new Map>(); const split = new Set(); const runs = new Map>(); const textBefore = new Map(); @@ -238,6 +241,13 @@ export function createTranscriptTimeline(chat: StoreApi, voice: Store boundary.sessionId = recognition?.sessionId ?? output?.sessionId ?? boundary.sessionId; entries.push(boundary); } + for (const [key, notice] of coverages) { + const recognition = v.recognition.find(f => f.conversationId === notice.conversationId); + const output = v.outputs.find(o => o.conversationId === notice.conversationId); + if (!recognition && !output && !(v.active && v.profile?.conversationId === notice.conversationId)) { coverages.delete(key); continue; } + notice.sessionId = recognition?.sessionId ?? output?.sessionId ?? notice.sessionId; + entries.push(notice); + } const rank = (key:string):readonly number[] => { const durable=ordered.get(key); if(durable!==undefined)return [durable,0,0]; const at=position(key), anchor=positions.get(key)?.afterHostSequence; @@ -310,9 +320,16 @@ export function createTranscriptTimeline(chat: StoreApi, voice: Store position(key); latest.set(next.sessionId, key); boundaries.set(key, { kind: "voice-boundary", key, sessionId: next.sessionId, conversationId: profile.conversationId, epoch: profile.epoch, label: "Voice reconnected" }); } + // The coverage notice opens the live section once its conversation reports it. + const coverage = next.active ? next.profile?.historyCoverage : undefined; + if (next.profile && coverage && ((coverage.includedMessages ?? 0) > 0 || coverage.state !== "complete") && !coverages.has(JSON.stringify(["voice-coverage", next.profile.conversationId]))) { + const key = JSON.stringify(["voice-coverage", next.profile.conversationId]); + position(key); latest.set(next.sessionId, key); + coverages.set(key, { kind: "voice-coverage", key, sessionId: next.sessionId, conversationId: next.profile.conversationId, coverage }); + } if (next.profile !== old.profile || next.recognition !== old.recognition || next.outputs !== old.outputs || next.active !== old.active || next.sessionId !== old.sessionId || next.dialogue !== old.dialogue) sync(); }); sync(); - return { state, dispose() { stopChat(); stopVoice(); positions.clear(); boundaries.clear(); runs.clear(); split.clear(); latest.clear(); textBefore.clear(); state.setState({ entries: [] }); } }; + return { state, dispose() { stopChat(); stopVoice(); positions.clear(); boundaries.clear(); coverages.clear(); runs.clear(); split.clear(); latest.clear(); textBefore.clear(); state.setState({ entries: [] }); } }; } /** Data-only display projections. Text ordinals stay intact for classified blocks. */ diff --git a/packages/ui-react/src/voice/conversation-client.ts b/packages/ui-react/src/voice/conversation-client.ts index b824b9eb8a..309d658d44 100644 --- a/packages/ui-react/src/voice/conversation-client.ts +++ b/packages/ui-react/src/voice/conversation-client.ts @@ -59,6 +59,13 @@ export interface ConversationClientState { token: number; connection: "Connecting" | "Connected" | "Reconnecting" | "Speech lost"; micOn: boolean; + /** + * The capture intent behind `micOn`: `idle` before Start in this entry, + * `listening` while consent stands (recovery restores capture on its own), + * `muted` after a manual Mute until Unmute, and `stopped` when a failure + * withdrew consent and only a new Start resumes capture. + */ + capture: "idle" | "listening" | "muted" | "stopped"; interaction: "Listening" | "Sending soon" | "Review before sending" | "Working" | "Speaking" | "Checking whether the reply stopped" | "Answering question"; disclosureOpen: boolean; profile: ServerConversationOpened | null; @@ -82,6 +89,23 @@ export interface ConversationClientState { dialogueRestoredThrough: Record; } +/** The notice for recognition that is uncertain or of unproven origin; the live field draws it as the draft's body (#3699). */ +export const UNCLEAR_NOTICE = "I couldn't hear that clearly. Review before sending."; +/** + * Notices about the held draft itself: the client cannot send it as heard. + * The live field draws them in place of the draft's words (#3699). + */ +export const REVIEW_BOUNDED_NOTICE = "Only bounded recognition context remains. Review retained dialogue and send typed text instead."; +export const REVIEW_TRIMMED_NOTICE = "Only recent recognition remains in the review buffer. Review retained dialogue before sending typed text."; +/** Capture is waiting for voice to become ready: the live field says "mic off" for these (#3699). */ +export const READINESS_NOTICES = { + connection: "Waiting for the voice connection. Microphone off.", + ready: "Waiting for voice readiness. Microphone off.", + resync: "Synchronizing voice. Microphone off.", +} as const; +/** Said by the field's own Muted word and pressed Mute (L7). */ +export const MUTED_NOTICE = "Microphone muted. Unmute to speak."; + // Local presentation metadata is neither wire state nor a public output field. const restoredOutputs = new WeakSet(); export const isRestoredConversationOutput = (output: ConversationClientOutput) => restoredOutputs.has(output); @@ -93,7 +117,7 @@ function outputInSession(output: ConversationClientOutput, sessionId: string) { /** Concrete root-owned orchestration; ordinary chat frames keep their existing path. */ export function createConversationClient(root: BrainUiServices, send: (message: ClientMessage) => boolean, answer: (sessionId: string | null, text: string) => boolean) { - const state = createStore(() => ({ available: false, active: false, token: 0, connection: "Connecting", micOn: false, interaction: "Listening", disclosureOpen: false, profile: null, conversationProfile: null, durableAvailable: false, sessionId: null, agentProviderId: null, text: "", voiceDraft: null, notice: "", announcement: "", playing: false, outputRecovery: "audible", work: {}, outputs: [], unassigned: [], recognition: [], unassignedWork: 0, dialogue: {}, dialogueNotice: "", dialogueRestoredThrough: {} })); + const state = createStore(() => ({ available: false, active: false, token: 0, connection: "Connecting", micOn: false, capture: "idle", interaction: "Listening", disclosureOpen: false, profile: null, conversationProfile: null, durableAvailable: false, sessionId: null, agentProviderId: null, text: "", voiceDraft: null, notice: "", announcement: "", playing: false, outputRecovery: "audible", work: {}, outputs: [], unassigned: [], recognition: [], unassignedWork: 0, dialogue: {}, dialogueNotice: "", dialogueRestoredThrough: {} })); let durableAvailable = false; let dialoguePrincipalKey:string|undefined; const dialogueReads = new Map(); @@ -124,6 +148,15 @@ export function createConversationClient(root: BrainUiServices, send: (message: let ready = false; let resync = 0; let consent = false; + // `keep` leaves a manual Mute authoritative across teardown and reconnects. + function setConsent(on: boolean, off: "keep" | "muted" | "stopped" | "idle" = "keep") { + consent = on; + const before = state.getState().capture; + const capture = on ? "listening" : off === "keep" ? (before === "muted" || before === "idle" ? before : "stopped") : off; + if (capture !== before) state.setState({ capture }); + } + // Display only: the newest microphone block's meter reading. + let inputLevel = 0; let agreedDisclosure: string | undefined; let agreedEntry: number | undefined; let draftId: string | null = null; @@ -255,7 +288,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: const key=liveScopeKey(); if(!key)return; if(storageFailedScope===key){if(code)storageFailureCode=code;return;} storageFailedScope=key; storageFailureCode=code ?? "DIALOGUE_STORAGE"; - consent=false; permissions.lost(); clearTimers(); resetRecovery(); stopMic(); playback.cut(); + setConsent(false, "stopped"); permissions.lost(); clearTimers(); resetRecovery(); stopMic(); playback.cut(); } function retainUnsaved(text: string): boolean { const current = state.getState(); @@ -332,7 +365,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: function requireCurrentDisclosure() { const profile = state.getState().conversationProfile; if (!state.getState().active || !profile || agreedDisclosure === undefined || agreedDisclosure === disclosureKey(profile)) return false; - consent = false; agreedEntry = undefined; entryLifetime++; + setConsent(false); agreedEntry = undefined; entryLifetime++; const changedEngine=scope()?.providerId !== profile.providerId; pause(false,true); if(changedEngine) state.setState({profile:null}); @@ -351,7 +384,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: state.setState({ playing, interaction: playing ? "Speaking" : answering ? "Answering question" : s.text ? (hold ? "Sending soon" : "Review before sending") : working || playback.pending() ? "Working" : "Listening" }); } function clearTimers() { clearTimeout(silence); clearTimeout(hold); clearTimeout(finalization); silence = hold = finalization = undefined; } - function stopMic() { mic?.stop(); mic = undefined; state.setState({ micOn: false }); } + function stopMic() { mic?.stop(); mic = undefined; inputLevel = 0; state.setState({ micOn: false }); } function saveDraft() { if (!draftId || reviewIsIncomplete()) return; // Interim recognition is never retained. Unknown finality is the explicit @@ -386,7 +419,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: playback.quiet(false); const profile = scope(); if (profile && notify) send({ type: "conversation_stop", conversationId: profile.conversationId, ...(resumable ? { resumable: true } : {}) }); - ready = false; consent = false; requested = false; + ready = false; setConsent(false); requested = false; state.setState({ connection: lost ? "Speech lost" : "Reconnecting", notice: closedNotice || (lost ? "Speech lost. Microphone off; reply outcome unknown until reconnect." : "Microphone off. Resume when voice is ready.") }); announce(lost ? "Speech lost. Chat is still connected." : "Microphone off"); } @@ -395,10 +428,11 @@ export function createConversationClient(root: BrainUiServices, send: (message: function suspend() { if (!state.getState().active) return; const retainedConsent = consent; + const retainedCapture = state.getState().capture; pause(true); openingId = undefined; consent = retainedConsent; - state.setState({ notice: closedNotice || (retainedConsent ? "Voice temporarily unavailable. Listening will recover in the same disclosed scope." : "Voice temporarily unavailable. Microphone remains muted.") }); + state.setState({ capture: retainedCapture, notice: closedNotice || (retainedConsent ? "Voice temporarily unavailable. Listening will recover in the same disclosed scope." : "Voice temporarily unavailable. Microphone remains muted.") }); } function dialogueDiagnostic(code: "DIALOGUE_UNAVAILABLE" | "DIALOGUE_STORAGE" | "DIALOGUE_PENDING_PRESSURE" | "DIALOGUE_INDETERMINATE") { const notices = { @@ -470,16 +504,17 @@ export function createConversationClient(root: BrainUiServices, send: (message: if (!state.getState().active || !consent || !profile || mic || (typeof document !== "undefined" && document.hidden)) return; const reason = storageFailedScope === liveScopeKey() ? dialogueDiagnostic(storageFailureCode ?? "DIALOGUE_STORAGE") : state.getState().disclosureOpen ? "Review the voice service disclosure. Microphone off." - : state.getState().connection !== "Connected" ? "Waiting for the voice connection. Microphone off." - : !ready ? "Waiting for voice readiness. Microphone off." - : resync !== 0 ? "Synchronizing voice. Microphone off." : ""; + : state.getState().connection !== "Connected" ? READINESS_NOTICES.connection + : !ready ? READINESS_NOTICES.ready + : resync !== 0 ? READINESS_NOTICES.resync : ""; if (reason) { state.setState({ notice: reason }); return; } const own = generation; const input = inputFormat; if (!input) return; state.setState({ notice: "Opening microphone. Check browser permission if prompted." }); - const captureSession = openConversationMicrophone(input.sampleRate, (pcm, speaking) => { + const captureSession = openConversationMicrophone(input.sampleRate, (pcm, speaking, level) => { if (!current(own) || mic !== captureSession) return; + inputLevel = level; if (speaking) { finalAfterSpeech = false; lastSpeech = performance.now(); @@ -502,11 +537,12 @@ export function createConversationClient(root: BrainUiServices, send: (message: mic = captureSession; try { await captureSession.ready; } catch (error) { if (current(own) && mic === captureSession) { - stopMic(); consent = false; + stopMic(); setConsent(false, "stopped"); const name = error instanceof DOMException ? error.name : ""; - state.setState({ notice: name === "NotAllowedError" ? "Microphone permission denied. Allow it in the browser, then unmute." - : name === "NotFoundError" ? "No microphone found. Connect one, then unmute." - : "Microphone could not be opened. Check the device and browser, then unmute." }); + // Capture has stopped (L9), whose action is Start again (#3699). + state.setState({ notice: name === "NotAllowedError" ? "Microphone is blocked. Allow it in this site’s browser settings, then Start again." + : name === "NotFoundError" ? "No microphone found. Connect one, then Start again." + : "Microphone could not be opened. Check the device and browser, then Start again." }); } } } function endpoint(own: number) { @@ -540,7 +576,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: } function commit(own: number) { if (reviewIsIncomplete()) { - state.setState({notice:"Only bounded recognition context remains. Review retained dialogue and send typed text instead."}); return false; + state.setState({notice:REVIEW_BOUNDED_NOTICE}); return false; } const s = state.getState(); const profile = scope(); @@ -593,7 +629,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: /** Principal/auth boundaries drop all volatile evidence and old callback identities. */ function clearPrivateDialogue() { unassignedWorkOwners.length = 0; - entryLifetime++; generation++; consent=false; ready=false; requested=false; openingId=undefined; + entryLifetime++; generation++; setConsent(false, "idle"); ready=false; requested=false; openingId=undefined; // Retire the source before cutting playback: no old identity is sent on a new principal socket. state.setState({active:false,profile:null}); clearTimers(); resetRecovery(); stopMic(); playback.cut(); @@ -809,7 +845,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: clearClosedNotice(); generation++; state.setState({ token: generation }); stopMic(); resetRecovery(); playback.dispose(); playback = makePlayback(); fragments.clear(); unassignedThrough = -1; seenRecognition.clear(); retiredInputs.clear(); capturedInputs.clear(); manualReview.clear(); incompleteReview.clear(); lastInput = undefined; state.setState({ profile: message, connection: "Connected", text: "", interaction: "Listening", disclosureOpen: agreedEntry !== entryLifetime || agreedDisclosure !== disclosureKey(message, message.agentProviderId ?? entryProfileId) }); - if (agreedEntry !== entryLifetime || agreedDisclosure !== disclosureKey(message, message.agentProviderId ?? entryProfileId)) consent = false; + if (agreedEntry !== entryLifetime || agreedDisclosure !== disclosureKey(message, message.agentProviderId ?? entryProfileId)) setConsent(false); resync = message.resync.work + message.resync.outputs; ready = false; if (consent) void capture(); return null; @@ -861,7 +897,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: while (unassigned.length > CONVERSATION_LIMITS.maxFragmentsPerUtterance || reviewChars > CONVERSATION_LIMITS.maxUtteranceChars) { reviewChars-=unassigned.shift()!.text.length; trimmed=true; } - state.setState({unassigned:[...retained.filter(f => f.taskContext),...unassigned],...(trimmed ? {notice:"Only recent recognition remains in the review buffer. Review retained dialogue before sending typed text."} : {})}); + state.setState({unassigned:[...retained.filter(f => f.taskContext),...unassigned],...(trimmed ? {notice:REVIEW_TRIMMED_NOTICE} : {})}); return null; } if (event.kind === "unassigned_delegation") { @@ -900,10 +936,10 @@ export function createConversationClient(root: BrainUiServices, send: (message: incompleteReview.add(event.utteranceId); manualReview.add(event.utteranceId); } const text = [...fragments.values()].flatMap((f) => [...f.values()].sort((a, b) => a.sequence - b.sequence).map((f) => f.text)).join(" ").trim(); - state.setState({ text, notice: event.certainty === "unknown" || event.origin !== "user" ? "I couldn't hear that clearly. Review before sending." : s.notice }); + state.setState({ text, notice: event.certainty === "unknown" || event.origin !== "user" ? UNCLEAR_NOTICE : s.notice }); if (reviewIsIncomplete()) { removeSavedDraft(); clearTimeout(hold); hold=undefined; - state.setState({notice:"Only bounded recognition context remains. Review retained dialogue and send typed text instead."}); + state.setState({notice:REVIEW_BOUNDED_NOTICE}); refresh(); return null; } saveDraft(); @@ -999,17 +1035,17 @@ export function createConversationClient(root: BrainUiServices, send: (message: // A new entry needs Start even when the service matches the last visit. agreedDisclosure = undefined; root.stores.voice.getState().setMode("conversation"); - agreedEntry = undefined; consent = false; permissions.refresh(); + agreedEntry = undefined; setConsent(false, "idle"); permissions.refresh(); }, start() { const profile = state.getState().conversationProfile; if (!state.getState().active || !profile || (typeof document !== "undefined" && document.hidden) || root.stores.connection.getState().wsStatus !== "connected") return; - agreedDisclosure = disclosureKey(profile); agreedEntry = entryLifetime; consent = true; + agreedDisclosure = disclosureKey(profile); agreedEntry = entryLifetime; setConsent(true); state.setState({ disclosureOpen: false }); startEpoch(); void capture(); }, details() { state.setState({ disclosureOpen: true }); }, - resume() { if (state.getState().disclosureOpen) return; consent = true; if (!ready) startEpoch(); void capture(); }, - mute() { consent = false; if (ready && mic) endpoint(generation); clearTimers(); stopMic(); state.setState({ notice: "Microphone muted. Unmute to speak." }); playback.quiet(true); permissions.refresh(); announce("Microphone off"); }, + resume() { if (state.getState().disclosureOpen) return; setConsent(true); if (!ready) startEpoch(); void capture(); }, + mute() { setConsent(false, "muted"); if (ready && mic) endpoint(generation); clearTimers(); stopMic(); state.setState({ notice: MUTED_NOTICE }); playback.quiet(true); permissions.refresh(); announce("Microphone off"); }, commit, reviewUnassigned() { const s = state.getState(); @@ -1037,6 +1073,8 @@ export function createConversationClient(root: BrainUiServices, send: (message: refresh(); }, stopReply, leave, + /** Display-only meter readings: the newest microphone block and what plays now. */ + levels: () => ({ input: mic ? inputLevel : 0, output: playback.level() }), dispose() { leave(); disposed = true; unwatchChat(); unwatchDrafts(); unwatchProvider(); unwatchConnection(); unwatchAuth(); playback.dispose(); if (typeof document !== "undefined") document.removeEventListener("visibilitychange", hidden); requests.clear(); contextualWork.clear(); unassignedWorkOwners.length = 0; }, }; } diff --git a/packages/ui-react/src/voice/conversation-pcm.ts b/packages/ui-react/src/voice/conversation-pcm.ts index de4da868e5..711b14e958 100644 --- a/packages/ui-react/src/voice/conversation-pcm.ts +++ b/packages/ui-react/src/voice/conversation-pcm.ts @@ -1,9 +1,17 @@ import type { ConversationAudioFormat, ConversationPlayback } from "@schlessera/brain-ui-sdk/protocol"; import { openPcmMicrophone, pcm16Bytes } from "./pcm-capture.js"; +/** + * A 0–1 meter reading from a block's RMS amplitude. Display only: it never + * gates capture, endpointing or playback evidence. + */ +function meterLevel(rms: number) { + return Math.max(0, Math.min(1, rms / 0.25)); +} + /** Concrete browser PCM transport. No recorder codec or independent speech service. */ -export function openConversationMicrophone(rate: number, receive: (pcm: Uint8Array, speaking: boolean) => void, opened: () => void, interrupted: () => void) { - return openPcmMicrophone(rate, (pcm, rms) => receive(pcm16Bytes(pcm), rms > 0.015), opened, interrupted); +export function openConversationMicrophone(rate: number, receive: (pcm: Uint8Array, speaking: boolean, level: number) => void, opened: () => void, interrupted: () => void) { + return openPcmMicrophone(rate, (pcm, rms) => receive(pcm16Bytes(pcm), rms > 0.015, meterLevel(rms)), opened, interrupted); } /** One queue owns all local output, including chunks waiting for a quiet boundary. */ @@ -13,7 +21,8 @@ export function createConversationPlayback(report: (outputId: string, state: Con let availableAt = 0; let blocked = true; const waiting: { outputId: string; bytes: Uint8Array; format: ConversationAudioFormat }[] = []; - const live = new Map(); + // `levels` holds one meter reading per 10 ms window from `start`. + const live = new Map(); let boundary: ReturnType | undefined; // PCM magnitude cannot prove physical audibility. Only digital silence is // excluded: every nonzero sample conservatively protects a 10 ms window. @@ -50,9 +59,13 @@ export function createConversationPlayback(report: (outputId: string, state: Con source.connect(context.destination); availableAt = Math.max(context.currentTime, availableAt); const audible: [number, number][] = []; + const levels: number[] = []; const window = Math.max(1, Math.round(chunk.format.sampleRate / 100)); for (let offset = 0; offset < samples.length; offset += window) { const end = Math.min(offset + window, samples.length); + let energy = 0; + for (let i = offset; i < end; i++) energy += samples[i]! * samples[i]!; + levels.push(meterLevel(Math.sqrt(energy / (end - offset)))); if (!samples.subarray(offset, end).some(sample => sample !== 0)) continue; const startTime = availableAt + offset / chunk.format.sampleRate; const endTime = availableAt + end / chunk.format.sampleRate; @@ -60,7 +73,7 @@ export function createConversationPlayback(report: (outputId: string, state: Con if (previous && previous[1] === startTime) previous[1] = endTime; else audible.push([startTime, endTime]); } - live.set(source, { outputId: chunk.outputId, audible }); + live.set(source, { outputId: chunk.outputId, audible, start: availableAt, step: window / chunk.format.sampleRate, levels }); touched.add(chunk.outputId); const own = generation; source.onended = () => { @@ -99,6 +112,16 @@ export function createConversationPlayback(report: (outputId: string, state: Con pending: () => waiting.length > 0 || live.size > 0, playing: () => playingIds().length > 0, playingIds, + /** The reading of whatever sounds now, for the meter only. */ + level() { + if (context?.state !== "running") return 0; + const now = context.currentTime; + for (const item of live.values()) { + const at = Math.floor((now - item.start) / item.step); + if (at >= 0 && at < item.levels.length) return item.levels[at]!; + } + return 0; + }, // A local floor/tone flush cannot retire an epoch-wide provider identity. // Only cancellation/teardown rejects later chunks with the same identity. flush() { flush(false); }, diff --git a/packages/ui-react/src/voice/conversation-permissions.ts b/packages/ui-react/src/voice/conversation-permissions.ts index 12d71de8c1..da7b6b97cd 100644 --- a/packages/ui-react/src/voice/conversation-permissions.ts +++ b/packages/ui-react/src/voice/conversation-permissions.ts @@ -17,6 +17,9 @@ export interface VoicePermissionReceipt { postureDenied?: true; } +/** The strip line while this turn's approvals wait for a tap; the live field draws its own copy for it (#3699). */ +export const PERMISSION_PENDING_LINE = "Use Deny on screen · voice can’t approve or refuse with this service"; + /** Concrete permission routing. Exact-copy speech is absent, so only a local earcon is queued. */ export function createConversationPermissions(root: BrainUiServices, send: (message: ClientMessage) => boolean, selected: () => { active: boolean; sessionId: string | null; micOn: boolean; quiet: boolean; isolated: boolean }, earcon: () => void, overflow: () => void) { @@ -41,7 +44,7 @@ export function createConversationPermissions(root: BrainUiServices, send: (mess // not prove user attribution; keep the scoped input guard and direct decisions // to the screen until a separately qualified capability can support this copy. function publish() { - state.setState({ records: [...records.values()], line: full ? "Use Deny on screen; the voice request limit was reached." : pending().length ? "Use Deny on screen · voice can’t approve or refuse with this service" : "" }); + state.setState({ records: [...records.values()], line: full ? "Use Deny on screen; the voice request limit was reached." : pending().length ? PERMISSION_PENDING_LINE : "" }); apply(); } function put(receipt: VoicePermissionReceipt) { diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-1-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-1-chromium-linux.png index 388ace5a3b..d4a78d10cb 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-1-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-1-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-2-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-2-chromium-linux.png index f819c558e5..78b5f450d3 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-2-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-dark-2-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-1-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-1-chromium-linux.png index 3e18b55ce9..2663a754c9 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-1-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-1-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-2-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-2-chromium-linux.png index 13c341968a..51a2afae95 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-2-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/interruption-light-2-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-body-dark-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-body-dark-chromium-linux.png new file mode 100644 index 0000000000..1793bbe698 Binary files /dev/null and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-body-dark-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-body-light-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-body-light-chromium-linux.png new file mode 100644 index 0000000000..055d970e33 Binary files /dev/null and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-body-light-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-review-dark-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-review-dark-chromium-linux.png deleted file mode 100644 index c34ac94987..0000000000 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-review-dark-chromium-linux.png and /dev/null differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-review-light-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-review-light-chromium-linux.png deleted file mode 100644 index c475fc05c9..0000000000 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/notice-review-light-chromium-linux.png and /dev/null differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/output-muted-draft-dark-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/output-muted-draft-dark-chromium-linux.png new file mode 100644 index 0000000000..12adc74436 Binary files /dev/null and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/output-muted-draft-dark-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/output-muted-draft-light-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/output-muted-draft-light-chromium-linux.png new file mode 100644 index 0000000000..6744d85f55 Binary files /dev/null and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/output-muted-draft-light-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-1-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-1-chromium-linux.png index 081d7890cb..07a11a492d 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-1-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-1-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-2-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-2-chromium-linux.png index cd5ad81d01..2812a068fd 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-2-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-dark-2-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-1-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-1-chromium-linux.png index b6b0da5130..d158c23aeb 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-1-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-1-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-2-chromium-linux.png b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-2-chromium-linux.png index 57110db657..c397c32fe4 100644 Binary files a/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-2-chromium-linux.png and b/packages/ui-react/tests/browser/__screenshots__/conversation-controls.offline.tsx/review-permission-light-2-chromium-linux.png differ diff --git a/packages/ui-react/tests/browser/conversation-continuous.offline.tsx b/packages/ui-react/tests/browser/conversation-continuous.offline.tsx index 6bde01c1e0..d392d23443 100644 --- a/packages/ui-react/tests/browser/conversation-continuous.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-continuous.offline.tsx @@ -166,7 +166,7 @@ for (const provider of ["gemini", "gpt"] as const) test(`${provider} contextual const s = await contextualScene(ctx, provider, "permitted", 320); const { recognition, generated } = await discuss(s, provider); for (const afterLeave of [false, true]) { - if (afterLeave) { await userEvent.click(s.button("Leave voice")); await s.pump(); } + if (afterLeave) { await userEvent.click(s.button("End")); await s.pump(); } await expect.poll(() => s.host.querySelector('[aria-label="Voice review controls"]'), { message: "CONTEXT_IS_DISCUSSION_NOT_UNSENT" }).toBeNull(); expect(s.button("Review in composer")).toBeUndefined(); expect(s.host.textContent).not.toContain("voice fragments weren't sent"); diff --git a/packages/ui-react/tests/browser/conversation-controls.offline.tsx b/packages/ui-react/tests/browser/conversation-controls.offline.tsx index 5e6501ba45..757c37d1c7 100644 --- a/packages/ui-react/tests/browser/conversation-controls.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-controls.offline.tsx @@ -41,66 +41,89 @@ async function scene(ctx: TestContext, width: number, height: number, theme: "li const client = ui.connection.conversation; const deliver = (message: ServerMessage) => network.socket()!.deliver(message); const capture = async (name: string) => { await page.screenshot({ element: host, path: `../../.vitest-attachments/conversation-controls/${theme}-${width}-${height}-${scale}-${name}.png` }); }; - const active = () => flushSync(() => client.state.setState({ active: true, sessionId: SESSION, connection: "Connected", profile: PROFILE, disclosureOpen: false })); - const strip = () => host.querySelector('[data-conversation-strip]')!; + const active = () => flushSync(() => client.state.setState({ active: true, sessionId: SESSION, connection: "Connected", capture: "listening", profile: PROFILE, disclosureOpen: false })); + const strip = () => host.querySelector('[data-conversation-field]')!; + const control = (name: string) => strip().querySelector(`button[aria-label="${name}"]`)!; + const word = () => strip().querySelector('[data-voice-word]')?.textContent; + const controls = () => [...strip().querySelectorAll(".bk-voice-field button")].map(node => node.getAttribute("aria-label")); + /** The connected clock ticks in real time; a baseline masks it, never the other meta. */ + const shot = () => ({ screenshotOptions: { mask: [...strip().querySelectorAll(".bk-voice-label-meta")].filter(node => /\d:\d\d$/.test(node.textContent ?? "")) } }); + /** The field holds its body and controls at 1× and doubled text (#3773), and every control takes its own taps. */ + const contained = (field: HTMLElement, what: string) => { + expect(field.scrollHeight, `${what} cannot overlap the controls`).toBeLessThanOrEqual(field.clientHeight + 1); + for (const control of field.querySelectorAll("button")) { + const box = control.getBoundingClientRect(); + expect(document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2)?.closest("button"), `${what}: ${control.getAttribute("aria-label")} stays reachable`).toBe(control); + } + }; + /** Rows of the live surface other than the field itself and its screen-reader region (#3699: none). */ + const stacked = () => [...strip().children].filter(node => !node.classList.contains("sr-only") && !node.querySelector(".bk-voice-field") && node.tagName !== "DIALOG").map(node => node.outerHTML.slice(0, 80)); if (scale !== 1) { // Text-only enlargement exercises wrapping independently of viewport zoom. - const large = document.createElement("style"); large.textContent = `[data-conversation-strip] { font-size:${12 * scale}px } [data-conversation-strip] :is(div,button,[role=button]) { font-size:inherit !important; line-height:1.3 !important }`; + const large = document.createElement("style"); large.textContent = `[data-conversation-field] { font-size:${12 * scale}px } [data-conversation-field] :is(div,button,[role=button]) { font-size:inherit !important; line-height:1.3 !important }`; document.head.append(large); ctx.onTestFinished(() => large.remove()); } - return { ui, client, host, deliver, capture, active, strip, network }; + return { ui, client, host, deliver, capture, active, strip, control, controls, stacked, shot, contained, word, network, scale }; } for (const theme of ["light", "dark"] as const) for (const [width, height, scale] of [[1280, 720, 1], [320, 568, 1], [320, 480, 2]] as const) test(`control audit ${theme} ${width}x${height} text ${scale}`, async ctx => { const s = await scene(ctx, width, height, theme, scale); s.active(); - for (const [name, connection, interaction, micOn, playing] of [ - ["connecting", "Connecting", "Listening", false, false], - ["listening", "Connected", "Listening", true, false], - ["muted", "Connected", "Listening", false, false], - ["working", "Connected", "Working", false, false], - ["speaking", "Connected", "Speaking", false, true], - ["interruption", "Reconnecting", "Checking whether the reply stopped", false, false], - ["reconnect", "Speech lost", "Listening", false, false], + for (const [name, connection, interaction, micOn, playing, capture, state] of [ + ["connecting", "Connecting", "Listening", false, false, "listening", "S5"], + ["listening", "Connected", "Listening", true, false, "listening", "L1"], + ["muted", "Connected", "Listening", false, false, "muted", "L7"], + ["working", "Connected", "Working", true, false, "listening", "L2"], + ["speaking", "Connected", "Speaking", false, true, "listening", "L4"], + ["interruption", "Reconnecting", "Checking whether the reply stopped", false, false, "listening", "L8"], + ["reconnect", "Speech lost", "Listening", false, false, "listening", "L8"], + ["stopped", "Speech lost", "Listening", false, false, "stopped", "L9"], ] as const) { - flushSync(() => s.client.state.setState({ connection, interaction, micOn, playing, notice: name === "reconnect" ? "Speech connection lost. Resume when ready." : "" })); + flushSync(() => s.client.state.setState({ connection, interaction, micOn, playing, capture, notice: name === "reconnect" || name === "stopped" ? "Speech connection lost. Resume when ready." : "" })); + expect(s.strip().dataset.liveState, name).toBe(state); // Pin keyboard modality and focus; earlier test input must not change a baseline's ring. - if (name === "interruption") { s.strip().querySelector('[aria-label="Voice service details"]')!.focus(); await userEvent.keyboard("{ArrowRight}"); } + if (name === "interruption") { s.control("Mute").focus(); await userEvent.keyboard("{ArrowRight}"); } await s.capture(name); - if (name === "interruption" && width === 320) await expect(page.elementLocator(s.strip())).toMatchScreenshot(`interruption-${theme}-${scale}`); - const status = s.strip().children[1] as HTMLElement; - expect(status.scrollHeight, `${name}: status must not paint over the next row`).toBeLessThanOrEqual(status.clientHeight + 1); + if (name === "interruption" && width === 320) await expect(page.elementLocator(s.strip())).toMatchScreenshot(`interruption-${theme}-${scale}`, s.shot()); + const field = s.strip().querySelector(".bk-voice-field")!; + s.contained(field, name); expect(s.strip().scrollWidth, `${name}: no horizontal overflow`).toBeLessThanOrEqual(s.strip().clientWidth); for (const control of s.strip().querySelectorAll('button,[role=button]')) { expect(control.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); expect(control.scrollWidth, `${name}: full control label`).toBeLessThanOrEqual(control.clientWidth + 1); } } - flushSync(() => s.client.state.setState({ connection: "Connected", interaction: "Review before sending", micOn: false, notice: "", text: "Ask Nestor about the departure, the harbour supplies and the next meeting before sailing." })); + flushSync(() => s.client.state.setState({ connection: "Connected", capture: "listening", interaction: "Review before sending", micOn: false, notice: "", text: "Ask Nestor about the departure, the harbour supplies and the next meeting before sailing." })); s.deliver({ type: "text_delta", sessionId: SESSION, turnId: "ithaca-turn", text: "The departure note needs review." }); s.deliver({ type: "tool_approval_request", sessionId: SESSION, turnId: "ithaca-turn", toolUseId: "ithaca-write", toolName: "Write", kind: "tool", input: { file_path: "voyage/raft.md", content: "Review the raft supplies" } }); await expect.poll(() => s.host.querySelector('[data-approval-card]')).not.toBe(null); - s.strip().querySelector('[aria-label="Voice service details"]')!.focus(); await userEvent.keyboard("{ArrowRight}"); + await expect.poll(() => s.strip().dataset.liveState, { message: "a pending approval card is L6" }).toBe("L6"); + s.control("Mute").focus(); await userEvent.keyboard("{ArrowRight}"); await s.capture("review-permission"); - if (width === 320) await expect(page.elementLocator(s.strip())).toMatchScreenshot(`review-permission-${theme}-${scale}`); - const line = s.strip().querySelector('[data-voice-refusal-window]')!; - expect(line.scrollHeight, "permission guidance cannot overlap controls under enlarged text").toBeLessThanOrEqual(line.clientHeight + 1); - expect(line.textContent).toContain("Use Deny on screen"); - expect(line.textContent).not.toContain("unmute to refuse"); + if (width === 320) await expect(page.elementLocator(s.strip())).toMatchScreenshot(`review-permission-${theme}-${scale}`, s.shot()); + // Nothing stacks above the field: the draft holds its body, the refusal window marks the field (#3699). + expect(s.strip().hasAttribute("data-voice-refusal-window"), "the refusal window is open").toBe(true); + expect(s.stacked(), "no row renders above the field").toEqual([]); + expect(s.strip().querySelector(".bk-voice-label-meta")?.textContent).toBe("Draft · not sent yet"); + expect(s.strip().querySelector('[data-conversation-review]')?.textContent).toBe("Ask Nestor about the departure, the harbour supplies and the next meeting before sailing."); + expect(s.controls(), "R1 and L6_NO_VOICE_GRANT: a held draft replaces Interrupt; nothing grants").toEqual(["Mute", "Discard draft", "Send now", "End"]); + const voiceField = s.strip().querySelector(".bk-voice-field")!; + s.contained(voiceField, "the draft"); flushSync(() => s.client.state.setState({ micOn: true })); s.client.permissions.refresh(); expect(s.client.permissions.state.getState().line).not.toContain("brain, stop"); flushSync(() => s.client.state.setState({ micOn: false })); expect(s.client.permissions.state.getState().records[0]?.script).not.toContain("unmute to refuse"); - const review = s.strip().querySelector('[data-conversation-review]')!; - expect(page.getByRole("region", { name: "Unsent voice transcript" }).element()).toBe(review); - s.strip().querySelector('[aria-label="Voice service details"]')!.focus(); - await userEvent.keyboard("{Tab}"); - expect(document.activeElement, "Tab reaches the review after service details").toBe(review); - const beforeScroll = review.scrollTop; - await userEvent.keyboard("{ArrowDown}"); - if (review.scrollHeight > review.clientHeight) await expect.poll(() => review.scrollTop).toBeGreaterThan(beforeScroll); - expect(document.activeElement).toBe(review); - expect(getComputedStyle(review).outlineStyle).not.toBe("none"); + page.getByRole("button", { name: "Send now", exact: true }).element().focus(); + await userEvent.keyboard("{Shift>}{Tab}{/Shift}"); + expect(document.activeElement, "the keyboard reaches Discard draft before Send now").toBe(s.control("Discard draft")); + // Without a draft, the refusal line is the body (L6), with nothing to say to approve. + const held = s.client.state.getState().text; + flushSync(() => s.client.state.setState({ text: "" })); + expect(s.strip().querySelector("[data-voice-text]")?.textContent).toBe("Tap Allow or Deny on the card. Voice can’t approve or refuse with this service."); + expect(s.strip().textContent).not.toContain("unmute to refuse"); + expect(s.controls()).toEqual(["Mute", "Interrupt", "End"]); + s.contained(voiceField, "the refusal line"); + flushSync(() => s.client.state.setState({ text: held })); await userEvent.click(page.getByRole("button", { name: /^Deny/ })); expect(s.network.socket()!.frames("tool_denial")).toHaveLength(1); expect(s.network.socket()!.frames("tool_denial")[0]?.channel).toBe("card"); @@ -140,7 +163,9 @@ for (const theme of ["light", "dark"] as const) test(`entry and connecting discl expect(s.network.socket()!.frames("conversation_start")[0]!.disclosed).toEqual(DISCLOSED_PROFILE); expect(s.client.state.getState().connection,"PROVIDER_OPENING_IS_STILL_PENDING").toBe("Connecting"); expect(s.client.state.getState().profile).toBe(null);expect(s.client.state.getState().micOn).toBe(false); - await userEvent.click(page.getByRole("button",{name:"Voice service details",exact:true})); + expect(s.strip().dataset.liveState, "a pending opening draws Connecting (S5)").toBe("S5"); + expect(s.control("Mute").disabled, "nothing to mute while connecting").toBe(true); + flushSync(() => s.client.details()); await expect.poll(()=>s.client.state.getState().disclosureOpen).toBe(true); await s.capture("pending-connecting-disclosure"); // A known destination is not enough when the host connection is unavailable. @@ -244,67 +269,64 @@ for (const theme of ["light", "dark"] as const) for (const [width, height] of [[ }); // Capture/readiness diagnostics remain actionable alongside an unsent draft. +// The body holds one message: draft → refusal → output muted → client notice (#3699). for (const theme of ["light", "dark"] as const) for (const [width, height, scale] of [[1280, 720, 1], [320, 568, 1], [320, 480, 2]] as const) test(`notice with review ${theme} ${width}x${height} text ${scale}`, async ctx => { const s = await scene(ctx, width, height, theme, scale); s.active(); const text = "Ask Nestor to review the harbour supplies before sailing."; flushSync(() => s.client.state.setState({ micOn: false, text, interaction: "Review before sending" })); - s.deliver({ type: "text_delta", sessionId: SESSION, turnId: "notice-turn", text: "The supplies need review." }); - s.deliver({ type: "tool_approval_request", sessionId: SESSION, turnId: "notice-turn", toolUseId: "notice-write", toolName: "Write", kind: "tool", input: { file_path: "voyage/raft.md", content: "Review supplies" } }); - await expect.poll(() => s.host.querySelector('[data-approval-card]')).not.toBe(null); - const details = s.strip().querySelector('[aria-label="Voice service details"]')!; - details.focus(); - for (const notice of [ - "Microphone input ended. Check the device, then resume.", - "Waiting for voice readiness. Microphone off.", - "Synchronizing voice. Microphone off.", - "Microphone off while checking the reply stop. Resume when voice is ready.", - "Microphone permission denied. Allow it in the browser, then unmute.", - "Speech input could not be matched to captured audio. Microphone off; review before resuming.", - "I couldn't hear that clearly. Review before sending.", - ]) { - flushSync(() => s.client.state.setState({ connection: "Speech lost", notice })); - expect(s.strip().textContent, "capture-off reason remains present beside review text").toContain(notice); - const diagnostic = page.getByRole("status", { name: "Voice notice" }); - await expect.element(diagnostic).toHaveTextContent(notice); - const node = diagnostic.element() as HTMLElement; - expect(node.textContent).toBe(notice); - expect(s.strip().textContent?.split(notice)).toHaveLength(2); - expect(s.strip().querySelector('[data-conversation-review]')?.textContent).toContain(text); - expect(document.activeElement, "a diagnostic must not steal focus").toBe(details); - const status = s.strip().children[1] as HTMLElement; - expect(status.scrollHeight, "diagnostic wraps within its growing row").toBeLessThanOrEqual(status.clientHeight + 1); - expect(node.scrollWidth).toBeLessThanOrEqual(node.clientWidth + 1); - expect(node.scrollHeight).toBeLessThanOrEqual(node.clientHeight + 1); + flushSync(() => s.client.state.setState({ connection: "Speech lost" })); + const mute = s.control("Mute"); + const body = () => s.strip().querySelector("[data-voice-text]")?.textContent; + const meta = () => s.strip().querySelector(".bk-voice-label-meta")?.textContent; + const field = () => s.strip().querySelector(".bk-voice-field")!; + for (const [notice, line, qualifier] of [ + ["Microphone input ended. Check the device, then resume.", "Microphone input ended. Check the device, then resume.", undefined], + ["Waiting for voice readiness. Microphone off.", "Waiting for voice to be ready. Nothing is heard until then.", "mic off"], + ["Synchronizing voice. Microphone off.", "Waiting for voice to be ready. Nothing is heard until then.", "mic off"], + ["Microphone off while checking the reply stop. Resume when voice is ready.", "Microphone off while checking the reply stop. Resume when voice is ready.", undefined], + ["Speech input could not be matched to captured audio. Microphone off; review before resuming.", "Speech input could not be matched to captured audio. Microphone off; review before resuming.", undefined], + ] as const) { + flushSync(() => s.client.state.setState({ connection: "Speech lost", notice, text })); + mute.focus(); + expect(s.strip().dataset.liveState, "a recoverable loss with retained consent is Reconnecting").toBe("L8"); + expect(body(), "the held draft outranks a client notice").toBe(text); + expect(meta()).toBe("Draft · not sent yet"); + expect(s.strip().textContent?.includes(notice), "one message at a time").toBe(false); + flushSync(() => s.client.state.setState({ text: "" })); + expect(body(), notice).toBe(line); + if (qualifier) expect(meta(), "readiness says the microphone is off").toBe(qualifier); + else expect(meta()).toMatch(/^GPT-Live · \d+:\d\d$/); + expect(s.control("Mute").disabled, "nothing to mute while voice is not ready").toBe(!!qualifier); + if (!qualifier) expect(document.activeElement, "a notice must not steal focus").toBe(mute); + s.contained(field(), notice); expect(s.strip().scrollWidth).toBeLessThanOrEqual(s.strip().clientWidth); + expect(s.stacked(), "no row renders above the field").toEqual([]); } - await userEvent.keyboard("{Tab}"); - const review = s.strip().querySelector('[data-conversation-review]')!; - expect(document.activeElement).toBe(review); - expect(getComputedStyle(review).outlineStyle).not.toBe("none"); - expect(page.getByRole("button", { name: "Send now", exact: true }).element().getAttribute("aria-disabled")).toBe("true"); - // A long diagnostic must not remove access to the host-owned permission card. - flushSync(() => s.client.state.setState({ notice: "Microphone input ended. Check the device, then resume.", connection: "Speech lost" })); - details.focus(); await userEvent.keyboard("{ArrowRight}"); - const diagnosticBounds = page.getByRole("status", { name: "Voice notice" }).element().getBoundingClientRect(); - const controls = page.getByRole("button", { name: "Resume microphone" }).element().getBoundingClientRect(); - expect(diagnosticBounds.top).toBeGreaterThanOrEqual(s.strip().getBoundingClientRect().top); - expect(diagnosticBounds.bottom, "the complete device notice fits above sticky controls").toBeLessThanOrEqual(controls.top); - if (scale === 2) { - // The reference captures hover plus keyboard focus. Pin both inputs: - // earlier permission-card clicks move when transcript arrival layout changes. - await userEvent.hover(details); - expect(details.matches(":hover")).toBe(true); - await expect(page.elementLocator(s.strip())).toMatchScreenshot(`notice-review-${theme}`); + await s.capture("notice"); + if (width === 320 && scale === 1) await expect(page.elementLocator(s.strip())).toMatchScreenshot(`notice-body-${theme}`, s.shot()); + // Unclear audio without a calibrated score: its line is the draft's body. + flushSync(() => s.client.state.setState({ connection: "Connected", notice: "I couldn't hear that clearly. Review before sending.", text })); + expect(body()).toBe("I couldn't hear that clearly. Review before sending."); + expect(meta()).toBe("Draft · not sent yet"); + expect(s.controls()).toEqual(["Mute", "Discard draft", "Send now", "End"]); + // Reply audio off outranks a client notice and keeps Recover in the row, even under a draft. + flushSync(() => s.client.state.setState({ outputRecovery: "muted", notice: "Reply audio is muted. Recover reply audio to listen; the microphone is unchanged." })); + expect(body(), "the draft still outranks it").toBe(text); + expect(s.controls(), "Recover stays while reply audio is off").toEqual(["Mute", "Recover reply audio", "Discard draft", "Send now", "End"]); + for (const control of s.strip().querySelectorAll("button")) { + expect(control.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); + expect(control.getBoundingClientRect().right).toBeLessThanOrEqual(field().getBoundingClientRect().right + 0.5); } - await s.capture("notice-review-permission"); - await userEvent.click(page.getByRole("button", { name: /^Deny/ })); - expect(s.network.socket()!.frames("tool_denial")).toHaveLength(1); - expect(s.network.socket()!.frames("tool_denial")[0]?.channel).toBe("card"); - expect(s.network.socket()!.frames("conversation_commit")).toHaveLength(0); + await s.capture("output-muted-draft"); + if (width === 320 && scale === 1) await expect(page.elementLocator(s.strip())).toMatchScreenshot(`output-muted-draft-${theme}`, s.shot()); flushSync(() => s.client.state.setState({ text: "" })); - await expect.element(page.getByRole("status", { name: "Voice notice" })).toHaveTextContent("Microphone input ended."); - flushSync(() => s.client.state.setState({ notice: "" })); + expect(body()).toBe("Brain’s voice was paused after a dropout. Replies still arrive as text."); + expect(meta()).toBe("Reply audio off"); + expect(s.controls()).toEqual(["Mute", "Recover reply audio", "End"]); + await s.capture("output-muted"); + flushSync(() => s.client.state.setState({ outputRecovery: "audible", notice: "" })); + expect(s.strip().querySelector("[data-voice-text]"), "no message, no body").toBe(null); expect(s.strip().querySelector('[role="status"]')).toBe(null); }); @@ -312,29 +334,30 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale for (const theme of ["light", "dark"] as const) for (const [width, height, scale] of [[1280, 720, 1], [320, 568, 1], [320, 480, 2]] as const) test(`reply windows keep controls stable ${theme} ${width}x${height} text ${scale}`, async ctx => { const s = await scene(ctx, width, height, theme, scale); s.active(); - flushSync(() => s.client.state.setState({ text: "Ask Nestor about the supplies.", interaction: "Review before sending", micOn: true, notice: "spoken portion unknown" })); - const names = ["Mute mic", "Stop reply", "Leave voice"]; - const controls = () => names.map(name => page.getByRole("button", { name, exact: true }).element() as HTMLElement); - expect(s.strip().textContent, "Stop reply keeps its place before playback starts").toContain("Stop reply"); + // No draft: R1 moves Interrupt out of a draft's row outside L4, which the field tests cover. + flushSync(() => s.client.state.setState({ text: "", interaction: "Review before sending", micOn: true, notice: "spoken portion unknown" })); + const names = ["Mute", "Interrupt", "End"]; + const controls = () => names.map(name => s.control(name)); + expect(s.control("Interrupt"), "Interrupt keeps its place before playback starts").not.toBe(null); const targets = controls(); const bounds = targets.map(node => node.getBoundingClientRect()); - expect(targets[1].getAttribute("aria-disabled")).toBe("true"); + expect(targets[1].disabled, "Interrupt is disabled outside L4").toBe(true); for (const box of bounds) { expect(box.height).toBeGreaterThanOrEqual(44); expect(box.width).toBeGreaterThanOrEqual(44); } // The strip holds Speaking for 300 ms after playback stops. That timer runs // on a fake clock, so each gap is exact rather than a real wait. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); ctx.onTestFinished(() => { vi.useRealTimers(); }); for (const gap of [10, 40, 100, 20]) { flushSync(() => s.client.state.setState({ playing: true, interaction: "Speaking" })); - await expect.element(page.getByRole("button", { name: "Stop reply", exact: true })).not.toHaveAttribute("aria-disabled", "true"); + await expect.poll(() => s.control("Interrupt").disabled).toBe(false); targets[0].focus(); await userEvent.keyboard("{Tab}"); - expect(document.activeElement, "Tab reaches Stop reply in its stable slot").toBe(targets[1]); + expect(document.activeElement, "Tab reaches Interrupt in its stable slot").toBe(targets[1]); flushSync(() => s.client.state.setState({ playing: false, interaction: gap === 40 ? "Listening" : "Review before sending" })); flushSync(() => vi.advanceTimersByTime(gap)); - expect(s.strip().children[1].textContent, "short PCM gaps retain Speaking feedback").toContain("Speaking"); + expect(s.word(), "short PCM gaps retain Speaking feedback").toBe("Speaking"); expect(s.client.state.getState().micOn, "display smoothing must not mute or resume capture").toBe(true); expect(s.client.state.getState().playing, "presentation must not alter sample-level state").toBe(false); - expect(targets[1].getAttribute("aria-disabled"), "Stop remains available across a short gap").not.toBe("true"); + expect(targets[1].disabled, "Interrupt remains available across a short gap").toBe(false); controls().forEach((node, index) => { const box = node.getBoundingClientRect(); expect([box.x, box.y, box.width, box.height], "control geometry stays fixed across PCM windows").toEqual([bounds[index].x, bounds[index].y, bounds[index].width, bounds[index].height]); @@ -346,13 +369,13 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale await s.capture("reply-gap"); flushSync(() => vi.runOnlyPendingTimers()); vi.useRealTimers(); - await expect.poll(() => targets[1].getAttribute("aria-disabled")).toBe("true"); - expect(s.strip().children[1].textContent).toContain("Review before sending"); + await expect.poll(() => targets[1].disabled).toBe(true); + expect(s.word()).toBe("Listening"); flushSync(() => s.client.state.setState({ playing: true, interaction: "Speaking" })); flushSync(() => s.client.state.setState({ playing: false, interaction: "Review before sending" })); flushSync(() => s.client.state.setState({ connection: "Speech lost", notice: "Speech connection lost. Resume when ready." })); - expect(s.strip().children[1].textContent, "connection loss is never smoothed away").toContain("Review before sending"); - expect(targets[1].getAttribute("aria-disabled")).toBe("true"); + expect(s.word(), "connection loss is never smoothed away").toBe("Reconnecting…"); + expect(targets[1].disabled).toBe(true); flushSync(() => s.client.state.setState({ connection: "Connected", notice: "", playing: true, interaction: "Speaking" })); flushSync(() => s.client.state.setState({ playing: false, interaction: "Review before sending" })); targets[0].focus(); @@ -360,9 +383,9 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale expect(document.activeElement).toBe(targets[1]); await userEvent.keyboard("{Enter}"); expect(s.client.state.getState().outputRecovery).not.toBe("audible"); - expect(s.strip().children[1].textContent, "explicit output stop takes precedence immediately").not.toContain("Speaking"); - expect(targets[1].getAttribute("aria-disabled")).toBe("true"); - expect(s.client.state.getState().micOn, "Stop reply preserves microphone intent").toBe(true); + expect(s.word(), "explicit output stop takes precedence immediately").not.toBe("Speaking"); + expect(targets[1].disabled).toBe(true); + expect(s.client.state.getState().micOn, "Interrupt preserves microphone intent").toBe(true); expect(s.network.socket()!.frames("conversation_audio")).toHaveLength(0); expect(s.network.socket()!.frames("conversation_commit")).toHaveLength(0); }); diff --git a/packages/ui-react/tests/browser/conversation-discard.offline.tsx b/packages/ui-react/tests/browser/conversation-discard.offline.tsx index 3046a0d4d1..77defec6af 100644 --- a/packages/ui-react/tests/browser/conversation-discard.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-discard.offline.tsx @@ -120,8 +120,11 @@ for (const consumed of ["submitted", "question", "permission", "lost-profile"] a if (consumed === "lost-profile") { s.deliver({ type: "error", code: "CONVERSATION_UNKNOWN", message: "Voice scope is unavailable." }); expect(s.client.state.getState().profile).toBe(null); - } - await userEvent.click(s.button("Discard")); + // A lost voice scope stops the conversation (L9): Close and Start again, the draft kept as a saved draft. + await expect.poll(() => s.host.querySelector("[data-conversation-field]")?.dataset.liveState).toBe("L9"); + expect(s.host.querySelector('[data-conversation-field] button[aria-label="Discard draft"]')).toBe(null); + flushSync(() => s.client.discard()); + } else await userEvent.click(s.button("Discard draft")); expect(s.client.state.getState().recognition.map(f => f.text), "Discard must retain earlier consumed recognition").toEqual([text, "Independent recognition."]); await expect.poll(() => [...s.host.querySelectorAll("[data-recognized-text]")].map(n => n.textContent)).toEqual([text, "Independent recognition."]); expect(transcriptTimelineFor(s.ui.stores.chat).state.getState().entries.some(e => e.key === firstEntry.key)).toBe(true); diff --git a/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx b/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx index 9c0c3284aa..801714c8fb 100644 --- a/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-endpoint.offline.tsx @@ -118,12 +118,12 @@ for (const action of ["send", "discard", "answer", "mute"] as const) for (const s.deliver({ type: "ask_user_request", sessionId: SESSION, turnId: "ithaca-turn", requestId: "ithaca-question", questions: [{ question: "Which day?", header: "Day", multiSelect: false, options: [{ label: "Tomorrow", description: "Before departure" }] }] }); } s.input("Tomorrow before departure"); - await expect.poll(() => s.button(action === "discard" ? "Discard" : action === "mute" ? "Mute mic" : "Send now")).not.toBeUndefined(); + await expect.poll(() => s.button(action === "discard" ? "Discard draft" : action === "mute" ? "Mute" : "Send now")).not.toBeUndefined(); expect(s.socket.frames("conversation_endpoint")).toHaveLength(1); expect(s.client.state.getState().outputRecovery).toBe("speaking"); let noise: ReturnType | undefined; if (noisy) { audio(); noise = setInterval(audio, 60); ctx.onTestFinished(() => clearInterval(noise)); } - await userEvent.click(s.button(action === "discard" ? "Discard" : action === "mute" ? "Mute mic" : "Send now")); + await userEvent.click(s.button(action === "discard" ? "Discard draft" : action === "mute" ? "Mute" : "Send now")); expect(s.client.state.getState().outputRecovery, "MANUAL_ENDPOINT_STARTS_RECOVERY").toBe("checking"); expect(s.socket.frames("conversation_endpoint")).toHaveLength(2); expect(s.socket.frames("conversation_commit")).toHaveLength(action === "send" ? 1 : 0); diff --git a/packages/ui-react/tests/browser/conversation.offline.tsx b/packages/ui-react/tests/browser/conversation.offline.tsx index b89b0b2deb..a10724ef1d 100644 --- a/packages/ui-react/tests/browser/conversation.offline.tsx +++ b/packages/ui-react/tests/browser/conversation.offline.tsx @@ -80,7 +80,7 @@ test("capture truth and disclosure: a ready speech session cannot mark an unopen await userEvent.click(s.button("Start")); await expect.poll(() => s.client.state.getState().micOn).toBe(true); await expect.poll(() => s.socket.frames("conversation_audio").length, { timeout: 5000 }).toBeGreaterThan(0); - expect(document.activeElement?.getAttribute("aria-label")).toBe("Mute mic"); + expect(document.activeElement?.getAttribute("aria-label")).toBe("Mute"); }); test("commit only: GPT-Live fragments remain NOT SENT while ordinary progress and tools keep streaming", async (ctx) => { @@ -88,7 +88,7 @@ test("commit only: GPT-Live fragments remain NOT SENT while ordinary progress an await s.start(); s.input("Find the departure note"); expect(s.socket.frames("conversation_commit"), "unknown fragments cannot commit themselves").toHaveLength(0); - await expect.poll(() => s.host.textContent).toContain("NOT SUBMITTED AS A BRAIN TASK"); + await expect.poll(() => s.host.querySelector("[data-conversation-field] .bk-voice-label-meta")?.textContent, { message: "the field says the draft is not sent" }).toBe("Draft · not sent yet"); s.deliver({ type: "text_delta", sessionId: SESSION, text: "Looking through the voyage notes" }); s.deliver({ type: "tool_use_start", sessionId: SESSION, toolUseId: "ithaca-search", toolName: "brain_search" }); s.deliver({ type: "tool_use_complete", sessionId: SESSION, toolUseId: "ithaca-search", toolName: "brain_search", input: { query: "departure" } }); @@ -189,7 +189,7 @@ test("barge-in flush: Stop reply discards every queued PCM chunk without revokin s.event({ kind: "output_transcript", outputId: "ithaca-reply", sequence: 0, text: "The note is ready." }); for (let sequence = 0; sequence < 3; sequence++) s.event({ kind: "audio", outputId: "ithaca-reply", sequence, format: { encoding: "pcm16", sampleRate: 24000, channels: 1 }, pcm: btoa(binary) }); await expect.poll(() => s.client.state.getState().playing).toBe(true); - await userEvent.click(s.button("Stop reply")); + await userEvent.click(s.button("Interrupt")); expect(s.client.state.getState().playing).toBe(false); expect(ended).toHaveLength(3); await expect.poll(() => ended.every(Boolean), { timeout: 500, message: "every real scheduled audio source ended at the cut, including future chunks" }).toBe(true); @@ -267,7 +267,7 @@ for (const theme of ["dark", "light"] as const) for (const width of [320, 1280]) s.ui.stores.followUp.getState().addLocal(SESSION, { requestId: "ithaca-pending", text: "Check the harbour fees", source: "voice-conversation", queuedAt: Date.now() }); s.deliver({ type: "text_delta", sessionId: SESSION, text: "The harbour work continues while you speak." }); await expect.poll(() => s.host.querySelector('[data-conversation-review]')).not.toBe(null); - const strip = s.host.querySelector('[data-conversation-strip]')!; + const strip = s.host.querySelector('[data-conversation-field]')!; const area = [...s.host.querySelectorAll('div')].find((element) => element.classList.contains("@container"))!; expect(area.getBoundingClientRect().height, "the actual scrolling transcript keeps at least 264 pixels at 320 × 568").toBeGreaterThanOrEqual(264); expect(strip.scrollWidth).toBeLessThanOrEqual(strip.clientWidth); @@ -706,7 +706,7 @@ for (const theme of ["dark", "light"] as const) test(`permission layout ${theme} const s = await scene(ctx, 320, true, theme); await s.start(); approval(s, "ithaca-layout"); recognition(s, "Review the departure note"); await expect.poll(() => s.host.querySelector('[data-voice-refusal-window]')).not.toBe(null); - const strip = s.host.querySelector('[data-conversation-strip]')!; + const strip = s.host.querySelector('[data-conversation-field]')!; const area = [...s.host.querySelectorAll('div')].find(element => element.classList.contains("@container"))!; expect(area.getBoundingClientRect().height).toBeGreaterThanOrEqual(264); for (const target of strip.querySelectorAll('[role="button"],button')) expect(target.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); @@ -790,9 +790,11 @@ test("microphone permission denial is visible and a late ready cannot undo expli ctx.onTestFinished(() => { if (descriptor) Object.defineProperty(media, "getUserMedia", descriptor); else Reflect.deleteProperty(media, "getUserMedia"); }); const s = await scene(ctx); await s.enter(); await userEvent.click(s.button("Start")); - await expect.poll(() => s.client.state.getState().notice).toContain("Microphone permission denied"); + await expect.poll(() => s.client.state.getState().notice).toContain("Microphone is blocked"); expect(s.client.state.getState().micOn).toBe(false); - await expect.poll(() => s.host.textContent).toContain("Microphone permission denied"); + await expect.poll(() => s.host.textContent).toContain("Microphone is blocked. Allow it in this site’s browser settings, then Start again."); + expect(s.host.querySelector("[data-conversation-field]")?.dataset.liveState, "a blocked microphone stops the conversation (L9)").toBe("L9"); + expect(s.button("Start again"), "the copy names the action L9 offers").not.toBeUndefined(); s.client.mute(); s.event({ kind: "ready", input: { encoding: "pcm16", channels: 1, sampleRate: 24000 }, output: { encoding: "pcm16", channels: 1, sampleRate: 24000 } }); expect(calls).toBe(1); @@ -1214,7 +1216,9 @@ for (const terminal of ["leave", "provider_error", "backpressure"] as const) tes expect(s.client.state.getState().micOn).toBe(false); expect(oldStream.getTracks().every(track => track.readyState === "ended")).toBe(true); } - await userEvent.click(s.button("Leave voice")); + // A closed epoch that withdrew capture is L9, whose Close leaves like End. + await expect.poll(() => s.button(terminal === "leave" ? "End" : "Close")).toBeDefined(); + await userEvent.click(s.button(terminal === "leave" ? "End" : "Close")); expect(s.client.state.getState().active).toBe(false); expect(oldStream.getTracks().every(track => track.readyState === "ended")).toBe(true); // Re-enter the same service in the same root. A fresh conversation has its @@ -1488,6 +1492,10 @@ test("output recovery timeout never mutes capture; manual output recovery and Le clearInterval(timer); expect(s.client.state.getState().micOn).toBe(true); expect(s.client.state.getState().playing).toBe(false); + const f = field(s); + expect(s.host.querySelector("[data-conversation-field] .bk-voice-label-meta")?.textContent).toBe("Reply audio off"); + expect(s.host.querySelector("[data-conversation-field] [data-voice-text]")?.textContent).toBe("Brain’s voice was paused after a dropout. Replies still arrive as text."); + expect(f.controls(), "recovery stays manual and in the row").toEqual(["Mute", "Recover reply audio", "End"]); await page.screenshot({ element: s.host, path: "../../.vitest-attachments/conversation/output-recovery-320.png" }); await userEvent.click(s.button("Recover reply audio")); s.event({ kind: "audio", outputId: "output-1", sequence: 1, pcm: outputPcm(0.2), format: { encoding: "pcm16", channels: 1, sampleRate: 24000 } }); @@ -1893,3 +1901,190 @@ test("late contextual correlation is bounded, exact and cleared with its princip expect(s.socket.frames("conversation_commit")).toHaveLength(0); expect(s.socket.frames("chat_message")).toHaveLength(0); }); + +/* ── The tall voice field (#3699): each live state from the client's own evidence ── */ + +function field(s: Awaited>) { + const root = () => s.host.querySelector("[data-conversation-field]"); + return { + state: () => root()?.dataset.liveState, + word: () => root()?.querySelector("[data-voice-word]")?.textContent, + control: (name: string) => root()?.querySelector(`button[aria-label="${name}"]`) ?? null, + controls: () => [...root()?.querySelectorAll(".bk-voice-field button") ?? []].map(node => node.getAttribute("aria-label")), + text: () => root()?.querySelector(".bk-voice-field")?.textContent ?? "", + }; +} +/** Interrupt is live only while brain's reply plays (L4), in every state. */ +function interruptOnlyInL4(f: ReturnType) { + const interrupt = f.control("Interrupt"); + if (interrupt) expect(interrupt.disabled, `INTERRUPT_ONLY_IN_L4 (${f.state()})`).toBe(f.state() !== "L4"); +} +const PCM24 = { encoding: "pcm16", channels: 1, sampleRate: 24000 } as const; + +/** Three seconds of brain's voice, in the one-second chunks the wire carries. */ +function speech(s: Awaited>, outputId: string) { + for (let sequence = 0; sequence < 3; sequence++) s.event({ kind: "audio", outputId, sequence, pcm: outputPcm(1), format: PCM24 }); +} + +test("live field: Listening, Speaking, Talked over, Muted and End follow real capture and playback", async (ctx) => { + const mic = controlledMicrophone(ctx, true); + const s = await scene(ctx); const f = field(s); + await s.enter(); + expect(s.host.querySelector(".bk-voice-field"), "the disclosure sheet is the only surface before Start").toBe(null); + await userEvent.click(s.button("Start")); + await expect.poll(f.state).toBe("L1"); + expect(f.word()).toBe("Listening"); + expect(f.controls()).toEqual(["Mute", "Interrupt", "End"]); + expect(f.text(), "the field names the service and the connected time, nothing more").toMatch(/^Listening\s*GPT-Live · \d+:\d\d$/); + interruptOnlyInL4(f); + await expect.poll(() => s.client.levels().input, { message: "the meter reads the real microphone level" }).toBeGreaterThan(0); + await userEvent.click(f.control("Mute")!); + await expect.poll(f.state).toBe("L7"); + expect(f.control("Unmute")!.getAttribute("aria-pressed")).toBe("true"); + interruptOnlyInL4(f); + // V5: Mute stops your microphone only; brain may finish its sentence. + speech(s, "ithaca-reply"); + await expect.poll(f.state).toBe("L4"); + expect(f.control("Unmute")!.getAttribute("aria-pressed"), "muted while brain speaks").toBe("true"); + expect(s.client.state.getState().micOn).toBe(false); + interruptOnlyInL4(f); + await expect.poll(() => s.client.levels().output, { message: "the meter reads what plays" }).toBeGreaterThan(0); + await userEvent.click(f.control("Interrupt")!); + await expect.poll(f.state).toBe("L7"); + interruptOnlyInL4(f); + // Talking over brain cuts it and gives you the floor (L5), then Listening again. + await expect.poll(() => s.client.state.getState().outputRecovery, { message: "the local quiet check ends" }).toBe("audible"); + speech(s, "ithaca-tail"); + await expect.poll(f.state).toBe("L4"); + await userEvent.click(f.control("Unmute")!); + await expect.poll(f.state).toBe("L5"); + expect(f.word()).toBe("Listening"); + interruptOnlyInL4(f); + mic.quiet(); + await expect.poll(f.state, { timeout: 5000 }).toBe("L1"); + await userEvent.click(f.control("End")!); + expect(s.client.state.getState().active).toBe(false); + await expect.poll(() => s.host.querySelector("textarea[data-composer]"), { message: "End returns the composer (L10)" }).not.toBe(null); + expect(s.host.querySelector("[data-conversation-field]")).toBe(null); +}); + +test("live field: Connecting, Working and Needs your tap; an approval stays tap-only", async (ctx) => { + controlledMicrophone(ctx); + const s = await scene(ctx); const f = field(s); + s.client.enter(); s.client.start(); + await expect.poll(f.state).toBe("S5"); + expect(f.word()).toBe("Connecting"); + expect(f.control("Mute")!.disabled, "nothing to mute while connecting").toBe(true); + interruptOnlyInL4(f); + s.opened(); + await expect.poll(f.state).toBe("L1"); + await expect.poll(() => s.socket.frames("conversation_audio").length).toBeGreaterThan(0); + s.deliver({ type: "text_delta", sessionId: SESSION, turnId: "ithaca-permission", text: "Checking the raft plan" }); + await expect.poll(f.state, { message: "host work is Working" }).toBe("L3"); + interruptOnlyInL4(f); + approval(s, "ithaca-tap"); + await expect.poll(f.state).toBe("L6"); + expect(f.word()).toBe("Needs your tap"); + expect(f.controls(), "L6_NO_VOICE_GRANT: the field offers no way to approve").toEqual(["Mute", "Interrupt", "End"]); + expect(f.text(), "L6_NO_VOICE_GRANT: the body directs to the card and offers nothing to say").toMatch(/^Needs your tapGPT-Live · \d+:\d\dTap Allow or Deny on the card\. Voice can’t approve or refuse with this service\.$/); + interruptOnlyInL4(f); + recognition(s, "yes, allow it"); + expect(s.socket.frames("tool_approval"), "speech never approves").toHaveLength(0); + await userEvent.click(page.getByRole("button", { name: /^Allow/ })); + expect(s.socket.frames("tool_approval")).toHaveLength(1); + expect(s.socket.frames("tool_approval")[0]?.channel ?? "card").toBe("card"); + await expect.poll(f.state, { message: "the tap answers it; the field leaves L6" }).not.toBe("L6"); +}); + +test("live field: a held draft takes the body and Interrupt's place unless brain speaks (R1)", async (ctx) => { + const mic = controlledMicrophone(ctx, true); + const s = await scene(ctx, 320); const f = field(s); + await s.start(); + const meta = () => s.host.querySelector("[data-conversation-field] .bk-voice-label-meta")?.textContent; + const body = () => s.host.querySelector("[data-conversation-field] [data-voice-text]")?.textContent; + const audio = s.socket.frames("conversation_audio").at(-1)!; + // A calibrated low score holds the words for review; they are the draft. + s.event({ kind: "input_fragment", utteranceId: String(audio.utteranceId), sequence: 0, text: "Ask Calypso when the axe is back", finalization: "final", certainty: "known", origin: "user", confidence: 0.5 }); + await expect.poll(body).toBe("Ask Calypso when the axe is back"); + expect(meta()).toBe("Draft · not sent yet"); + expect(f.state()).toBe("L1"); + expect(f.controls(), "DRAFT_HIDES_INTERRUPT").toEqual(["Mute", "Discard draft", "Send now", "End"]); + // V5: muted, brain may still finish its sentence. + await userEvent.click(f.control("Mute")!); + speech(s, "ithaca-axe"); + await expect.poll(f.state).toBe("L4"); + expect(f.controls(), "L4 with a draft carries five controls").toEqual(["Unmute", "Interrupt", "Discard draft", "Send now", "End"]); + interruptOnlyInL4(f); + const frame = s.host.querySelector(".bk-voice-field")!.getBoundingClientRect(); + for (const name of f.controls()) { + const box = f.control(name!)!.getBoundingClientRect(); + expect(box.width, `${name} keeps a 44px target`).toBeGreaterThanOrEqual(44); + expect(box.right, `${name} fits the 320px row`).toBeLessThanOrEqual(frame.right + 0.5); + } + expect(body(), "brain speaking does not hide the draft").toBe("Ask Calypso when the axe is back"); + await page.screenshot({ element: s.host, path: "../../.vitest-attachments/conversation/draft-speaking-320.png" }); + await userEvent.click(f.control("Interrupt")!); + await expect.poll(f.state).toBe("L7"); + expect(f.controls(), "DRAFT_HIDES_INTERRUPT").toEqual(["Unmute", "Discard draft", "Send now", "End"]); + await userEvent.click(f.control("Unmute")!); + await expect.poll(() => s.client.state.getState().micOn).toBe(true); + await userEvent.click(f.control("Discard draft")!); + expect(s.client.state.getState().text).toBe(""); + expect(s.socket.frames("conversation_commit"), "Discard sends nothing").toHaveLength(0); + await expect.poll(f.controls).toEqual(["Mute", "Interrupt", "End"]); + expect(meta()).toMatch(/^GPT-Live · \d+:\d\d$/); + // Unproven origin: the draft's body says it was unclear, and Send now stays explicit. + await expect.poll(() => s.socket.frames("conversation_audio").length).toBeGreaterThan(0); + mic.quiet(); + await expect.poll(() => s.client.state.getState().outputRecovery, { message: "the local quiet check ends", timeout: 6000 }).toBe("audible"); + s.input("Tally the cask"); + await expect.poll(body).toBe("I couldn't hear that clearly. Review before sending."); + expect(meta()).toBe("Draft · not sent yet"); + await userEvent.click(f.control("Send now")!); + await expect.poll(() => s.socket.frames("conversation_commit").length).toBe(1); + expect(s.socket.frames("conversation_commit")[0]?.text).toBe("Tally the cask"); +}); + +for (const [count, copy] of [[12, "Started with the last 12 messages"], [1, "Started with the last 1 message"]] as const) test(`coverage (R2): the host's count of ${count} sent messages opens the live section in the chat`, async (ctx) => { + controlledMicrophone(ctx); + const s = await scene(ctx, 320, true); + s.client.enter(); s.client.start(); + s.opened(1, CAPS, { historyCoverage: { state: "complete", tailOmitted: false, includedMessages: count } }); + await expect.poll(() => s.client.state.getState().profile?.historyCoverage?.includedMessages, { message: "the wire field survives validation" }).toBe(count); + const notice = () => s.host.querySelector("[data-voice-coverage]"); + await expect.poll(() => notice()?.textContent, { message: "VOICE_COVERAGE_COUNT_COPY" }).toBe(`${copy} · Details`); + expect(notice()!.closest("[data-conversation-field]"), "a chat notice, not a row above the field").toBe(null); + expect(notice()!.closest("[data-arrival-key]")).not.toBe(null); + await userEvent.click(s.button("Prior context details")); + await expect.poll(() => s.client.state.getState().disclosureOpen, { message: "Details opens the existing sheet" }).toBe(true); +}); + +test("live field: Reconnecting while recovery runs, Stopped only when it fails, Start again reopens Start", async (ctx) => { + controlledMicrophone(ctx, true); + const s = await scene(ctx); const f = field(s); + await s.start(); + s.network.drop({ announce: true }); + await expect.poll(f.state).toBe("L8"); + expect(f.word()).toBe("Reconnecting…"); + expect(s.client.state.getState().capture, "recovery keeps consent").toBe("listening"); + interruptOnlyInL4(f); + s.network.recover(); s.ui.connection.reconnectNow(); + await expect.poll(() => s.network.socket() !== s.socket && s.ui.stores.connection.getState().wsStatus === "connected").toBe(true); + const replacement = s.network.socket()!; + await expect.poll(() => replacement.frames("conversation_start").length).toBe(1); + replacement.deliver({ ...PROFILE, epoch: 2, requestId: replacement.frames("conversation_start").at(-1)?.requestId }); + replacement.deliver({ type: "conversation_event", conversationId: PROFILE.conversationId, epoch: 2, event: { kind: "ready", input: PCM24, output: PCM24 } }); + await expect.poll(f.state, { message: "recovery returns to Listening" }).toBe("L1"); + replacement.deliver({ type: "error", code: "CONVERSATION_UNKNOWN", message: "Voice scope is unavailable." }); + await expect.poll(f.state).toBe("L9"); + const stopped = s.host.querySelector("[data-conversation-field]")!; + expect(stopped.textContent).toContain("Live conversation stopped"); + expect(stopped.textContent, "the client's own reason, no more").toContain("Voice scope is unavailable."); + expect(s.client.state.getState().micOn).toBe(false); + await userEvent.click(s.button("Start again")); + await expect.poll(() => s.client.state.getState().disclosureOpen, { message: "Start again leads to the Start sheet" }).toBe(true); + expect(s.host.querySelector(".bk-voice-field")).toBe(null); + expect(s.client.state.getState().micOn).toBe(false); + await userEvent.click(s.button("Cancel")); + expect(s.client.state.getState().active).toBe(false); +}); diff --git a/packages/ui-react/tests/browser/dialogue-qualifiers.offline.tsx b/packages/ui-react/tests/browser/dialogue-qualifiers.offline.tsx index 0cd183e9cc..9d91ff7285 100644 --- a/packages/ui-react/tests/browser/dialogue-qualifiers.offline.tsx +++ b/packages/ui-react/tests/browser/dialogue-qualifiers.offline.tsx @@ -139,7 +139,10 @@ for(const providerId of ["gemini-live","gpt-live"])for(const theme of ["light"," flushSync(()=>s.ui.connection.conversation.state.setState({active:true,sessionId:SESSION,connection:"Connected",conversationProfile:profile(providerId),durableAvailable:true,profile:{...profile(providerId),historyCoverage:{state:"partial",tailOmitted:true}},disclosureOpen:false})); expect(s.host.textContent).toContain("Newest prior context may be missing."); const trigger=s.host.querySelector('[aria-label="Prior context details"]')!; - expect(trigger).not.toBeNull();trigger.focus();expect(document.activeElement).toBe(trigger); + expect(trigger).not.toBeNull(); + expect(trigger.closest("[data-conversation-field]"),"R2: coverage is a chat notice, not a row above the field").toBeNull(); + expect(trigger.closest("[data-voice-coverage]")?.closest("[data-arrival-key]"),"R2: it sits in the transcript").not.toBeNull(); + trigger.focus();expect(document.activeElement).toBe(trigger); if(width===320)await userEvent.click(trigger);else await userEvent.keyboard("{Enter}"); const dialog=document.querySelector("dialog[open]")!; expect(dialog).not.toBeNull();expect(dialog.textContent).toContain("The newest prior item may be missing."); diff --git a/packages/ui-react/tests/transcript-timeline.test.ts b/packages/ui-react/tests/transcript-timeline.test.ts index a4d65ea373..3af893286f 100644 --- a/packages/ui-react/tests/transcript-timeline.test.ts +++ b/packages/ui-react/tests/transcript-timeline.test.ts @@ -4,7 +4,7 @@ import { createTranscriptTimeline, transcriptMessage, transcriptRange, transcrip function entryText(e: TranscriptEntry) { if (e.kind === "history-notice") return e.label; - if (e.kind === "voice-boundary") return ""; + if (e.kind === "voice-boundary" || e.kind === "voice-coverage") return ""; if (e.kind === "recognition") return e.fragments.map(f => f.text).join(""); if (e.kind === "speech") return e.output.generated; const message = transcriptMessage(e); @@ -370,3 +370,43 @@ test("backend position qualification waits for completed native text",()=>{ expect(rows().filter(e=>e.kind==="message").map(entryText).join("\n")).toContain("The mast is ready. Tail."); }finally{root.dispose();} }); + +// R2 (#3699): incomplete startup-context coverage opens the live section in the chat, once. +test("incomplete live coverage is one chat entry after the earlier turns; complete coverage draws none", () => { + const root = createBrainUiRoot({ storage: null }); + try { + const chat = root.stores.chat.getState(); + const timeline = transcriptTimelineFor(root.stores.chat).state; + chat.addUserMessage("ithaca", "Which harbour first?"); + const voice = root.connection.conversation.state; + const profile = (conversationId: string, state: "complete" | "bounded") => ({ conversationId, epoch: 1, providerId: "gpt-live", capabilities: {}, historyCoverage: { state, tailOmitted: state !== "complete" } }) as unknown as NonNullable["profile"]>; + voice.setState({ active: true, sessionId: "ithaca", profile: profile("calm", "complete") }); + expect(timeline.getState().entries.some(e => e.kind === "voice-coverage"), "complete coverage claims nothing").toBe(false); + voice.setState({ active: true, sessionId: "ithaca", profile: profile("windy", "bounded") }); + // A reconnect later in the section does not move or repeat it. + voice.setState({ profile: { ...voice.getState().profile!, epoch: 2 } }); + chat.addUserMessage("ithaca", "And then Ithaca."); + const kinds = timeline.getState().entries.filter(e => e.sessionId === "ithaca").map(e => e.kind); + expect(kinds, "VOICE_COVERAGE_OPENS_LIVE_SECTION").toEqual(["message", "voice-coverage", "voice-boundary", "message"]); + const notice = timeline.getState().entries.find(e => e.kind === "voice-coverage"); + expect(notice?.kind === "voice-coverage" && notice.coverage).toEqual({ state: "bounded", tailOmitted: true }); + voice.setState({ active: false, profile: null }); + expect(timeline.getState().entries.some(e => e.kind === "voice-coverage"), "it leaves with the live section that has no retained evidence").toBe(false); + } finally { root.dispose(); } +}); + +// #3699 ruling: a host-reported count opens the section even when coverage is complete. +test("a sent-message count draws the coverage notice; an empty complete history draws none", () => { + const root = createBrainUiRoot({ storage: null }); + try { + const timeline = transcriptTimelineFor(root.stores.chat).state; + root.stores.chat.getState().addUserMessage("ithaca", "Which harbour first?"); + const voice = root.connection.conversation.state; + const profile = (conversationId: string, includedMessages: number) => ({ conversationId, epoch: 1, providerId: "gpt-live", capabilities: {}, historyCoverage: { state: "complete", tailOmitted: false, includedMessages } }) as unknown as NonNullable["profile"]>; + voice.setState({ active: true, sessionId: "ithaca", profile: profile("empty", 0) }); + expect(timeline.getState().entries.some(e => e.kind === "voice-coverage"), "nothing sent, nothing to say").toBe(false); + voice.setState({ active: true, sessionId: "ithaca", profile: profile("counted", 12) }); + const notice = timeline.getState().entries.find(e => e.kind === "voice-coverage"); + expect(notice?.kind === "voice-coverage" && notice.coverage.includedMessages, "VOICE_COVERAGE_CARRIES_COUNT").toBe(12); + } finally { root.dispose(); } +}); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 6bfd10a05e..62d8ef351e 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -2383,8 +2383,13 @@ export interface ClientConversationStop { * a single snapshot frame could outgrow the per-frame cap and be clipped. */ export interface ServerConversationOpened { - /** Actual bounded startup text coverage; no semantic recall guarantee. */ - historyCoverage?: { state: "complete" | "bounded" | "partial" | "unavailable"; tailOmitted: boolean }; + /** + * Actual bounded startup text coverage; no semantic recall guarantee. + * `includedMessages` (#3699) is how many prior chat and spoken messages the + * startup context actually carried; completed results and gap markers are + * not counted. Absent from older hosts. + */ + historyCoverage?: { state: "complete" | "bounded" | "partial" | "unavailable"; tailOmitted: boolean; includedMessages?: number }; historyGeneration?: number; historyOwnerId?: string; type: "conversation_opened"; diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index abadd30abf..9fb674eaae 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1899,7 +1899,7 @@ export const dialoguePageSchema = z.object({ cursor:z.string().max(2048).optiona export const serverDialogueHistorySchema = dialoguePageSchema.extend({ type: z.literal("dialogue_history"), requestId: id.optional() }) satisfies z.ZodType; export const serverConversationOpenedSchema = z.looseObject({ - historyCoverage: z.object({ state: z.enum(["complete", "bounded", "partial", "unavailable"]), tailOmitted: z.boolean() }).optional(), + historyCoverage: z.object({ state: z.enum(["complete", "bounded", "partial", "unavailable"]), tailOmitted: z.boolean(), includedMessages: z.number().int().nonnegative().optional() }).optional(), type: z.literal("conversation_opened"), historyGeneration:conversationEpoch.optional(), historyOwnerId: id.optional(), diff --git a/packages/ui-sdk/src/server/conversation.ts b/packages/ui-sdk/src/server/conversation.ts index 10981d83fb..e75a2950c5 100644 --- a/packages/ui-sdk/src/server/conversation.ts +++ b/packages/ui-sdk/src/server/conversation.ts @@ -206,8 +206,12 @@ export interface LiveConversationOpenOptions { * @experimental Part of the `LiveConversationProvider` seam. */ export interface LiveConversationSession { - /** Actual bounded historical seed coverage, when the adapter supports it. */ - historyCoverage?: { state: "complete" | "bounded" | "partial" | "unavailable"; tailOmitted: boolean }; + /** + * Actual bounded historical seed coverage, when the adapter supports it. + * `includedMessages` counts the prior chat and spoken messages the seed + * carried (not results or gap markers). + */ + historyCoverage?: { state: "complete" | "bounded" | "partial" | "unavailable"; tailOmitted: boolean; includedMessages?: number }; events: AsyncIterable; appendAudio(chunk: LiveConversationAudioChunk): void; markEndpoint(utteranceId: string): void; diff --git a/packages/ui-server/src/voice/conversation-history.ts b/packages/ui-server/src/voice/conversation-history.ts index 25280b70e3..bcbc87d911 100644 --- a/packages/ui-server/src/voice/conversation-history.ts +++ b/packages/ui-server/src/voice/conversation-history.ts @@ -96,5 +96,5 @@ export function liveContext(scope: ConversationScope, options: LiveConversationO const resync = selectResync(scope, options.resync, { ...limits, maxBytes: limits.maxBytes - reserve }); const history = boundHistory(options.history, resync.resultKeys, { maxItems: 128, maxBytes: limits.maxBytes - bytes(resync.text), maxFactBytes: limits.maxFactBytes - resync.factBytes }); - return { blocks: [orientation, history.text, resync.text].filter(Boolean), coverage: { state: history.coverage.state, tailOmitted: history.tailOmitted } }; + return { blocks: [orientation, history.text, resync.text].filter(Boolean), coverage: { state: history.coverage.state, tailOmitted: history.tailOmitted, includedMessages: history.includedMessages } }; } diff --git a/packages/ui-server/src/voice/session-history.ts b/packages/ui-server/src/voice/session-history.ts index 292e33afe6..44461f247d 100644 --- a/packages/ui-server/src/voice/session-history.ts +++ b/packages/ui-server/src/voice/session-history.ts @@ -43,6 +43,8 @@ export interface BoundedHistory { selectedRefs: readonly string[]; /** Host-only: newest omitted, or omitted text may be newer when source order is unknown. */ tailOmitted: boolean; + /** Host-only: chat and spoken messages actually serialized into `text` (not results or gaps). */ + includedMessages: number; coverage: ConversationHistoryEnvelope["coverage"]; } @@ -63,7 +65,7 @@ export function boundHistory( excludeResults: ReadonlySet = new Set(), limits: { maxBytes: number; maxItems: number; maxFactBytes: number } = HISTORY_LIMITS, ): BoundedHistory { - const empty = (coverage: BoundedHistory["coverage"]): BoundedHistory => ({ text: "", bytes: 0, selectedRefs: [], tailOmitted: false, coverage }); + const empty = (coverage: BoundedHistory["coverage"]): BoundedHistory => ({ text: "", bytes: 0, selectedRefs: [], tailOmitted: false, includedMessages: 0, coverage }); if (!envelope) return empty({ state: "unavailable", reasons: ["source_unavailable"] }); // Exact-identity dedupe (keep the newest occurrence); facts already in resync drop out. const seen = new Set(); @@ -133,7 +135,9 @@ export function boundHistory( const item=candidates[i]?.item; return item?.kind==="gap" && item.reason==="source_unavailable"; }); - return { text, bytes: bytes(text), tailOmitted: unavailableTail || uncertainOmission || candidates.length > 0 && !chosen[candidates.length - 1], selectedRefs: candidates.filter((_, i) => chosen[i]).map((c) => c.item.ref), + // Only what the provider actually receives: a dropped block carried none. + const includedMessages = text ? candidates.filter((c, i) => chosen[i] && c.item.kind !== "host_fact" && c.item.kind !== "gap").length : 0; + return { text, bytes: bytes(text), includedMessages, tailOmitted: unavailableTail || uncertainOmission || candidates.length > 0 && !chosen[candidates.length - 1], selectedRefs: candidates.filter((_, i) => chosen[i]).map((c) => c.item.ref), coverage: { state, reasons: outReasons } }; } diff --git a/packages/ui-server/tests/live-history-adapters.test.ts b/packages/ui-server/tests/live-history-adapters.test.ts index ec67926b5b..f5bfbf3fc3 100644 --- a/packages/ui-server/tests/live-history-adapters.test.ts +++ b/packages/ui-server/tests/live-history-adapters.test.ts @@ -291,7 +291,11 @@ for(const engine of ["gemini","gpt"] as const)test(`${engine}: preowner native p const rendered=historyTexts(engine,sockets[0]!).join("\n"); expect(rendered,"SOCKET_PRESERVES_NEWEST_SPOKEN_QUESTION_OVER_OLD_NATIVE_PREFIX").toContain(text[2]!); expect(rendered).not.toContain(huge);expect(rendered).toContain("ambiguous_order"); - expect(session.historyCoverage,"SOCKET_RECENCY_UNCERTAINTY_CANNOT_REPORT_FULL_NEWEST_COVERAGE").toEqual({state:"partial",tailOmitted:true}); + expect(session.historyCoverage,"SOCKET_RECENCY_UNCERTAINTY_CANNOT_REPORT_FULL_NEWEST_COVERAGE").toMatchObject({state:"partial",tailOmitted:true}); + // #3699: the count is exactly the messages the provider socket received. + const sent=rendered.match(/\\?"from\\?":\\?"(typed_user|typed_assistant|submitted_voice_request|dictated_chat_text|recognized_speech_unverified|generated_voice_reply)/g)?.length??0; + expect(sent).toBeGreaterThan(0); + expect(session.historyCoverage?.includedMessages,"COVERAGE_COUNT_IS_WHAT_THE_PROVIDER_RECEIVED").toBe(sent); expect(Buffer.byteLength(rendered)).toBeLessThanOrEqual(engine==="gpt"?7500:24000);await session.close(); }); diff --git a/packages/ui-server/tests/session-history.test.ts b/packages/ui-server/tests/session-history.test.ts index aac42d95ae..210a145c19 100644 --- a/packages/ui-server/tests/session-history.test.ts +++ b/packages/ui-server/tests/session-history.test.ts @@ -179,3 +179,28 @@ test("ambiguous cross-stream order qualifies only a possibly newest omission, no expect(out.tailOmitted,"BOTH_SOURCE_TAILS_INCLUDED_DO_NOT_INVENT_A_NEWEST_OMISSION").toBe(false); expect(out.coverage.state).toBe("partial"); }); + +// #3699: the coverage count names exactly the messages serialized, never results, gaps or dropped items. +test("includedMessages counts the serialized chat and spoken messages only", () => { + const items: HistoricalItem[] = [ + typed("m1", "Which harbour did Penelope name?"), + { ref: "s1", kind: "recognized", text: "the bronze owl signal", finalization: "final", provenance: prov }, + { ref: "g1", kind: "generated", text: "I will look that up.", provenance: prov }, + fact("r1", "Departure signal: a bronze owl over the blue sail."), + { ref: "x1", kind: "gap", reason: "source_unavailable" } as HistoricalItem, + typed("m2", "Thanks, keep the blue sail.", "assistant"), + ]; + const all = boundHistory(env(items)); + const sent = data(all.text).filter(row => typeof row.from === "string" && row.from !== "host_result").length; + expect(sent).toBe(4); + expect(all.includedMessages, "COVERAGE_COUNT_MATCHES_SERIALIZED_MESSAGES").toBe(sent); + // A tight bound keeps the newest few: the count follows what fit. + const tight = boundHistory(env(items), new Set(), { ...HISTORY_LIMITS, maxBytes: u8(HISTORY_PREAMBLE) + 160, maxFactBytes: 0 }); + expect(tight.includedMessages).toBe(data(tight.text).filter(row => typeof row.from === "string").length); + expect(tight.includedMessages).toBeLessThan(4); + expect(boundHistory(undefined).includedMessages, "nothing sent, nothing counted").toBe(0); + // The host-only coverage the session reports carries the same count. + const live = liveContext({ conversationId: "ithaca-new", epoch: 1 }, { signal: new AbortController().signal, resync: { work: [], results: [] }, history: env(items) }, STARTUP_CONTEXT_LIMITS.gpt); + expect(live.coverage.includedMessages).toBe(4); + for (const block of live.blocks) expect(block, "the count never reaches the provider").not.toContain("includedMessages"); +});