Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/spoken-turn-marks.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 5 additions & 3 deletions packages/ui-react/src/components/chat/chat-page.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -760,7 +760,9 @@ export function ChatPage() {
{visibleEntries.map((entry) => {
if (entry.kind === "history-notice") return <p key={entry.key} className="py-3 text-sm">{entry.label}</p>;
if (entry.kind === "speech") return <ConversationOutput key={entry.key} arrivalKey={entry.key} output={entry.output} restored={entry.restored} />;
if (entry.kind === "voice-boundary") return <p key={entry.key} data-arrival-key={entry.key} tabIndex={-1} className="py-3 text-xs text-muted-foreground">{entry.label}</p>;
if (entry.kind === "voice-boundary") return entry.label === "Voice ended"
? <div key={entry.key} data-arrival-key={entry.key} tabIndex={-1} className="py-3"><ConversationEndDivider label={conversationEndLabel(entry.durationMs)} /></div>
: <p key={entry.key} data-arrival-key={entry.key} tabIndex={-1} className="py-3 text-xs text-muted-foreground">{entry.label}</p>;
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 : []);
Expand Down
8 changes: 5 additions & 3 deletions packages/ui-react/src/components/chat/message-bubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -128,7 +130,6 @@ export const MessageBubble = memo(function MessageBubble({
<TurnHeader
who={isUser ? message.source === "voice-context" ? "Conversation task" : "You" : root.config.assistantName}
when={message.turnShell ? (shellStartedAt !== null ? formatTime(shellStartedAt) : undefined) : formatTime(message.timestamp)}
voice={isUser && (message.source === "voice-dictate" || message.source === "voice-conversation") ? message.source : undefined}
effort={isUser && message.thinkingLevel !== undefined ? (
message.effectiveThinkingLevel === undefined ? `effort ${message.thinkingLevel} requested` :
message.effectiveThinkingLevel === message.thinkingLevel ? `effort ${message.thinkingLevel}` :
Expand All @@ -143,11 +144,12 @@ export const MessageBubble = memo(function MessageBubble({
) : isUser && message.source === "voice-context" ? (
taskContext ?? <ConversationTaskContext message={message} />
) : isUser ? (
<UserTurn>
<UserTurn spoken={spoken}>
{spoken && message.content && <span className="chat-message-body whitespace-pre-wrap">{linkifyPaths(message.content)}</span>}
<UserAttachments message={message} />
{!!message.files?.length && <div className="grid gap-2">{message.files.map(file => <AttachmentRow key={file.path} {...trackRowProps(file)} />)}</div>}
{!!message.attachmentFiles?.length && <div className="grid gap-2" data-sent-files="">{message.attachmentFiles.map(file => <AttachmentRow key={file.fileId} {...attachmentRowProps(file)} />)}</div>}
{message.content && (
{!spoken && message.content && (
<div className="chat-message-body text-sm leading-relaxed text-foreground whitespace-pre-wrap">
{linkifyPaths(message.content)}
</div>
Expand Down
23 changes: 8 additions & 15 deletions packages/ui-react/src/components/chat/transcript-turn.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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";
Expand All @@ -41,24 +41,17 @@ export function TurnHeader(p: TurnHeaderProps) {
</span>
{p.effort && <span className="font-[family-name:var(--font-mono)] text-[10px] text-[var(--bk-amber-ink)]">{p.effort}</span>}
<div className="h-px flex-1 bg-border/40" />
{p.voice && (
<span
role="img"
aria-label={p.voice === "voice-conversation" ? "Voice conversation" : "Voice dictation"}
className={p.voice === "voice-conversation" ? "flex text-primary/70" : "flex text-primary/50"}
>
<Icon icon="mic" size={12} />
</span>
)}
{p.when !== undefined && (
<span data-turn-time="" className="font-[family-name:var(--font-mono)] text-[10px] text-muted-foreground/40">{p.when}</span>
)}
</div>
);
}

/** 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 <SpokenTurn speaker="you">{children}</SpokenTurn>;
return (
<MessageBubble role="user" text="">
<div className="space-y-2 text-left">{children}</div>
Expand Down
59 changes: 49 additions & 10 deletions packages/ui-react/src/components/voice/conversation-outputs.tsx
Original file line number Diff line number Diff line change
@@ -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}<UncertainWord>{words}</UncertainWord>{trail}</> : <>{fragment.text}</>;
}

/** Voice-generated words share Chat's scrolling transcript; they never replace backend progress. */
export function ConversationPermissionOutcomes({ sessionId }: { sessionId: string | null }) {
Expand All @@ -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 <div className="py-4" data-arrival-key={arrivalKey} tabIndex={-1} data-conversation-output="" data-output-id={output.outputId}>
<TurnHeader who="Voice reply" tone="brain" />
<div className="whitespace-pre-wrap" style={{ overflowWrap: "anywhere" }}>{output.generated}<TranscriptQualifiers kind="generated" source={output.providerId ? conversationService(output.providerId) : undefined}
<SpokenTurn speaker="brain"><span className="whitespace-pre-wrap">{output.generated}</span></SpokenTurn>
<div className="flex"><TranscriptQualifiers kind="generated" source={output.providerId ? conversationService(output.providerId) : undefined}
playback={output.playback === "discarded" ? "not-spoken" : output.playback} restored={restored} unsaved={output.unsaved} orderUnknown={output.orderUnknown ?? restored} evidenceLabel="Technical evidence (generated reply)">
<p>Conversation {output.conversationId} · epoch {output.epoch} · output {output.outputId}</p>
{output.playedSamples && <p>Reported local samples: {output.playedSamples.start}–{output.playedSamples.end}. This does not align text to audio.</p>}
</TranscriptQualifiers></div>
{(output.orderUnknown ?? restored) && <p className="mt-2 text-xs text-muted-foreground">Original discussion position unknown.</p>}
</div>;
}

Expand Down Expand Up @@ -55,23 +74,43 @@ export function ConversationTaskContext({ message, sessionId, result, entries =
</div>;
}

/** 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 <section className="py-4 text-foreground" data-conversation-recognition="" style={{ overflowWrap: "anywhere" }}>
{introduction && <div className="mb-3 text-xs text-muted-foreground">Voice · {service} <TranscriptSymbols /></div>}
<TurnHeader who="Recognized speech" tone="neutral" />
<div className="whitespace-pre-wrap"><span data-recognized-text="">{fragments.every(f => f.moved) ? "Moved to voice review" : fragments.map(f => f.text).join("")}</span><TranscriptQualifiers
kind="recognized" source={service} finish={finish} unsaved={first.unsaved} restored={fragments.some(f=>f.restored)} orderUnknown={fragments.some(f=>f.orderUnknown)} evidenceLabel={`Technical evidence (${fragments.length} fragment${fragments.length === 1 ? "" : "s"})`}>
<SpokenTurn speaker="you" inProgress={!restored && !moved && updating > 0}><span className="whitespace-pre-wrap" data-recognized-text="">{moved ? "Moved to voice review" : fragments.map(f => <RecognizedWords key={JSON.stringify([f.kind, f.sequence])} fragment={f} />)}</span></SpokenTurn>
<div className="flex justify-end"><TranscriptQualifiers
kind="recognized" source={service} finish={finish} unsaved={first.unsaved} restored={restored} orderUnknown={fragments.some(f=>f.orderUnknown)} evidenceLabel={`Technical evidence (${fragments.length} fragment${fragments.length === 1 ? "" : "s"})`}>
<p>Recognized text evidence. Display order does not establish an exact response pairing.</p>
<ol>{fragments.map(f => <li key={JSON.stringify([f.kind, f.sequence])} className="py-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."}
</li>)}</ol>
</TranscriptQualifiers></div>
</section>;
}

/**
* 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}`;
}
13 changes: 10 additions & 3 deletions packages/ui-react/src/lib/transcript-timeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] };

Expand Down Expand Up @@ -41,6 +43,7 @@ export function createTranscriptTimeline(chat: StoreApi<ChatState>, voice: Store
return positions.get(key)!.arrival;
};
const boundaries = new Map<string, Extract<TranscriptEntry, { kind: "voice-boundary" }>>();
const opened = new Map<string, number>();
const split = new Set<string>();
const runs = new Map<string, Array<{ key: string; start: number; end: number }>>();
const textBefore = new Map<string, string>();
Expand Down Expand Up @@ -284,16 +287,20 @@ export function createTranscriptTimeline(chat: StoreApi<ChatState>, 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. */
Expand Down
Loading
Loading