diff --git a/.changeset/spoken-turn-marks.md b/.changeset/spoken-turn-marks.md new file mode 100644 index 0000000000..3b8bfc2c6e --- /dev/null +++ b/.changeset/spoken-turn-marks.md @@ -0,0 +1,11 @@ +--- +"@schlessera/brain-ui-react": minor +--- + +Spoken turns in the chat now use the voice kit's marks (#3700). Recognized speech is your spoken turn, with the amber mic. A voice reply is brain's, with the teal speaker. A dictated or reviewed voice message also carries the mic inline, in place of the header badge. Typed and legacy turns stay plain. + +- While live recognition is still updating, your turn shows the outlined bubble and cursor. Restored text never does. +- A fragment is dotted as uncertain only when the service reported a calibrated confidence below the client's 0.9 review threshold. That evidence is retained, so a reloaded chat shows the same marks. +- No reply text is dimmed as unplayed, because the client does not know which words the played audio carried. +- When a live conversation ends, the chat shows the end divider with its locally observed duration, in place of "Voice ended". +- The "Recognized speech" and "Voice reply" headers and the "Original discussion position unknown" line are gone. That evidence stays in the transcript details. diff --git a/packages/ui-react/src/components/chat/chat-page.tsx b/packages/ui-react/src/components/chat/chat-page.tsx index 4702847453..c0e4e513a8 100644 --- a/packages/ui-react/src/components/chat/chat-page.tsx +++ b/packages/ui-react/src/components/chat/chat-page.tsx @@ -1,12 +1,12 @@ import { transcriptMessage, transcriptTimelineFor, transcriptRange } from "../../lib/transcript-timeline.js"; import { useStore } from "zustand"; -import { ConversationOutput, ConversationRecognitionRow, ConversationPermissionOutcomes, ConversationTaskContext } from "../voice/conversation-outputs.js"; +import { 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"; import { useState, useRef, useEffect, useLayoutEffect, useCallback, useMemo } from "react"; import { TranscriptReadingScope } from "@schlessera/brain-ui-kit/internal"; -import { Button } from "@schlessera/brain-ui-kit"; +import { Button, ConversationEndDivider } from "@schlessera/brain-ui-kit"; import { useChatStore, activeChat, restorationOf } from "../../stores/chat-store.js"; import type { AskUserAnnotation } from "@schlessera/brain-ui-sdk/protocol"; import type { AnswerPayload } from "../../lib/answer-delivery/types.js"; @@ -760,7 +760,9 @@ export function ChatPage() { {visibleEntries.map((entry) => { if (entry.kind === "history-notice") return

{entry.label}

; if (entry.kind === "speech") return ; - if (entry.kind === "voice-boundary") return

{entry.label}

; + if (entry.kind === "voice-boundary") return entry.label === "Voice ended" + ?
+ :

{entry.label}

; if (entry.kind === "recognition") { const first = entry.fragments[0]!; const preceding = entries.slice(0, entries.indexOf(entry)).filter(e => e.kind === "recognition").flatMap(e => e.kind === "recognition" ? e.fragments : []); diff --git a/packages/ui-react/src/components/chat/message-bubble.tsx b/packages/ui-react/src/components/chat/message-bubble.tsx index f7c55330c8..4530028e39 100644 --- a/packages/ui-react/src/components/chat/message-bubble.tsx +++ b/packages/ui-react/src/components/chat/message-bubble.tsx @@ -114,6 +114,8 @@ export const MessageBubble = memo(function MessageBubble({ }) { const root = useBrainUiRoot(); const isUser = message.role === "user"; + // Dictated or reviewed voice text came in by voice; its source survives replay. + const spoken = isUser && (message.source === "voice-dictate" || message.source === "voice-conversation"); const reducedMotion = useReducedMotion(); const shellStartedAt = useShellStartedAt(message); @@ -128,7 +130,6 @@ export const MessageBubble = memo(function MessageBubble({ ) : isUser ? ( - + + {spoken && message.content && {linkifyPaths(message.content)}} {!!message.files?.length &&
{message.files.map(file => )}
} {!!message.attachmentFiles?.length &&
{message.attachmentFiles.map(file => )}
} - {message.content && ( + {!spoken && message.content && (
{linkifyPaths(message.content)}
diff --git a/packages/ui-react/src/components/chat/transcript-turn.tsx b/packages/ui-react/src/components/chat/transcript-turn.tsx index 1cd2b3b4f9..74c5ca2bd3 100644 --- a/packages/ui-react/src/components/chat/transcript-turn.tsx +++ b/packages/ui-react/src/components/chat/transcript-turn.tsx @@ -1,4 +1,4 @@ -import { Chip, Disclosure, Icon, MessageBubble, StatusDot } from "@schlessera/brain-ui-kit"; +import { Chip, Disclosure, MessageBubble, SpokenTurn, StatusDot } from "@schlessera/brain-ui-kit"; import type { ReactNode } from "react"; import { cn } from "../../lib/utils.js"; @@ -15,14 +15,14 @@ import { cn } from "../../lib/utils.js"; * share menu is real and sits under the last text block. The thinking blurb * is a kit `Disclosure` whose summary says what is hidden ("Thought for ~N * tokens"), controlled by the container so it can auto-collapse when the - * stream ends. + * stream ends. A user turn that came in by voice is the kit's `SpokenTurn`, + * whose inline amber mic replaces the old header badge; a typed or legacy turn + * stays a plain bubble. */ interface TurnHeaderProps { who: string; /** Mono time, already formatted. Absent prints no time (a turn shell the host has not timed). */ when?: string; - /** The user turn came in by voice: which kind. */ - voice?: "voice-dictate" | "voice-conversation"; /** Explicit effort provenance, already formatted; defaults leave this absent. */ effort?: string; tone: "user" | "brain" | "neutral"; @@ -41,15 +41,6 @@ export function TurnHeader(p: TurnHeaderProps) { {p.effort && {p.effort}}
- {p.voice && ( - - - - )} {p.when !== undefined && ( {p.when} )} @@ -57,8 +48,10 @@ export function TurnHeader(p: TurnHeaderProps) { ); } -/** The user's bubble: attachments above the text, both the container's. */ -export function UserTurn({ children }: { children: ReactNode }) { +/** The user's bubble: attachments above the text, both the container's. A + * spoken turn carries the mic mark first, so its words lead. */ +export function UserTurn({ children, spoken = false }: { children: ReactNode; spoken?: boolean }) { + if (spoken) return {children}; return (
{children}
diff --git a/packages/ui-react/src/components/voice/conversation-outputs.tsx b/packages/ui-react/src/components/voice/conversation-outputs.tsx index 528fc266b3..ae5ea0aa87 100644 --- a/packages/ui-react/src/components/voice/conversation-outputs.tsx +++ b/packages/ui-react/src/components/voice/conversation-outputs.tsx @@ -1,11 +1,26 @@ -import { Button } from "@schlessera/brain-ui-kit"; +import { Button, SpokenTurn, 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"; import type { ChatMessage } from "../../stores/chat-state.js"; import { useStore } from "zustand"; import { useBrainUiRoot } from "../../root-context.js"; -import { TurnHeader } from "../chat/transcript-turn.js"; + +/** + * The confidence below which the conversation client already holds captured + * input for review instead of sending it (`conversation-client.ts`). Only a + * calibrated score (`certainty: "known"`) below it marks words uncertain; an + * absent score is no evidence either way, so nothing is marked. + */ +const REVIEW_CONFIDENCE = 0.9; +const uncertain = (f: ConversationRecognition) => f.kind === "input_fragment" && f.certainty === "known" && f.confidence !== undefined && f.confidence < REVIEW_CONFIDENCE; + +/** The dotted underline covers the fragment the score describes, never its surrounding spaces. */ +function RecognizedWords({ fragment }: { fragment: ConversationRecognition }) { + if (!uncertain(fragment)) return <>{fragment.text}; + const [, lead = "", words = "", trail = ""] = /^(\s*)([\s\S]*?)(\s*)$/.exec(fragment.text) ?? []; + return words ? <>{lead}{words}{trail} : <>{fragment.text}; +} /** Voice-generated words share Chat's scrolling transcript; they never replace backend progress. */ export function ConversationPermissionOutcomes({ sessionId }: { sessionId: string | null }) { @@ -17,16 +32,20 @@ export function ConversationPermissionOutcomes({ sessionId }: { sessionId: strin ; } -/** A display segment retains the engine's output identity and playback evidence. */ +/** + * A display segment retains the engine's output identity and playback evidence. + * It reads as brain's spoken turn: the teal speaker mark, never a heard claim. + * No text is dimmed as unplayed: the client knows which chunks drained, not + * which words they carried (`playedSamples` does not align text to audio). + */ export function ConversationOutput({ output, restored = false, arrivalKey }: { output: ConversationClientOutput; restored?: boolean; arrivalKey?: string }) { return
- -
{output.generated}{output.generated} +

Conversation {output.conversationId} · epoch {output.epoch} · output {output.outputId}

{output.playedSamples &&

Reported local samples: {output.playedSamples.start}–{output.playedSamples.end}. This does not align text to audio.

}
- {(output.orderUnknown ?? restored) &&

Original discussion position unknown.

}
; } @@ -55,23 +74,43 @@ export function ConversationTaskContext({ message, sessionId, result, entries =
; } -/** Readable uncertain evidence, outside user-message and live-announcement regions. */ +/** + * Recognized speech reads as your spoken turn: the amber mic mark, an outlined + * bubble with a cursor while live recognition is still updating, and a dotted + * underline only where a calibrated score is low. Restored text never shows as + * still being recognized. Provider, timing and speaker evidence stay in the + * details, outside user-message and live-announcement regions. + */ export function ConversationRecognitionRow({ fragments, introduction = false }: { fragments: ConversationRecognition[]; introduction?: boolean }) { const first = fragments[0]!; const service = conversationService(first.providerId); const updating = fragments.filter(f => f.finalization === "interim").length; const finish = updating ? updating === fragments.length ? "updating" : "some-updating" : fragments.some(f => f.finalization === "final") ? "finished" : "unknown"; + const restored = fragments.some(f => f.restored); + const moved = fragments.every(f => f.moved); return
{introduction &&
Voice · {service}
} - -
{fragments.every(f => f.moved) ? "Moved to voice review" : fragments.map(f => f.text).join("")}f.restored)} orderUnknown={fragments.some(f=>f.orderUnknown)} evidenceLabel={`Technical evidence (${fragments.length} fragment${fragments.length === 1 ? "" : "s"})`}> + 0}>{moved ? "Moved to voice review" : fragments.map(f => )} +
f.orderUnknown)} evidenceLabel={`Technical evidence (${fragments.length} fragment${fragments.length === 1 ? "" : "s"})`}>

Recognized text evidence. Display order does not establish an exact response pairing.

    {fragments.map(f =>
  1. Epoch {f.epoch} · fragment {f.sequence} · {f.kind === "input_fragment" ? `Captured input ${f.utteranceId}; speaker unverified` : "Unassigned input; speaker unverified"}. + {f.kind === "input_fragment" ? f.certainty === "known" && f.confidence !== undefined ? ` Service confidence ${Math.round(f.confidence * 100)}%.` : " No calibrated confidence." : ""} {f.kind === "unassigned_input_fragment" && f.sessionInterval ? ` Provider session timing; approximate: ${f.sessionInterval.startMs}–${f.sessionInterval.endMs} ms.` : f.kind === "input_fragment" && f.interval ? ` Provider input timing: ${f.interval.startMs}–${f.interval.endMs} ms.` : " Timing unavailable; speaker unverified."} {f.finalization === "final" ? " Service finish marker received." : f.finalization === "interim" ? " Updating recognition." : " No finish evidence."}
  2. )}
; } + +/** + * The end divider's label: `Live`, then the locally observed duration. The + * persona joins it once a conversation carries one (#3617); none is guessed. + */ +export function conversationEndLabel(durationMs?: number) { + if (durationMs === undefined) return "Live"; + const total = Math.round(durationMs / 1000); + const h = Math.floor(total / 3600), m = Math.floor(total / 60) % 60, sec = String(total % 60).padStart(2, "0"); + return `Live · ${h ? `${h}:${String(m).padStart(2, "0")}` : m}:${sec}`; +} diff --git a/packages/ui-react/src/lib/transcript-timeline.ts b/packages/ui-react/src/lib/transcript-timeline.ts index c89d0ce646..bcb8190c58 100644 --- a/packages/ui-react/src/lib/transcript-timeline.ts +++ b/packages/ui-react/src/lib/transcript-timeline.ts @@ -7,7 +7,9 @@ import type { ConversationClientState, ConversationClientOutput, ConversationRec export type TranscriptEntry = | { key: string; sessionId: string | null; kind: "message"; message: ChatMessage; index: number; section: "whole" | "progress" | "answer"; start?: number; end?: number } | { key: string; sessionId: string | null; kind: "speech"; output: ConversationClientOutput; restored: boolean } - | { key: string; sessionId: string | null; kind: "voice-boundary"; conversationId: string; epoch: number; label: "Voice ended" | "Voice reconnected" } + | { key: string; sessionId: string | null; kind: "voice-boundary"; conversationId: string; epoch: number; label: "Voice ended" | "Voice reconnected"; + /** Locally observed, from this client first seeing the conversation open to its end. Absent when the open was not observed. */ + durationMs?: number } | {key:string;sessionId:string|null;kind:"history-notice";label:string} | { key: string; sessionId: string | null; kind: "recognition"; fragments: ConversationRecognition[] }; @@ -41,6 +43,7 @@ export function createTranscriptTimeline(chat: StoreApi, voice: Store return positions.get(key)!.arrival; }; const boundaries = new Map>(); + const opened = new Map(); const split = new Set(); const runs = new Map>(); const textBefore = new Map(); @@ -284,16 +287,20 @@ export function createTranscriptTimeline(chat: StoreApi, voice: Store if (next.buffers !== old.buffers || next.draft !== old.draft || next.detachedDrafts !== old.detachedDrafts) sync(); }); const stopVoice = voice.subscribe((next, old) => { + if (next.active && next.profile && !opened.has(next.profile.conversationId)) opened.set(next.profile.conversationId, Date.now()); if (old.profile && old.active && (!next.active || next.profile && next.profile.conversationId === old.profile.conversationId && next.profile.epoch > old.profile.epoch)) { const reconnect = next.active && next.profile; const profile = reconnect || old.profile; const key = JSON.stringify(["voice-boundary", profile.conversationId, profile.epoch, sequence]); position(key); latest.set(next.sessionId, key); - boundaries.set(key, { kind: "voice-boundary", key, sessionId: next.sessionId, conversationId: profile.conversationId, epoch: profile.epoch, label: reconnect ? "Voice reconnected" : "Voice ended" }); + const start = opened.get(profile.conversationId); + if (!reconnect) opened.delete(profile.conversationId); + boundaries.set(key, { kind: "voice-boundary", key, sessionId: next.sessionId, conversationId: profile.conversationId, epoch: profile.epoch, label: reconnect ? "Voice reconnected" : "Voice ended", + ...(!reconnect && start !== undefined ? { durationMs: Math.max(0, Date.now() - start) } : {}) }); } 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(); opened.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/tests/browser/conversation-contextual.offline.tsx b/packages/ui-react/tests/browser/conversation-contextual.offline.tsx index a83c7d9b6b..4635d9c993 100644 --- a/packages/ui-react/tests/browser/conversation-contextual.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-contextual.offline.tsx @@ -589,7 +589,12 @@ test("cold restored speech explicitly has unknown original discussion position", s.client.enter(); s.client.start(); s.deliver({...PROFILE,resync:{work:0,outputs:1},requestId:String(s.socket.frames("conversation_start").at(-1)!.requestId)}); s.deliver({ type: "conversation_output", conversationId: PROFILE.conversationId, epoch: 1, outputId: "historical-voyage", generated: "An earlier voyage reply.", playback: "unknown" }); - await expect.poll(() => s.host.querySelector("[data-conversation-output]")?.textContent).toContain("Original discussion position unknown"); + await expect.poll(() => s.host.querySelector("[data-conversation-output]")?.textContent).toContain("An earlier voyage reply."); + // #3700: the unknown position is evidence in the details, not a diagnostic line in the chat. + expect(s.host.querySelector("[data-conversation-output]")!.textContent).not.toContain("Original discussion position unknown"); + await userEvent.click(s.host.querySelector('[data-conversation-output] [data-transcript-qualifiers="generated"]')!); + await expect.poll(() => document.querySelector("dialog[open]")?.textContent).toContain("Original discussion position unknown"); + await userEvent.keyboard("{Escape}"); expect(s.client.state.getState().micOn).toBe(false); }); @@ -1064,7 +1069,7 @@ test("bounded recognition eviction and replacement never fabricate cold-reload d await expect.poll(() => s.host.textContent).toContain("Voice reconnected"); expect(s.client.state.getState().recognition.at(-1)).toMatchObject({ epoch: 2, sequence: 0, text: "A new voyage." }); s.client.leave(); - await expect.poll(() => s.host.textContent).toContain("Voice ended"); + await expect.poll(() => s.host.querySelector('[role="separator"]')?.getAttribute("aria-label")).toMatch(/^Live conversation ended: Live/); s.ui.stores.chat.getState().setActiveSession("pylos-watch"); s.client.enter(); expect(s.client.state.getState().recognition).toEqual([]); diff --git a/packages/ui-react/tests/browser/spoken-turn-marks.offline.tsx b/packages/ui-react/tests/browser/spoken-turn-marks.offline.tsx new file mode 100644 index 0000000000..013337586e --- /dev/null +++ b/packages/ui-react/tests/browser/spoken-turn-marks.offline.tsx @@ -0,0 +1,111 @@ +/// +// Spoken-turn marks in the chat (#3700): the kit's #3692 components, driven +// only by recorded provenance. Live, settled and reloaded chats are each +// rendered through the real ChatPage and transcript timeline. +import { afterAll, beforeAll, expect, test, vi, type TestContext } from "vitest"; +import { commands, page } from "vitest/browser"; +import { createRoot } from "react-dom/client"; +import { flushSync } from "react-dom"; +import axe from "axe-core"; +import { createBrainUiRoot } from "../../src/root.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { ChatPage } from "../../src/components/chat/chat-page.js"; +import { CONVERSATION_LIMITS, type DialogueRecord, type ServerConversationOpened, type SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { ConversationRecognition } from "../../src/voice/conversation-client.js"; +import { installFaultNetwork } from "./offline/fault-network.js"; + +const SESSION = "odysseus-raft"; +const PROFILE: ServerConversationOpened = { type: "conversation_opened", conversationId: "odysseus-voice", epoch: 1, sessionId: SESSION, providerId: "gemini-live", capabilities: { nonblockingWork: "supported", manualEndpoint: "supported", finalTranscript: "supported", remoteOutputCancelAck: "unproven", exactPermissionSpeech: "unproven", echoIsolatedInput: "unproven", outputWordAlignment: "unproven" }, disclosure: { voiceService: "Odysseus voice fixture", destinations: [] }, limits: { ...CONVERSATION_LIMITS }, resync: { work: 0, outputs: 0 } }; +let styles: HTMLStyleElement; +beforeAll(async () => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(new Date("2026-07-12T09:00:00Z")); styles = document.createElement("style"); styles.textContent = await commands.formConsumerStyles(); document.head.append(styles); }); +afterAll(() => { styles.remove(); vi.useRealTimers(); }); + +async function scene(ctx: TestContext, history: SessionHistoryMessage[] = [], width = 320) { + const previous = { width: innerWidth, height: innerHeight }; + const outer = await commands.formViewport(width, 720); + await page.viewport(width, 720); + const network = installFaultNetwork({ routes: url => url.pathname.endsWith("/sessions") ? Response.json({ sessions: [] }) : undefined, + onOpen(socket) { socket.deliver({ type: "server_hello", protocolRev: 5, principalKey: "odysseus", capabilities: {} }); socket.deliver({ type: "session_info", sessionId: SESSION, isNew: false }); socket.deliver({ type: "session_history", sessionId: SESSION, messages: history }); socket.deliver({ type: "status", sessionId: SESSION, status: "idle" }); } }); + const ui = createBrainUiRoot({ storage: null, request: network.request }); + ui.stores.chat.getState().setActiveSession(SESSION); + const host = document.createElement("div"); host.style.cssText = `position:fixed;inset:0;width:${width}px;height:720px;background:var(--bk-color-canvas);color:var(--bk-color-ink);overflow:auto`; + document.body.append(host); + const root = createRoot(host); + flushSync(() => root.render()); + const release = ui.connection.connect(); + ctx.onTestFinished(async () => { flushSync(() => root.unmount()); release(); ui.dispose(); network.restore(); host.remove(); await page.viewport(previous.width, previous.height); await commands.formViewport(outer.width - 100, outer.height - 120); }); + await expect.poll(() => ui.stores.connection.getState().wsStatus).toBe("connected"); + return { ui, host }; +} + +/** Captured input with exactly the confidence evidence given; nothing is filled in. */ +function captured(sequence: number, text: string, evidence: { confidence?: number; finalization?: "interim" | "final" | "unknown" } = {}): ConversationRecognition { + return { kind: "input_fragment", conversationId: "odysseus-voice", epoch: 1, sessionId: SESSION, providerId: "gemini-live", activation: 1, contextual: true, utteranceId: "calypso-axe", sequence, text, + finalization: evidence.finalization ?? "final", origin: "user", ...(evidence.confidence === undefined ? { certainty: "unknown" as const } : { certainty: "known" as const, confidence: evidence.confidence }) }; +} +const marks = (root: ParentNode) => ({ + you: root.querySelectorAll('.bk-spoken-mark[data-speaker="you"]').length, + brain: root.querySelectorAll('.bk-spoken-mark[data-speaker="brain"]').length, +}); +const uncertainWords = (root: ParentNode) => [...root.querySelectorAll(".bk-uncertain")].map(w => w.firstChild?.textContent); + +test("a live spoken exchange carries the mic and speaker marks; only a low calibrated score is uncertain", async ctx => { + const s = await scene(ctx, [{ role: "user", content: "Which timber is left for the raft?", toolCalls: [] }, { role: "assistant", content: "Eleven logs of seasoned pine.", toolCalls: [] }]); + await expect.poll(() => s.host.textContent).toContain("Eleven logs of seasoned pine."); + expect(marks(s.host), "a typed exchange carries no mark").toEqual({ you: 0, brain: 0 }); + flushSync(() => s.ui.connection.conversation.state.setState({ active: true, sessionId: SESSION, profile: PROFILE, + recognition: [captured(1, "When is ", { confidence: 0.97 }), captured(2, "Calypso's ", { confidence: 0.41 }), captured(3, "axe back?", { finalization: "interim" })], + outputs: [{ conversationId: "odysseus-voice", epoch: 1, sessionId: SESSION, providerId: "gemini-live", outputId: "axe-reply", generated: "Calypso returns the bronze axe at dusk.", playback: "discarded" }] })); + const row = await vi.waitFor(() => s.host.querySelector("[data-conversation-recognition]")!); + expect(marks(s.host)).toEqual({ you: 1, brain: 1 }); + expect(uncertainWords(row), "only the calibrated 0.41 fragment, without its trailing space").toEqual(["Calypso's"]); + expect(row.querySelector(".bk-spoken-bubble")!.getAttribute("data-in-progress"), "an interim fragment is still being recognized").toBe("true"); + expect(row.querySelector(".bk-voice-cursor")).not.toBeNull(); + expect(s.host.querySelector(".bk-unplayed"), "no text position is known, so nothing is dimmed as unplayed").toBeNull(); + expect(s.host.querySelector(".bk-cut-off"), "a cut-off claim needs barge-in evidence the transcript does not carry").toBeNull(); + expect(s.host.textContent, "the old turn labels are gone").not.toMatch(/Recognized speech|Voice reply/); + // The spoken turns only: the header time stamp is outside this change. + for (const turn of s.host.querySelectorAll("[data-conversation-recognition], [data-conversation-output]")) expect((await axe.run(turn)).violations.flatMap(v => v.nodes.map(n => `${v.id} ${n.target.join(" ")}: ${n.failureSummary}`))).toEqual([]); + await page.screenshot({ element: s.host, path: "../../.vitest-attachments/spoken-turn-marks/live-320.png" }); + + // Settled: the interim fragment finishes, and the cursor goes. + flushSync(() => s.ui.connection.conversation.state.setState(state => ({ recognition: state.recognition.map(f => f.sequence === 3 ? { ...f, finalization: "final" as const } : f) }))); + expect(row.querySelector(".bk-spoken-bubble")!.hasAttribute("data-in-progress")).toBe(false); + expect(row.querySelector(".bk-voice-cursor")).toBeNull(); +}); + +test("a settled conversation ends with the divider and its locally observed duration", async ctx => { + const s = await scene(ctx); + flushSync(() => s.ui.connection.conversation.state.setState({ active: true, sessionId: SESSION, profile: PROFILE, recognition: [captured(1, "Is the raft ready?")] })); + vi.setSystemTime(Date.now() + 72_000); + flushSync(() => s.ui.connection.conversation.state.setState({ active: false })); + const divider = await vi.waitFor(() => s.host.querySelector(".bk-voice-divider")!); + expect(divider.getAttribute("role")).toBe("separator"); + expect(divider.getAttribute("aria-label"), "duration only: no persona is recorded, so none is named").toBe("Live conversation ended: Live · 1:12"); + expect(s.host.textContent).not.toContain("Voice ended"); + await page.screenshot({ element: s.host, path: "../../.vitest-attachments/spoken-turn-marks/ended-320.png" }); +}); + +test("a reloaded chat renders the same marks from retained evidence; a legacy turn stays plain", async ctx => { + const s = await scene(ctx, [ + { role: "user", content: "Which timber is left for the raft?", toolCalls: [] }, + { role: "user", content: "Count the pine logs again.", toolCalls: [], source: "voice-dictate" }, + ]); + await expect.poll(() => s.host.textContent).toContain("Count the pine logs again."); + const record = (sequence: number, event: Extract["event"]): DialogueRecord => + ({ sequence, identity: `record-${sequence}`, evidence: { kind: "voice", conversationId: "odysseus-voice", epoch: 1, providerId: "gemini-live", event } }); + flushSync(() => s.ui.connection.conversation.state.setState({ sessionId: SESSION, dialogueRestoredThrough: { [SESSION]: 3 }, dialogue: { [SESSION]: { ownerId: "odysseus-voice", sessionId: SESSION, generation: 1, coverage: "complete", through: 3, records: [ + record(1, { kind: "input_fragment", utteranceId: "calypso-axe", sequence: 1, text: "When is Calypso's ", finalization: "final", certainty: "known", confidence: 0.98, origin: "user" }), + // Saved while still interim: retained, but no longer being recognized. + record(2, { kind: "input_fragment", utteranceId: "calypso-axe", sequence: 2, text: "axe back?", finalization: "interim", certainty: "known", confidence: 0.3, origin: "user" }), + record(3, { kind: "output_transcript", outputId: "axe-reply", sequence: 3, text: "Calypso returns the bronze axe at dusk." }), + ] } } })); + const row = await vi.waitFor(() => s.host.querySelector("[data-conversation-recognition]")!); + expect(marks(s.host), "the dictated turn, the recognized turn and the voice reply").toEqual({ you: 2, brain: 1 }); + expect(uncertainWords(row), "the retained calibrated score marks the same words").toEqual(["axe back?"]); + expect(row.querySelector(".bk-spoken-bubble")!.hasAttribute("data-in-progress"), "restored text is never shown as still being recognized").toBe(false); + const typed = [...s.host.querySelectorAll(".chat-message-body")].find(b => b.textContent === "Which timber is left for the raft?")!; + expect(typed.closest(".bk-spoken-turn"), "a turn with no voice source renders plain").toBeNull(); + expect(s.host.querySelector(".bk-unplayed")).toBeNull(); + await page.screenshot({ element: s.host, path: "../../.vitest-attachments/spoken-turn-marks/reloaded-320.png" }); +}); diff --git a/packages/ui-react/tests/render/message-source.test.tsx b/packages/ui-react/tests/render/message-source.test.tsx index f1b56d0b0e..7b54024254 100644 --- a/packages/ui-react/tests/render/message-source.test.tsx +++ b/packages/ui-react/tests/render/message-source.test.tsx @@ -1,6 +1,7 @@ // Render test for a replayed message's source (#549): a user message the -// host replays with `source: "voice-dictate"` keeps its dictation badge, and -// one replayed without a source renders as typed. The frame goes through the +// host replays with `source: "voice-dictate"` keeps its spoken mark (#3700: +// the kit's inline amber mic), and one replayed without a source renders as +// typed, with no mark. The frame goes through the // real client handler into the store, and the stored message is rendered by // the component the transcript uses. Queries come from `render()`, never // `screen` — see tests/render/dom.ts for why. @@ -54,19 +55,21 @@ function replayAndRender(messages: SessionHistoryMessage[]) { } describe("a replayed user message keeps its source", () => { - test("a dictated message shows the dictation badge after replay", () => { + test("a dictated message shows the spoken mark after replay", () => { const [dictated] = replayAndRender([ { role: "user", content: "Buy oat milk", toolCalls: [], source: "voice-dictate" }, { role: "assistant", content: "Added.", toolCalls: [] }, ]); expect(dictated!.container.textContent).toContain("Buy oat milk"); - expect(dictated!.getByRole("img", { name: "Voice dictation" })).toBeTruthy(); + expect(dictated!.getByRole("img", { name: "Spoken by you" })).toBeTruthy(); + expect(dictated!.container.querySelectorAll(".bk-spoken-mark"), "one mark, inline in the turn").toHaveLength(1); }); test("a message replayed without a source renders as typed, with no badge", () => { const [typed] = replayAndRender([{ role: "user", content: "Buy oat milk", toolCalls: [] }]); expect(typed!.container.textContent).toContain("Buy oat milk"); - expect(typed!.queryByRole("img", { name: /^Voice/ })).toBeNull(); + expect(typed!.queryByRole("img", { name: /^Spoken by/ })).toBeNull(); + expect(typed!.container.querySelector(".bk-spoken-turn"), "a legacy turn is a plain bubble").toBeNull(); expect(useChatStore.getState().buffers["s1"]!.messages[0]!.source).toBe("typed"); }); }); diff --git a/packages/ui-react/tests/render/render-smoke.test.tsx b/packages/ui-react/tests/render/render-smoke.test.tsx index 3627162c9d..df7f7a876c 100644 --- a/packages/ui-react/tests/render/render-smoke.test.tsx +++ b/packages/ui-react/tests/render/render-smoke.test.tsx @@ -5861,11 +5861,11 @@ describe("ComposerView", () => { }); describe("transcript turn views", () => { - test("the header names who and when, and marks a voice turn", () => { - const view = render(); + test("the header names who and when; a voice turn's mark is inline, not in the header", () => { + const view = render(); expect(view.getByText("You")).toBeTruthy(); expect(view.getByText("09:41")).toBeTruthy(); - expect(view.getByRole("img", { name: "Voice dictation" })).toBeTruthy(); + expect(view.queryByRole("img")).toBeNull(); view.unmount(); const brain = render(); expect(brain.queryByRole("img")).toBeNull(); @@ -5880,6 +5880,10 @@ describe("transcript turn views", () => { expect(bubble?.style.borderBottomRightRadius).toBe("5px"); expect(bubble?.parentElement?.style.alignItems, "the user bubble aligns right").toBe("flex-end"); view.unmount(); + const spoken = render(hello); + expect(spoken.getByRole("img", { name: "Spoken by you" }).parentElement?.className, "a spoken turn is the kit's spoken bubble").toBe("bk-spoken-bubble"); + expect(spoken.getByText("hello").previousElementSibling?.className, "the mic leads the words").toBe("bk-spoken-mark"); + spoken.unmount(); const count = render(); expect(count.getByText("2 images")).toBeTruthy(); count.unmount();