diff --git a/.changeset/3698-start-card.md b/.changeset/3698-start-card.md new file mode 100644 index 0000000000..55e4984a90 --- /dev/null +++ b/.changeset/3698-start-card.md @@ -0,0 +1,11 @@ +--- +"@schlessera/brain-ui-react": minor +"@schlessera/brain-ui-kit": patch +--- + +Live conversation opens on the Start card (#3698) instead of the pre-Start disclosure sheet. + +- **Card.** The kit `StartCard` names the service Start would open, lists the full former disclosure behind "What's shared", and holds the Service row and the persona list. Change appears only when two or more services are usable, applies to this conversation only and is never saved; an unavailable saved service needs an explicit Choose. Picking a persona also saves it as the default. +- **Recovery.** A persona with no voice on the service names the default voice; a saved voice the service no longer offers blocks Start until "Use the default voice this time"; instructions over the service's byte cap block Start; an unusable persona file offers "Use Standard this time". The one-time choices go into the Start's `personaRef` and are not saved. +- **Client.** `choosePersona(ref | null)` records the persona this entry's Start sends, and `personaChoice` is in the client state. A refused first Start lets the card pick a service or persona again. +- **Kit.** The Service row's key and Change/Choose link no longer break mid-word at 320px. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index eb49090367..d29ae581e8 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -361,6 +361,7 @@ signatures (every public export and the types it is made of) conversationProfiles: ConversationProfile[]; liveDefault: LiveDefault | null; serviceChoice: string | null; + personaChoice: ConversationPersonaRef | null; livePersona: LivePersonaStatus | null; durableAvailable: boolean; sessionId: string | null; @@ -1395,6 +1396,7 @@ signatures (every public export and the types it is made of) connect: () => () => void; conversation: { attachControls(): () => void; + choosePersona(ref: import("@schlessera/brain-ui-sdk").ConversationPersonaRef | null): void; chooseService(providerId: null | string): void; commit: (own: number) => boolean; details(): void; diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 7146d1dc0c..59b71c698c 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,20 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## The Start card's persona choice (additive, 0.45.0, #3698) + +In `@schlessera/brain-ui-react`, the conversation client's state adds +`personaChoice: ConversationPersonaRef | null`, and the client adds +`choosePersona(ref | null)`: the persona this entry's Start sends as +`personaRef` instead of the saved one, including the one-time +`{ id: "standard", revision: "builtin" }` and `voice: "default"` choices. +It saves nothing and is cleared on Enter and Leave. A first Start the host +refused, which opened nothing, may choose a service or persona again; a +`CONVERSATION_PERSONA_CHANGED` refusal clears the choice. No wire or HTTP +shape changes. See +[the package API](integration-contract/package-api.md#start-card-persona-choice-3698). +This ships in a minor. + ## Host-owned web tools for Pi (additive, 0.45.0, #3685) Pi's ordinary governed and strict interactive sessions gain four diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 4a08bc5f44..2f15684b53 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4866,6 +4866,23 @@ 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. + + +### Start-card persona choice (#3698) + +Additive. The conversation client's state carries `personaChoice`, the +`ConversationPersonaRef` this entry's Start sends instead of the saved persona's +`personaRef`; `null` sends the saved one. `choosePersona(ref | null)` sets it +before Start: a persona picked on the Start card, `{ id: "standard", revision: +"builtin" }` for "Use Standard this time", or a ref with `voice: "default"` for +"Use the default voice this time". It is ignored once Start was agreed, saves +nothing, and is cleared on Enter and Leave. The host still refuses a revision +that is no longer current. When the host refuses a first Start that opened +nothing, the entry may choose its service (`chooseService`) or persona again +before the next explicit Start; a `CONVERSATION_PERSONA_CHANGED` refusal also +clears `personaChoice`. Neither call opens a microphone, reads history or +contacts a provider. + ### Retained dialogue data (#3177) The SDK protocol exports `DialogueEvidence`, `DialogueRecord`, `DialoguePage`, diff --git a/packages/ui-kit/src/tokens.css b/packages/ui-kit/src/tokens.css index 6f2848ba71..8ead89b0e6 100644 --- a/packages/ui-kit/src/tokens.css +++ b/packages/ui-kit/src/tokens.css @@ -2878,9 +2878,9 @@ html:has(dialog.bk-overlay[open]:modal) { overflow: hidden; } .bk-voice-close > span { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; background: var(--bk-color-raised); box-shadow: inset 0 0 0 1px var(--bk-color-edge); } .bk-voice-service { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 4px 0 12px; border-radius: 12px; background: var(--bk-color-surface); box-shadow: inset 0 0 0 1px var(--bk-color-edge); } .bk-voice-service[data-required="true"] { box-shadow: inset 0 0 0 1.5px var(--bk-amber-ink); } -.bk-voice-service-key { font: 600 10px/1 "JetBrains Mono", ui-monospace, monospace; letter-spacing: .08em; text-transform: uppercase; color: var(--bk-color-ink-mute); } +.bk-voice-service-key { flex: none; white-space: nowrap; font: 600 10px/1 "JetBrains Mono", ui-monospace, monospace; letter-spacing: .08em; text-transform: uppercase; color: var(--bk-color-ink-mute); } .bk-voice-service-name { flex: 1 1 auto; min-width: 0; font: 600 13px/18px "Plus Jakarta Sans", sans-serif; color: var(--bk-color-ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.bk-voice-link { appearance: none; min-height: 44px; padding: 0 10px; border: 0; border-radius: 10px; background: transparent; color: var(--bk-teal-ink); font: 600 12.5px/1 "Plus Jakarta Sans", sans-serif; cursor: pointer; } +.bk-voice-link { appearance: none; flex: none; white-space: nowrap; min-height: 44px; padding: 0 10px; border: 0; border-radius: 10px; background: transparent; color: var(--bk-teal-ink); font: 600 12.5px/1 "Plus Jakarta Sans", sans-serif; cursor: pointer; } .bk-voice-personas { display: flex; flex-direction: column; margin: 0; padding: 0; border-radius: 12px; overflow: hidden; background: var(--bk-color-surface); box-shadow: inset 0 0 0 1px var(--bk-color-edge); } .bk-voice-persona { appearance: none; display: flex; align-items: center; gap: 10px; width: 100%; min-height: 48px; margin: 0; padding: 7px 12px; border: 0; border-top: 1px solid var(--bk-color-line); background: transparent; color: var(--bk-color-ink); text-align: left; font: inherit; cursor: pointer; } .bk-voice-persona:first-child { border-top: 0; } diff --git a/packages/ui-react/README.md b/packages/ui-react/README.md index 6673697a0c..3c870566a0 100644 --- a/packages/ui-react/README.md +++ b/packages/ui-react/README.md @@ -147,8 +147,7 @@ Before Start, the conversation client exposes the pick through `chooseService(providerId | null)`, which applies to that Start only and is never saved, and `conversationProfile` is the service Start would disclose and open: the pick, else the effective service, else `null` when a pick is required. -The disclosure sheet offers that pick when several services are usable or the -saved default is unavailable; the Start card (#3698) replaces it. +The Start card draws that pick as its Service row (below). ### Live-conversation personas @@ -174,6 +173,31 @@ it per service (voice, default or stale voice, over-limit), and Start echoes its `personaRef`. A persona shapes speech only; it cannot change what brain may do, see or approve. The pane never opens the microphone or a provider. +### The Start card + +Entering live conversation opens the kit `StartCard` in place of the composer +(#3698), with focus on its Start. Its first line names the service Start would +open; **What's shared** lists the full disclosure: the service's own words and +destinations, the host relay, the agent backend, task and retention notes and +history coverage. The Service row shows **Change** only when two or more +services are usable; each press moves to the next one for this conversation +only and never saves the default. When the saved service is unavailable, the +row asks to **Choose** a service and Start stays unavailable until one is +picked; the host default is never substituted. The persona list preselects the +saved persona, and picking one also saves it as the default. + +One notice above Start says what changes it: a persona with no voice on this +service names the default voice it will use; a saved voice the service no +longer offers blocks Start until **Use the default voice this time**; persona +instructions over the service's byte cap block Start (**Edit persona** opens +Settings › Voice, or change the service); a persona file that can't be used +offers **Use Standard this time**. Those one-time choices go into the Start's +`personaRef` and are not saved. Change, a persona pick and every notice +action open no microphone, read no history and contact no provider; Start is +the only way out that does, and it sends exactly the service, persona and +voice the card shows. × or Escape leaves. A refused Start is drawn as the +stopped notice, whose **Start again** reopens the card. + ### Recording on the device Set `localCapture: true` and a stable `storagePrefix` on a persistent root to diff --git a/packages/ui-react/src/components/voice/conversation-field.tsx b/packages/ui-react/src/components/voice/conversation-field.tsx index e26ce0386e..556dd3999e 100644 --- a/packages/ui-react/src/components/voice/conversation-field.tsx +++ b/packages/ui-react/src/components/voice/conversation-field.tsx @@ -1,10 +1,10 @@ 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 { 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"; -import { liveServiceView } from "../../voice/live-service.js"; +import { ConversationStartCard } from "./start-card.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"; @@ -13,7 +13,7 @@ type LiveFieldState = "S5" | "L1" | "L2" | "L3" | "L4" | "L5" | "L6" | "L7" | "L * 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). + * while the Start card asks for one). */ function liveFieldState(s: Pick, o: { speaking: boolean; hostWork: boolean; approval: boolean }): LiveFieldState | null { @@ -87,7 +87,6 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea 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"))); @@ -121,15 +120,8 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea 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; - // #3616: the one-time pick before Start. A minimal stand-in until the Start - // card (#3698) draws it as the Service row and S3d. - const live = liveServiceView(s); - // It stays once picked, so the pick can be seen and changed before Start. - const pickable = !profile && live.services.length > 0 && (live.canChange || live.pickRequired || live.savedUnavailable !== null || s.serviceChoice !== null); const muted = s.capture === "muted"; const draft = !!s.text; const outputMuted = s.outputRecovery === "muted"; @@ -151,9 +143,9 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea : null; const meta = draft ? DRAFT_META : outputMuted ? "Reply audio off" : readiness ? "mic off" : [service, state === "S5" ? null : clock(seconds)].filter(Boolean).join(" · ") || undefined; - return
+ return
{s.announcement}
- {state === "L9" + {s.disclosureOpen ? null : state === "L9" ?
: state &&
@@ -176,35 +168,6 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea {body}
} - -
- {pickable &&
- Live service for this conversation - {live.savedUnavailable - ?

Your saved default, {conversationService(live.savedUnavailable)}, isn{"'"}t available on this host. Choose a service for this conversation.

- : live.pickRequired &&

Choose a live service for this conversation.

} - {live.services.map((option) => )} -

Applies to this conversation only. Settings › Voice keeps the default.

-
} -

{disclosed?.disclosure.voiceService ?? (pickable ? "No live service chosen yet." : "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}

} -
-
-
+ {s.disclosureOpen &&
}
; } diff --git a/packages/ui-react/src/components/voice/start-card.tsx b/packages/ui-react/src/components/voice/start-card.tsx new file mode 100644 index 0000000000..7ce35f445f --- /dev/null +++ b/packages/ui-react/src/components/voice/start-card.tsx @@ -0,0 +1,196 @@ +import { useEffect, useRef, useState } from "react"; +import { useStore } from "zustand"; +import { StartCard, type StartCardNotice, type StartCardPersona } from "@schlessera/brain-ui-kit"; +import { + STANDARD_PERSONA_ID, + STANDARD_PERSONA_REVISION, + type ConversationProfile, + type LivePersonaProviderStatus, + type LivePersonaStatus, + type LivePersonaSummary, +} from "@schlessera/brain-ui-sdk/protocol"; +import { useBrainUiRoot } from "../../root-context.js"; +import { ApiRequestError } from "../../lib/api-client.js"; +import { conversationService } from "../../voice/conversation-client.js"; +import { liveServiceView } from "../../voice/live-service.js"; + +const STANDARD: LivePersonaSummary = { id: STANDARD_PERSONA_ID, name: "Standard", voices: {}, instructionBytes: 0, revision: STANDARD_PERSONA_REVISION, builtIn: true }; + +/** + * What one persona means for one service, exactly as the host computes it + * (`providerStatus`, packages/ui-server/src/voice/personas.ts). Null: the + * persona is invalid, or the service takes no personas. + */ +function personaOnService(persona: LivePersonaSummary, profile: ConversationProfile, live: LivePersonaStatus | null): LivePersonaProviderStatus | null { + // The host's own answer for the saved persona wins whenever it is the same file. + if (live && live.persona.id === persona.id && live.persona.revision === persona.revision) return live.providers[profile.providerId] ?? null; + if (persona.invalid || !profile.voices || !profile.defaultVoice || profile.personaInstructionBytes === undefined) return null; + const saved = persona.builtIn ? undefined : persona.voices[profile.providerId]; + const offered = saved !== undefined && profile.voices.some((voice) => voice.id === saved); + return { + voice: offered ? saved : profile.defaultVoice, + voiceSource: offered ? "persona" : "default", + ...(saved !== undefined && !offered ? { staleVoice: saved } : {}), + maxInstructionBytes: profile.personaInstructionBytes, + overLimit: persona.instructionBytes > profile.personaInstructionBytes, + }; +} + +const voiceLabel = (profile: ConversationProfile, id: string) => profile.voices?.find((voice) => voice.id === id)?.label ?? id; +const count = (n: number) => n.toLocaleString("en-US"); + +/** The persona row's second line: the voice it speaks with on this service. */ +function voiceLine(persona: LivePersonaSummary, profile: ConversationProfile | null, status: LivePersonaProviderStatus | null, defaultThisTime: boolean): string | undefined { + if (!profile) return undefined; + const service = conversationService(profile.providerId); + if (persona.invalid) return "can’t be used"; + if (!status) return persona.builtIn ? undefined : `not available with ${service}`; + if (status.staleVoice !== undefined) return defaultThisTime ? `default voice ${voiceLabel(profile, status.voice)} this time` : `voice ${status.staleVoice} · no longer offered`; + if (status.voiceSource === "persona" || persona.builtIn) return `voice ${voiceLabel(profile, status.voice)}`; + return `no ${service} voice set`; +} + +/** The persona list and the saved selection's revision, read when the card opens. */ +function usePersonas(open: boolean, live: LivePersonaStatus | null) { + const root = useBrainUiRoot(); + const [list, setList] = useState(null); + const [saved, setSaved] = useState<{ value: string; revision: number } | null>(null); + // A pushed change re-reads the files, as Settings › Voice does. + useEffect(() => { + if (!open || !live) return; + let current = true; + void Promise.all([root.api.livePersonas(), root.api.voiceSettings()]).then(([personas, settings]) => { + if (!current) return; + setList(personas.personas); setSaved(settings.persona); + }, () => { if (current) setList(null); }); + return () => { current = false; }; + }, [root, open, live]); + return { list, saved, setSaved }; +} + +/** + * The Start card (#3698): the kit `StartCard` (#3692) fed with the real + * service, persona and disclosure data. It replaces the pre-Start sheet and + * shows everything that sheet showed. Nothing here starts a microphone, + * reads history or opens a provider: Change and a persona pick only record + * this entry's choice (and V2 saves the persona as the default); `Start` is + * the only way out that opens anything. + */ +export function ConversationStartCard({ backend, onLeave }: { backend: string; onLeave: () => void }) { + const root = useBrainUiRoot(); + const client = root.connection.conversation; + const s = useStore(client.state); + const chat = useStore(root.stores.connection, (state) => state.wsStatus); + const { list, saved, setSaved } = usePersonas(s.disclosureOpen, s.livePersona); + const frame = useRef(null); + // The composer that opened Start is gone; focus moves to the card's Start. + useEffect(() => { frame.current?.querySelector(".bk-voice-start")?.focus(); }, []); + + const leave = () => { client.leave(); onLeave(); }; + const live = liveServiceView(s); + const disclosed = s.conversationProfile; + const service = disclosed ? conversationService(disclosed.providerId) : null; + const pickable = !s.profile && live.services.length > 0 && (live.canChange || live.pickRequired); + const changeService = pickable ? () => { + const ids = live.services.map((option) => option.providerId); + const at = disclosed ? ids.indexOf(disclosed.providerId) : -1; + client.chooseService(ids[(at + 1) % ids.length]!); + } : undefined; + + // Personas: only on a host that resolves them (#3617). + const status = s.livePersona; + const known = list ?? (status ? [STANDARD, ...(status.persona.id === STANDARD_PERSONA_ID ? [] : [status.persona])] : []); + const choice = s.personaChoice; + const selectedId = choice?.id ?? status?.persona.id; + const personas = status ? known.filter((persona) => !persona.invalid || persona.id === selectedId) : []; + const selected = personas.find((persona) => persona.id === selectedId) ?? null; + const defaultThisTime = choice?.voice === "default"; + const onService = (persona: LivePersonaSummary) => disclosed ? personaOnService(persona, disclosed, status) : null; + const rows: StartCardPersona[] = personas.map((persona) => ({ id: persona.id, name: persona.name, + voice: voiceLine(persona, disclosed, onService(persona), persona.id === selectedId && defaultThisTime) })); + + const pickPersona = async (id: string) => { + const persona = personas.find((entry) => entry.id === id); + if (!persona || (id === selectedId && !defaultThisTime)) return; + client.choosePersona({ id: persona.id, revision: persona.revision }); + // V2: a pick on the card is also the saved default. The choice above makes + // Start send this persona even while the save is on the way. + if (!saved || saved.value === id) return; + try { + setSaved((await root.api.saveLivePersonaSelection(id, saved.revision)).persona); + } catch (error) { + if (!(error instanceof ApiRequestError && error.message === "LIVE_PERSONA_CHANGED")) return; + // Changed on another device meanwhile: this pick is newer, so it is saved over it. + try { + const current = await root.api.voiceSettings(); + setSaved((await root.api.saveLivePersonaSelection(id, current.persona.revision)).persona); + } catch { /* the one-time choice still stands for this Start */ } + } + }; + const standardThisTime = { label: "Use Standard this time", onClick: () => client.choosePersona({ id: STANDARD_PERSONA_ID, revision: STANDARD_PERSONA_REVISION }) }; + + // One notice at a time: what blocks Start first, then what Start will do differently. + const notice = ((): StartCardNotice | undefined => { + if (!disclosed && !pickable) return { kind: "block", text: s.notice || "Connecting to the configured voice service…" }; + if (!disclosed) return { kind: "block", text: live.savedUnavailable + ? `Your saved service, ${conversationService(live.savedUnavailable)}, isn’t available here. Choose a service to start.` + : "Choose a service to start." }; + if (chat !== "connected") return { kind: "block", text: "Waiting for the connection to this app’s host. Start works once it’s back." }; + if (!selected || !service) return s.notice ? { kind: "warn", text: s.notice } : undefined; + const st = onService(selected); + if (selected.invalid) return { kind: "block", text: `${selected.name} can’t be used. Edit it in Settings › Voice, or use Standard this time.`, action: standardThisTime }; + if (!st && !selected.builtIn) return { kind: "block", text: `${service} doesn’t take personas. Use Standard this time, or change the service.`, action: standardThisTime }; + if (st?.overLimit) return { kind: "block", text: `${selected.name}’s instructions are ${count(selected.instructionBytes)} bytes; ${service} takes ${count(st.maxInstructionBytes)}. Shorten them or change the service.`, + action: { label: "Edit persona", onClick: () => root.stores.ui.getState().openSettings("voice") } }; + if (st?.staleVoice !== undefined && !defaultThisTime) return { kind: "error", text: `${selected.name}’s saved voice, ${st.staleVoice}, is no longer offered by ${service}. Use the default voice this time, or edit the persona.`, + action: { label: "Use the default voice this time", onClick: () => client.choosePersona({ id: selected.id, revision: selected.revision, voice: "default" }) } }; + const warn = st?.staleVoice !== undefined ? `${selected.name}’s saved voice, ${st.staleVoice}, isn’t offered by ${service}. The default voice (${voiceLabel(disclosed, st.voice)}) is used this time.` + : st && st.voiceSource === "default" && !selected.builtIn ? `${selected.name} has no ${service} voice. The default voice (${voiceLabel(disclosed, st.voice)}) is used this time.` + : status?.selectedMissing && !choice && selected.id === STANDARD_PERSONA_ID ? `${status.selected} isn’t available — using Standard.` + : ""; + const text = [s.notice, warn].filter(Boolean).join(" "); + return text ? { kind: "warn", text } : undefined; + })(); + + // Everything the pre-Start sheet said, behind "What's shared". + const profile = s.profile; + const coverage = s.connection === "Connected" ? profile?.historyCoverage : undefined; + const relay = typeof window === "undefined" ? root.apiBase() || "this application’s host" : new URL(root.apiBase() || "/", window.location.href).origin; + const shared = [ + disclosed?.disclosure.voiceService ?? (pickable ? "No live service chosen yet." : "Connecting to the configured voice service…"), + ...(disclosed?.disclosure.destinations ?? []), + `Host relay: ${relay}`, + `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."].filter(Boolean).join(" ") : "", + "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." : "", + ].filter(Boolean); + + // "What's shared" carries the whole former sheet; opened on a small phone it + // scrolls inside the card's frame instead of running off the screen. + return
{ if (event.key === "Escape") { event.preventDefault(); leave(); } }}> + void pickPersona(id)} + notice={notice} + shared={shared} + onStart={client.start} + onCancel={leave} + /> +
; +} diff --git a/packages/ui-react/src/voice/conversation-client.ts b/packages/ui-react/src/voice/conversation-client.ts index a16bbc58b7..101a6e892d 100644 --- a/packages/ui-react/src/voice/conversation-client.ts +++ b/packages/ui-react/src/voice/conversation-client.ts @@ -2,7 +2,7 @@ import { createConversationRecovery } from "./conversation-recovery.js"; import { createConversationPermissions } from "./conversation-permissions.js"; import { createStore } from "zustand/vanilla"; import { CONVERSATION_LIMITS } from "@schlessera/brain-ui-sdk/protocol"; -import type { ClientMessage, ServerMessage, ServerConversationOpened, ConversationProfile, LiveDefault, LivePersonaStatus, ServerConversationClosed, ConversationWireEvent, ConversationWorkReceipt, ConversationOutputRecord, DialoguePage, DialogueRecord } from "@schlessera/brain-ui-sdk/protocol"; +import type { ClientMessage, ServerMessage, ServerConversationOpened, ConversationPersonaRef, ConversationProfile, LiveDefault, LivePersonaStatus, ServerConversationClosed, ConversationWireEvent, ConversationWorkReceipt, ConversationOutputRecord, DialoguePage, DialogueRecord } from "@schlessera/brain-ui-sdk/protocol"; import type { BrainUiServices } from "../root.js"; import { openConversationMicrophone, createConversationPlayback } from "./conversation-pcm.js"; @@ -81,6 +81,12 @@ export interface ConversationClientState { liveDefault: LiveDefault | null; /** The one-time pick for this entry's Start (#3616 L1/L2). Never saved. */ serviceChoice: string | null; + /** + * The persona this entry's Start sends instead of the saved one (#3698): a + * pick on the Start card while its save is on the way, "Use Standard this + * time", or "Use the default voice this time". Cleared on Enter and Leave. + */ + personaChoice: ConversationPersonaRef | null; /** * The selected live persona as the host resolves it (#3617): from * `server_hello` and every `live_persona` frame. Its `personaRef` is what @@ -134,7 +140,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, capture: "idle", interaction: "Listening", disclosureOpen: false, profile: null, conversationProfile: null, conversationProfiles: [], liveDefault: null, serviceChoice: null, livePersona: 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, conversationProfiles: [], liveDefault: null, serviceChoice: null, personaChoice: null, livePersona: 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(); @@ -180,7 +186,12 @@ export function createConversationClient(root: BrainUiServices, send: (message: * changed; a running or resumed one keeps the persona frozen at its Start. */ let agreedPersona: string | undefined; - const personaKey = () => { const ref = state.getState().livePersona?.personaRef; return ref ? `${ref.id}\u0000${ref.revision}` : ""; }; + /** What Start sends as `personaRef`: this entry's one-time choice, else the saved persona. */ + const startPersona = (): ConversationPersonaRef | undefined => { + const s = state.getState(); + return s.personaChoice ?? (s.livePersona ? { id: s.livePersona.personaRef.id, revision: s.livePersona.personaRef.revision } : undefined); + }; + const personaKey = () => { const ref = startPersona(); return ref ? `${ref.id}\u0000${ref.revision}\u0000${ref.voice ?? ""}` : ""; }; let agreedEntry: number | undefined; // The legacy hello profile, for a host without a service roster (#3616). let advertisedProfile: ConversationProfile | null = null; @@ -509,7 +520,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: pause(false, false); fragments.clear(); lastInput = undefined; utterance = null; startedService = null; - state.setState(s => ({ active: false, serviceChoice: null, text: "", disclosureOpen: false, recognition: s.recognition.filter(f => f.unsaved || f.finalization !== "interim") })); + state.setState(s => ({ active: false, serviceChoice: null, personaChoice: null, text: "", disclosureOpen: false, recognition: s.recognition.filter(f => f.unsaved || f.finalization !== "interim") })); applyLiveProfile(); if (root.stores.voice.getState().mode === "conversation") root.stores.voice.getState().setMode("idle"); if (retainedOwner && leaving && !state.getState().sessionId) { @@ -542,8 +553,8 @@ export function createConversationClient(root: BrainUiServices, send: (message: sequence = 0; utterance = null; ended = false; clearTimers(); resetRecovery(); const s = state.getState(); openingId = crypto.randomUUID(); openingEntry = entryLifetime; - const persona = s.livePersona?.personaRef; - send({ type: "conversation_start", disclosed: advertised, ...(s.conversationProfiles.length ? { providerId: advertised.providerId } : {}), contextualTasks: true, requestId: openingId, ...(persona ? { personaRef: { id: persona.id, revision: persona.revision } } : {}), ...((!s.sessionId || historyOwnerFor(s.sessionId)) && s.agentProviderId ? { agentProviderId: s.agentProviderId } : {}), ...(s.profile ? { conversationId: s.profile.conversationId } : {}), ...(s.sessionId && historyOwnerFor(s.sessionId) ? {historyOwnerId:historyOwnerFor(s.sessionId)} : s.sessionId ? { sessionId: s.sessionId } : {}) }); + const persona = startPersona(); + send({ type: "conversation_start", disclosed: advertised, ...(s.conversationProfiles.length ? { providerId: advertised.providerId } : {}), contextualTasks: true, requestId: openingId, ...(persona ? { personaRef: persona } : {}), ...((!s.sessionId || historyOwnerFor(s.sessionId)) && s.agentProviderId ? { agentProviderId: s.agentProviderId } : {}), ...(s.profile ? { conversationId: s.profile.conversationId } : {}), ...(s.sessionId && historyOwnerFor(s.sessionId) ? {historyOwnerId:historyOwnerFor(s.sessionId)} : s.sessionId ? { sessionId: s.sessionId } : {}) }); } async function capture() { const profile = scope(); @@ -856,7 +867,12 @@ export function createConversationClient(root: BrainUiServices, send: (message: if (message.type === "error" && message.code.startsWith("CONVERSATION_")) { if (message.requestId && message.requestId !== openingId) return null; openingId = undefined; pause(true, true, false); - state.setState({ notice: message.message, ...(message.code === "CONVERSATION_UNKNOWN" ? { profile: null } : {}) }); + // A refused first Start opened nothing (#3698): the Start card may pick + // a service or persona again before the next explicit Start. + if (!state.getState().profile) { startedService = null; agreedEntry = undefined; } + state.setState({ notice: message.message, ...(message.code === "CONVERSATION_UNKNOWN" ? { profile: null } : {}), + // The host just sent the current persona; a choice made against the old revision is void. + ...(message.code === "CONVERSATION_PERSONA_CHANGED" ? { personaChoice: null } : {}) }); return null; } if (message.type === "live_persona") { @@ -1098,7 +1114,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: entryLifetime++; entryProfileId = providers.pinnedId ?? agentProviderId; startedService = null; - state.setState({ serviceChoice: null }); + state.setState({ serviceChoice: null, personaChoice: null }); state.setState({ active: true, sessionId, agentProviderId, recognition: state.getState().recognition.filter(f => !f.contextual || f.sessionId === sessionId), unassigned: state.getState().unassigned.filter(f => !f.taskContext || f.sessionId === sessionId), profile: null, work: {}, connection: "Connecting", disclosureOpen: true, text: "", notice: "", interaction: "Listening" }); // A new entry needs Start even when the service matches the last visit. agreedDisclosure = undefined; @@ -1129,6 +1145,17 @@ export function createConversationClient(root: BrainUiServices, send: (message: state.setState({ serviceChoice: providerId }); applyLiveProfile(); }, + /** + * The persona this entry's Start sends (#3698), chosen on the Start card. + * It never saves anything itself; `null` returns to the saved persona. + * Ignored once Start was agreed. The host still refuses a ref whose + * revision is no longer current, so nothing stale can open. + */ + choosePersona(ref: ConversationPersonaRef | null) { + const s = state.getState(); + if (!s.active || startedService !== null || agreedEntry === entryLifetime) return; + state.setState({ personaChoice: ref && { id: ref.id, revision: ref.revision, ...(ref.voice === "default" ? { voice: "default" as const } : {}) } }); + }, 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, diff --git a/packages/ui-react/tests/browser/conversation-controls.offline.tsx b/packages/ui-react/tests/browser/conversation-controls.offline.tsx index e531641f1f..c2747cb3a4 100644 --- a/packages/ui-react/tests/browser/conversation-controls.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-controls.offline.tsx @@ -137,11 +137,13 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale flushSync(() => s.client.state.setState({ disclosureOpen: true, micOn: false })); await s.capture("disclosure"); expect(document.body.textContent).not.toContain("Refusal by voice needs headphones"); + // The Start card (#3698) keeps the former sheet's disclosure behind "What's shared". + const dialog = document.querySelector("[data-start-card]")!; + await userEvent.click(dialog.querySelector(".bk-voice-shared")!); expect(document.body.textContent).toContain("Spoken refusal is unavailable"); - const dialog = document.querySelector('[data-overlay-site="conversation-disclosure"]')!; for (const name of ["Start", "Cancel"]) { - const control = [...dialog.querySelectorAll('button,[role=button]')].find(node => node.textContent === name)!; - expect(control.getBoundingClientRect().right, `${name} fits inside disclosure`).toBeLessThanOrEqual(dialog.getBoundingClientRect().right); + const control = [...dialog.querySelectorAll('button,[role=button]')].find(node => (node.getAttribute("aria-label") ?? node.textContent) === name)!; + expect(control.getBoundingClientRect().right, `${name} fits inside the Start card`).toBeLessThanOrEqual(dialog.getBoundingClientRect().right); } await userEvent.click(page.getByRole("button", { name: "Cancel", exact: true })); expect(s.client.state.getState().active).toBe(false); @@ -161,7 +163,7 @@ for (const theme of ["light", "dark"] as const) test(`entry and connecting discl expect(s.network.socket()!.frames("conversation_start"),"ENTRY_DISCLOSES_WITHOUT_OPENING_PROVIDER").toHaveLength(0); const start=page.getByRole("button",{name:"Start",exact:true}); expect(start.element().getAttribute("aria-disabled"),"KNOWN_DISCLOSURE_ALLOWS_EXPLICIT_START").not.toBe("true"); - expect(document.querySelector('[data-overlay-site="conversation-disclosure"]')!.contains(document.activeElement),"ENTRY_DISCLOSURE_OWNS_FOCUS").toBe(true); + expect(document.querySelector("[data-start-card]")!.contains(document.activeElement),"ENTRY_DISCLOSURE_OWNS_FOCUS").toBe(true); await userEvent.click(start); expect(s.network.socket()!.frames("conversation_start")).toHaveLength(1); expect(s.network.socket()!.frames("conversation_start")[0]!.disclosed).toEqual(DISCLOSED_PROFILE); diff --git a/packages/ui-react/tests/browser/conversation.offline.tsx b/packages/ui-react/tests/browser/conversation.offline.tsx index f356ef003c..eb8b0f8e7d 100644 --- a/packages/ui-react/tests/browser/conversation.offline.tsx +++ b/packages/ui-react/tests/browser/conversation.offline.tsx @@ -75,6 +75,8 @@ test("capture truth and disclosure: a ready speech session cannot mark an unopen await s.enter(); expect(s.client.state.getState().micOn).toBe(false); expect(s.socket.frames("conversation_audio")).toHaveLength(0); + // The Start card (#3698) keeps the former sheet's disclosure behind "What's shared". + await userEvent.click(document.querySelector("[data-start-card] .bk-voice-shared")!); expect(document.body.textContent).toContain("Host relay:"); expect(document.body.textContent).toContain("Independently selected agent backend:"); await userEvent.click(s.button("Start")); @@ -1930,7 +1932,8 @@ test("live field: Listening, Speaking, Talked over, Muted and End follow real ca 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); + expect(s.host.querySelector("[data-conversation-field]")!.getAttribute("data-live-state"), "no live field before Start").toBe(null); + expect([...s.host.querySelectorAll(".bk-voice-field")].every(node => node.closest("[data-start-card]")), "the Start card is the only surface before Start").toBe(true); await userEvent.click(s.button("Start")); await expect.poll(f.state).toBe("L1"); expect(f.word()).toBe("Listening"); @@ -2082,8 +2085,8 @@ test("live field: Reconnecting while recovery runs, Stopped only when it fails, 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); + await expect.poll(() => s.client.state.getState().disclosureOpen, { message: "Start again leads to the Start card" }).toBe(true); + expect([...s.host.querySelectorAll(".bk-voice-field")].map(node => !!node.closest("[data-start-card]")), "only the Start card draws").toEqual([true]); 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 9d91ff7285..7d08501385 100644 --- a/packages/ui-react/tests/browser/dialogue-qualifiers.offline.tsx +++ b/packages/ui-react/tests/browser/dialogue-qualifiers.offline.tsx @@ -94,10 +94,11 @@ for(const unsaved of [true,false])for(const kind of ["recognition","speech"] as }); for(const providerId of ["gemini-live","gpt-live"])test(`${providerId} consent discloses durable text without audio or engine receipt`,async ctx=>{ const s=await scene(ctx,320,"light");s.ui.stores.provider.setState({available:[{id:"athena",label:"Athena",backendId:"local"}],selectedId:"athena",loaded:true});flushSync(()=>s.ui.connection.conversation.state.setState({active:true,sessionId:SESSION,connection:"Connected",profile:profile(providerId),conversationProfile:profile(providerId),durableAvailable:true,disclosureOpen:true})); - const dialog=document.querySelector("dialog[open]")!;expect(dialog.textContent).toContain("Recognized speech and generated voice replies are saved as text with this chat.");expect(dialog.textContent).toContain("This feature does not save audio.");expect(dialog.textContent).toContain("does not replay audio or prove the voice service received this history"); - const body=dialog.querySelector(".bk-overlay-body")!;body.scrollTop=0; + // The Start card (#3698) keeps the former sheet's disclosure behind "What's shared". + const dialog=document.querySelector("[data-start-card]")!;await userEvent.click(dialog.querySelector(".bk-voice-shared")!);expect(dialog.textContent).toContain("Recognized speech and generated voice replies are saved as text with this chat.");expect(dialog.textContent).toContain("This feature does not save audio.");expect(dialog.textContent).toContain("does not replay audio or prove the voice service received this history"); + dialog.scrollTop=0; await page.screenshot({element:dialog,path:`../../.vitest-attachments/durable-dialogue/consent-top-${providerId}.png`}); - [...dialog.querySelectorAll("p")].find(p=>p.textContent?.startsWith("Recognized speech and generated"))!.scrollIntoView({block:"center"}); + [...dialog.querySelectorAll("li")].find(p=>p.textContent?.startsWith("Recognized speech and generated"))!.scrollIntoView({block:"center"}); await page.screenshot({element:dialog,path:`../../.vitest-attachments/durable-dialogue/consent-retention-${providerId}.png`}); }); @@ -124,11 +125,11 @@ for(const theme of ["light","dark"] as const)for(const width of [320,1280])test( const s=await scene(ctx,width,theme);s.ui.stores.provider.setState({available:[{id:"athena",label:"Athena",backendId:"local"}],selectedId:"athena",loaded:true}); flushSync(()=>s.ui.connection.conversation.state.setState({active:true,sessionId:SESSION,connection:"Connected",conversationProfile:profile("gpt-live"),durableAvailable:true,profile:{...profile("gpt-live"),historyCoverage:{state:"bounded",tailOmitted:true}},disclosureOpen:true})); expect(s.host.textContent).toContain("Newest prior context was not sent."); - const dialog=document.querySelector("dialog[open]")!; + const dialog=document.querySelector("[data-start-card]")!;await userEvent.click(dialog.querySelector(".bk-voice-shared")!); expect(dialog.textContent).toContain("Starting voice sends bounded prior chat text and completed results to this voice service, including when you switch services."); expect(dialog.textContent).toContain("The newest prior item was not included."); expect(dialog.textContent).toContain("does not prove the service understood or recalled it"); - const paragraph=[...dialog.querySelectorAll("p")].find(p=>p.textContent?.startsWith("Starting voice sends"))!; + const paragraph=[...dialog.querySelectorAll("li")].find(p=>p.textContent?.startsWith("Starting voice sends"))!; paragraph.scrollIntoView({block:"center"}); expect(dialog.scrollWidth).toBeLessThanOrEqual(dialog.clientWidth+1); await page.screenshot({element:dialog,path:`../../.vitest-attachments/live-history/coverage-${theme}-${width}.png`}); @@ -144,11 +145,15 @@ for(const providerId of ["gemini-live","gpt-live"])for(const theme of ["light"," 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."); + // Details opens the Start card (#3698); its "What's shared" carries the coverage line. + await expect.poll(()=>document.querySelector("[data-start-card]")).not.toBeNull(); + const dialog=document.querySelector("[data-start-card]")!; expect(dialog.contains(document.activeElement),"DETAILS_RECEIVES_KEYBOARD_FOCUS").toBe(true); - [...dialog.querySelectorAll("p")].find(p=>p.textContent?.includes("The newest prior item"))!.scrollIntoView({block:"center"}); + await userEvent.click(dialog.querySelector(".bk-voice-shared")!); + expect(dialog.textContent).toContain("The newest prior item may be missing."); + [...dialog.querySelectorAll("li")].find(p=>p.textContent?.includes("The newest prior item"))!.scrollIntoView({block:"center"}); await page.screenshot({element:dialog,path:`../../.vitest-attachments/live-history/details-${providerId}-${theme}-${width}.png`}); - await userEvent.keyboard("{Escape}");await expect.poll(()=>document.querySelector("dialog[open]")).toBeNull(); + dialog.querySelector(".bk-voice-start")!.focus(); + await userEvent.keyboard("{Escape}");await expect.poll(()=>document.querySelector("[data-start-card]")).toBeNull(); expect(s.ui.connection.conversation.state.getState().micOn).toBe(false); }); diff --git a/packages/ui-react/tests/fixtures/start-card-client.tsx b/packages/ui-react/tests/fixtures/start-card-client.tsx new file mode 100644 index 0000000000..4f5223750c --- /dev/null +++ b/packages/ui-react/tests/fixtures/start-card-client.tsx @@ -0,0 +1,26 @@ +// #3698: the real chat page and its Start card against a real server with +// two keyless live-service doubles. The server, not this page, records which +// double a Start opened; the page records only what it sent. +import { createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { BrainUiProvider, ChatPage, createBrainUiRoot } from "@schlessera/brain-ui-react"; + +const root = createBrainUiRoot({ storagePrefix: "odysseus-start-card", storage: localStorage }); +const renderer = createRoot(document.getElementById("app")!); +renderer.render(createElement(BrainUiProvider, { root, children: createElement(ChatPage) })); +const conversation = root.connection.conversation; +Object.assign(window, { + __start: { + ready: () => root.stores.connection.getState().wsStatus === "connected" && conversation.state.getState().available, + connected: () => root.stores.connection.getState().wsStatus === "connected", + enter: () => conversation.enter(), + leave: () => conversation.leave(), + state: () => { + const s = conversation.state.getState(); + return { active: s.active, disclosureOpen: s.disclosureOpen, disclosed: s.conversationProfile?.providerId ?? null, + opened: s.profile?.providerId ?? null, source: s.profile?.providerSource ?? null, capture: s.capture, micOn: s.micOn, + persona: s.livePersona?.selected ?? null, personaChoice: s.personaChoice }; + }, + }, +}); +window.addEventListener("pagehide", () => root.dispose(), { once: true }); diff --git a/packages/ui-react/tests/live-service-runtime.test.ts b/packages/ui-react/tests/live-service-runtime.test.ts index 34b26fe5a4..a6944d17b4 100644 --- a/packages/ui-react/tests/live-service-runtime.test.ts +++ b/packages/ui-react/tests/live-service-runtime.test.ts @@ -187,12 +187,14 @@ async function pick(page: Page, name: RegExp) { for (let waited = 0; log.filter((entry) => entry.method === "PUT").length <= before; waited += 10) { if (waited > 10_000) throw new Error("No live settings save reached the server"); await Bun.sleep(10); } await page.waitForFunction(() => !document.querySelector("[data-live-service-settings] [role=status]")?.textContent?.includes("Saving")); } -/** Enter live conversation: the disclosure sheet, before any Start. */ +/** Enter live conversation: the Start card (#3698), before any Start, with "What's shared" open. */ async function enter(page: Page) { await page.waitForFunction("window.__live.ready()"); await page.evaluate(() => (window as unknown as { __live: { enter(): void } }).__live.enter()); await page.waitForFunction(() => (window as unknown as { __live: { state(): LiveState } }).__live.state().disclosureOpen); - return page.locator('[data-overlay-site="conversation-disclosure"]'); + const card = page.locator("[data-start-card]"); + await card.getByRole("button", { name: /What’s shared/ }).click(); + return card; } async function startAndWait(page: Page) { await page.getByRole("button", { name: "Start", exact: true }).click(); @@ -259,7 +261,7 @@ describe.skipIf(!executablePath)("Settings › Voice live service and the next S expect(await sheet.getByText("Fictional GPT-Live of Ithaca").count()).toBe(1); expect(counts(), "NO_PROVIDER_BEFORE_START").toEqual(before); expect(await gum(page), "NO_MICROPHONE_BEFORE_START").toBe(0); - await fits(page, width, "[data-live-service-pick] label"); + await fits(page, width, "[data-start-card] .bk-voice-service"); await shot(page, `live-sheet-${width}`); await startAndWait(page); expect(counts(), "SAVED_DEFAULT_OPENS").toEqual({ gemini: before.gemini, gpt: before.gpt + 1 }); @@ -278,7 +280,7 @@ describe.skipIf(!executablePath)("Settings › Voice live service and the next S // The next Start uses the new default; Change picks GPT-Live for this one only. sheet = await enter(page); expect(await sheet.getByText("Fictional Gemini Live of Ithaca").count()).toBe(1); - await sheet.getByRole("radio", { name: "GPT-Live" }).check(); + await sheet.getByRole("button", { name: "Change service, now Gemini Live" }).click(); expect(await sheet.getByText("Fictional GPT-Live of Ithaca").count(), "the disclosure follows the pick").toBe(1); expect(counts(), "a pick opens nothing").toEqual({ gemini: before.gemini, gpt: before.gpt + 1 }); await startAndWait(page); @@ -311,11 +313,11 @@ describe.skipIf(!executablePath)("Settings › Voice live service and the next S const before = counts(); const sheet = await enter(page); - expect(await sheet.locator("[data-live-service-unavailable]").textContent()).toContain("GPT-Live"); - expect(await page.getByRole("button", { name: "Start", exact: true }).isDisabled(), "S3D_START_NEEDS_PICK").toBe(true); + expect(await sheet.locator(".bk-voice-card-notice").textContent()).toContain("GPT-Live"); + expect(await page.getByRole("button", { name: "Start", exact: true }).getAttribute("aria-disabled"), "S3D_START_NEEDS_PICK").toBe("true"); expect(counts(), "S3D_NO_SUBSTITUTE").toEqual(before); await shot(page, `live-s3d-${width}`); - await sheet.getByRole("radio", { name: "Gemini Live" }).check(); + await sheet.getByRole("button", { name: "Choose a service" }).click(); await startAndWait(page); expect(counts(), "S3D_PICK_OPENS").toEqual({ gemini: before.gemini + 1, gpt: before.gpt }); expect(await saved(), "the unavailable saved default is kept").toBe("gpt-live"); diff --git a/packages/ui-react/tests/start-card-runtime.test.ts b/packages/ui-react/tests/start-card-runtime.test.ts new file mode 100644 index 0000000000..ac80541976 --- /dev/null +++ b/packages/ui-react/tests/start-card-runtime.test.ts @@ -0,0 +1,419 @@ +import { runtimePackageBuild } from "./fixtures/runtime-package-build"; +// #3698: the Start card in real Chrome against a real password-mode server. +// Two keyless live-service doubles stand in for Gemini Live and GPT-Live, +// each with its own voices and instruction cap; personas are Markdown files +// in an Odysseus brain. The server records every `open` and the options it +// was given, and the page records every frame it sent, so the card's +// disclosure is checked against what Start actually echoed. Every state runs +// at 320px and 1280px. Nothing leaves loopback. +import { runtimeHookPhases } from "./fixtures/runtime-hook-phases.ts"; +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { statSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { generateSignedCookie } from "hono/cookie"; +import { chromium, type Browser, type BrowserContext, type Page } from "playwright"; +import { createRecordingObservability, createStaticBackendRegistry, resolveServerConfig } from "@schlessera/brain-ui-server"; +import type { LiveConversationProvider } from "@schlessera/brain-ui-sdk/server"; +import { createFixtureApp as createApp } from "../../ui-server/tests/helpers/native-app-fixture.js"; +import { createPrincipal } from "../../ui-server/src/db/principals.js"; +import { makeFakeBackend } from "../../ui-server/tests/helpers/fake-backend.ts"; +import { fakeLiveProvider, type FakeLiveSession } from "../../ui-server/tests/helpers/live-conversation.ts"; + +const executablePath = [process.env.PUPPETEER_EXECUTABLE_PATH, process.env.BRAIN_UI_CHROME_PATH, + "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"] + .find((path) => path && statSync(path, { throwIfNoEntry: false })?.isFile()); +if (!executablePath && process.env.BRAIN_REQUIRE_CHROME === "1") throw new Error("Start card runtime proof requires real Chrome"); +if (!executablePath) console.warn("SKIPPING Start card runtime proof: no Chrome; the Start card is unverified locally."); + +const repo = resolve(import.meta.dir, "../../.."); +const SECRET = "start-card-runtime-secret-0123456789"; +/** The phone the card must fit (#3698), and a desktop. */ +const SIZES = [[320, 640], [1280, 860]] as const; +const SHOTS = process.env.BRAIN_START_CARD_SCREENSHOTS; +const hook = runtimeHookPhases("start-card-runtime"); + +type Id = "gemini-live" | "gpt-live"; +const SPEECH: Record> = { + "gemini-live": { voices: [{ id: "Kore", label: "Kore" }, { id: "Puck", label: "Puck" }], defaultVoice: "Kore", personaInstructionBytes: 2_000 }, + "gpt-live": { voices: [{ id: "marin", label: "marin" }, { id: "cedar", label: "cedar" }], defaultVoice: "marin", personaInstructionBytes: 1_500 }, +}; +/** Every session each double opened, across restarts. */ +const opened: Record = { "gemini-live": [], "gpt-live": [] }; +function double(id: Id): LiveConversationProvider { + const fake = fakeLiveProvider(); + const voiceService = id === "gemini-live" ? "Fictional Gemini Live of Ithaca" : "Fictional GPT-Live of Ithaca"; + return { ...fake.provider, ...SPEECH[id], id, disclosure: { ...fake.provider.disclosure, voiceService }, + open: async (scope, options) => { const session = await fake.provider.open(scope, options); opened[id].push(fake.sessions.at(-1)!); return session; } }; +} +const counts = () => ({ gemini: opened["gemini-live"].length, gpt: opened["gpt-live"].length }); + +/** Odysseus personas, as `_voice/personas/.md`. */ +const PERSONAS = { + "ithaca-steward": { name: "Ithaca steward", voices: { "gemini-live": "Puck", "gpt-live": "cedar" }, text: "Calm, brief, plain words." }, + // No GPT-Live voice: S3 on GPT-Live. + "harbour-storyteller": { name: "Harbour storyteller", voices: { "gemini-live": "Puck" }, text: "Slow and warm, with the sea in it." }, + // Orion is no longer offered by Gemini Live: S3b. + "palace-herald": { name: "Palace herald", voices: { "gemini-live": "Orion", "gpt-live": "cedar" }, text: "Loud and clear, for the great hall." }, + // 1,709 bytes: over GPT-Live's 1,500, under Gemini Live's 2,000 (S3c). + "long-bard": { name: "Long-winded bard", voices: { "gemini-live": "Puck", "gpt-live": "cedar" }, text: "Sing of the wrath. ".repeat(90) }, +} as const; +type PersonaId = keyof typeof PERSONAS; + +let fixture = "", brain = "", assets = "", origin = "", port = 0; +let app: Awaited> | undefined; +let server: ReturnType | undefined; +let browser: Browser | undefined; +let owner = ""; +/** Every `/api/settings/voice` write, in order, with its body. */ +const writes: Array<{ status: number; body: Record }> = []; + +async function start(ids: Id[], hostDefault?: Id) { + app = await hook.phase("host-start", () => createApp({ + config: resolveServerConfig({ BRAIN_PATH: brain, DB_PATH: resolve(fixture, "ui.db"), + AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: "unused-fixture-hash", COOKIE_SECRET: SECRET, BRAIN_UI_ALLOW_LOOPBACK_ORIGIN: "1", + HOST: "127.0.0.1", NODE_ENV: "test", BRAIN_UI_PRICING_DISCOVERY: "0", BRAIN_UI_MODEL_DISCOVERY: "0" }), + registry: createStaticBackendRegistry([makeFakeBackend({ id: "start-fixture" })], "start-fixture"), + staticRoot: assets, observability: createRecordingObservability(), + conversationProviders: ids.map(double), + ...(hostDefault ? { defaultConversationProviderId: hostDefault } : {}), + })); + const current = app; + const handle = async (request: Request, bun: unknown) => { + const url = new URL(request.url); + const body = url.pathname === "/api/settings/voice" && request.method === "PUT" ? await request.clone().json().catch(() => ({})) as Record : null; + const response = await current.fetch(request, bun as never); + if (body) writes.push({ status: response?.status ?? 0, body }); + return response; + }; + for (let attempt = 0; ; attempt++) { + try { + server = Bun.serve({ hostname: "127.0.0.1", port, fetch: handle, websocket: current.websocket }); + break; + } catch (error) { if (attempt > 20) throw error; await Bun.sleep(50); } + } + port = server.port!; + origin = `http://127.0.0.1:${port}`; +} +async function restart(ids: Id[], hostDefault?: Id) { + await closeAll(); + server?.stop(true); + await app?.close(); + await start(ids, hostDefault); +} + +beforeAll(async () => { + if (!executablePath) return; + await runtimePackageBuild(repo, ["ui-react", "ui-server", "core"], hook); + fixture = await mkdtemp(resolve(tmpdir(), "odysseus-start-card-")); + brain = resolve(fixture, "brain"); + await mkdir(resolve(brain, "notes"), { recursive: true }); + await writeFile(resolve(brain, "notes", "ithaca.md"), "# Ithaca\n\nOdysseus is expected home on 2026-07-12.\n"); + assets = resolve(fixture, "assets"); + await mkdir(assets); + const bundle = Bun.spawn([process.execPath, "-e", 'const r=await Bun.build({entrypoints:[process.argv[1]],target:"browser",outdir:process.argv[2],naming:"client.js"});if(!r.success){console.error(r.logs);process.exit(1)}', resolve(import.meta.dir, "fixtures/start-card-client.tsx"), assets], { cwd: repo, stdout: "pipe", stderr: "pipe", stdin: "ignore" }); + const [out, err, code] = await hook.child("client-build", bundle); + if (code !== 0) throw new Error(`Start card client build failed (${code}): ${out}\n${err}`); + await writeFile(resolve(assets, "index.html"), 'Odysseus Start card
'); + for (const [name, pkg] of [["kit.css", "ui-kit"], ["app.css", "ui-react"]]) await writeFile(resolve(assets, name!), await readFile(resolve(repo, `packages/${pkg}/dist/styles.css`))); + await start(["gemini-live", "gpt-live"]); + const principal = createPrincipal(app!.db, { authMethod: "password", label: "Penelope's phone", ttlSeconds: 3600 }); + owner = (await generateSignedCookie("brain_ui_session", principal.id, SECRET)).split(";")[0]!.slice("brain_ui_session=".length); + browser = await hook.phase("chrome-launch", () => chromium.launch({ executablePath, headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage", "--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream"] })); +}, 240_000); + +afterAll(() => hook.phase("cleanup", async () => { + await closeAll(); + await browser?.close(); + server?.stop(true); + await app?.close(); + if (fixture) await rm(fixture, { recursive: true, force: true }); +})); + +/* ── The owner's other device, through the real routes ─────────────────── */ + +const headers = () => ({ cookie: `brain_ui_session=${owner}`, origin, "content-type": "application/json" }); +type VoiceSettings = { defaultProvider: string | null; revision: number; persona: { value: string; revision: number } }; +const settings = async () => await (await fetch(`${origin}/api/settings/voice`, { headers: headers() })).json() as VoiceSettings; +async function put(body: Record) { + const response = await fetch(`${origin}/api/settings/voice`, { method: "PUT", headers: headers(), body: JSON.stringify(body) }); + expect(response.status, "the other device saved").toBe(200); +} +/** Writes exactly these persona files, then saves the selection and the live default. */ +async function brainWith(personas: PersonaId[], selected: PersonaId | "standard", service: Id | null) { + const dir = resolve(brain, "_voice/personas"); + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); + for (const id of personas) { + const p = PERSONAS[id]; + await writeFile(resolve(dir, `${id}.md`), `---\nschema: 1\nname: "${p.name}"\nvoices:\n${Object.entries(p.voices).map(([k, v]) => ` ${k}: "${v}"`).join("\n")}\n---\n${p.text}\n`); + } + const current = await settings(); + await put({ persona: { value: selected, revision: current.persona.revision } }); + const now = await settings(); + if (now.defaultProvider !== service) await put({ defaultProvider: service, revision: now.revision }); +} +const revisionOf = async (id: string) => + ((await (await fetch(`${origin}/api/voice/personas`, { headers: headers() })).json()) as { personas: Array<{ id: string; revision: string }> }).personas.find((p) => p.id === id)!.revision; + +/* ── The page ─────────────────────────────────────────────────────────── */ + +const contexts: BrowserContext[] = []; +async function open(width: number, height: number): Promise { + const context = await browser!.newContext({ viewport: { width, height }, hasTouch: width < 900 }); + contexts.push(context); + await context.addCookies([{ name: "brain_ui_session", value: owner, url: `http://127.0.0.1:${port}` }]); + await context.route("**/*", (route) => new URL(route.request().url()).hostname === "127.0.0.1" ? route.continue() : route.abort()); + // Count every microphone request and every frame the page sends, from its first script on. + await context.addInitScript(() => { + const scope = window as unknown as { __gum: number; __sent: Array> }; + scope.__gum = 0; scope.__sent = []; + const media = navigator.mediaDevices; + const original = media.getUserMedia.bind(media); + media.getUserMedia = (constraints) => { scope.__gum++; return original(constraints); }; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (typeof data === "string") try { scope.__sent.push(JSON.parse(data) as Record); } catch { /* not a frame */ } + return send.call(this, data); + }; + }); + const page = await context.newPage(); + await page.goto(origin); + await page.waitForFunction("window.__start?.connected()"); + return page; +} +async function closeAll() { for (const context of contexts.splice(0)) await context.close(); } + +type StartState = { active: boolean; disclosureOpen: boolean; disclosed: string | null; opened: string | null; source: string | null; capture: string; micOn: boolean; persona: string | null; + personaChoice: { id: string; revision: string; voice?: string } | null }; +const state = (page: Page) => page.evaluate(() => (window as unknown as { __start: { state(): StartState } }).__start.state()); +const gum = (page: Page) => page.evaluate(() => (window as unknown as { __gum: number }).__gum); +const sent = (page: Page) => page.evaluate(() => (window as unknown as { __sent: Array> }).__sent); +/** Frames that would start a provider, a microphone stream or a history read for one. */ +const starting = async (page: Page) => (await sent(page)).filter((frame) => String(frame.type).startsWith("conversation_")).map((frame) => frame.type); +async function shot(page: Page, name: string) { + if (!SHOTS) return; + await mkdir(SHOTS, { recursive: true }); + await page.waitForTimeout(450); + await page.screenshot({ path: resolve(SHOTS, `${name}.png`) }); +} + +/** Enter live conversation: the Start card, before any Start, with its persona list read. */ +async function enter(page: Page, personas: number) { + await page.waitForFunction("window.__start.ready()"); + await page.evaluate(() => (window as unknown as { __start: { enter(): void } }).__start.enter()); + const card = page.locator("[data-start-card]"); + await card.waitFor(); + await page.waitForFunction((n) => document.querySelectorAll("[data-start-card] [role=radio]").length === n, personas); + return card; +} +const line = (page: Page) => page.locator("[data-start-card] .bk-voice-card-line").textContent(); +const notice = (page: Page) => page.locator("[data-start-card] .bk-voice-card-notice").textContent(); +const startButton = (page: Page) => page.locator("[data-start-card] .bk-voice-start"); +/** Nothing has started: no frame toward a provider, no microphone, no double opened. */ +async function nothingStarted(page: Page, before: ReturnType, what: string) { + expect(await starting(page), `${what}: NO_CONVERSATION_FRAME_BEFORE_START`).toEqual([]); + expect(await gum(page), `${what}: NO_MICROPHONE_BEFORE_START`).toBe(0); + expect(counts(), `${what}: NO_PROVIDER_BEFORE_START`).toEqual(before); + const s = await state(page); + expect(s.micOn || s.capture !== "idle", `${what}: NO_CAPTURE_BEFORE_START`).toBe(false); +} +/** A blocked Start does nothing when pressed. */ +async function startRefused(page: Page, before: ReturnType, what: string) { + expect(await startButton(page).getAttribute("aria-disabled"), `${what}: START_BLOCKED`).toBe("true"); + // aria-disabled keeps it focusable; a forced press still reaches the handler. + await startButton(page).click({ force: true }); + await page.waitForTimeout(150); + await nothingStarted(page, before, what); +} +async function startAndWait(page: Page) { + await startButton(page).click(); + await page.waitForFunction(() => (window as unknown as { __start: { state(): StartState } }).__start.state().opened !== null); + const frames = (await sent(page)).filter((frame) => frame.type === "conversation_start"); + expect(frames, "one Start, one conversation_start").toHaveLength(1); + return frames[0]! as { providerId?: string; disclosed: { providerId: string }; personaRef?: { id: string; revision: string; voice?: string } }; +} +async function leave(page: Page) { + await page.evaluate(() => (window as unknown as { __start: { leave(): void } }).__start.leave()); + await page.waitForFunction(() => !(window as unknown as { __start: { state(): StartState } }).__start.state().active); +} +/** The card sits wholly inside the viewport, with no horizontal page scroll, and Start and Cancel in reach. */ +async function fits(page: Page, width: number, height: number) { + expect(await page.evaluate(() => document.documentElement.scrollWidth), `no horizontal scroll at ${width}px`).toBeLessThanOrEqual(width); + for (const selector of ["[data-start-card]", "[data-start-card] .bk-voice-start", "[data-start-card] [aria-label=Cancel]"]) { + const box = (await page.locator(selector).boundingBox())!; + expect(box.x, `${selector} inside the left edge`).toBeGreaterThanOrEqual(0); + expect(box.x + box.width, `${selector} inside the right edge`).toBeLessThanOrEqual(width); + expect(box.y, `${selector} inside the top edge`).toBeGreaterThanOrEqual(0); + expect(box.y + box.height, `${selector} fits ${width}×${height}`).toBeLessThanOrEqual(height); + } + // Whatever "What's shared" opened can be scrolled to inside the card. + const last = page.locator("[data-start-card] .bk-voice-shared-list li").last(); + if (await last.count()) { + await last.scrollIntoViewIfNeeded(); + const box = (await last.boundingBox())!; + expect(box.y + box.height, "the last shared line is reachable").toBeLessThanOrEqual(height); + await page.locator("[data-start-card]").evaluate((node) => { node.scrollTop = 0; }); + } +} + +describe.skipIf(!executablePath)("the Start card against mounted routes and two live-service doubles", () => { + for (const [width, height] of SIZES) test(`${width}px: three personas and the Service row fit; a pick is saved (V2), Change is not; nothing starts before Start; Start sends what the card shows`, async () => { + await restart(["gemini-live", "gpt-live"]); + await brainWith(["ithaca-steward", "harbour-storyteller"], "ithaca-steward", "gemini-live"); + const page = await open(width, height); + const before = counts(); + const card = await enter(page, 3); + await fits(page, width, height); + await shot(page, `start-s2-${width}`); + // S2+: several services, the saved one named, the last persona preselected. + expect(await line(page)).toBe("Gemini Live hears you and reads this chat."); + expect(await card.getByRole("button", { name: "Change service, now Gemini Live" }).count()).toBe(1); + expect(await card.getByRole("radio", { name: /Ithaca steward/ }).getAttribute("aria-checked"), "the last pick is preselected").toBe("true"); + expect(await card.getByRole("radio", { name: /Ithaca steward/ }).textContent()).toContain("voice Puck"); + expect(await card.getByRole("radio", { name: /Standard/ }).textContent()).toContain("voice Kore"); + expect(await page.evaluate(() => document.activeElement?.classList.contains("bk-voice-start")), "the card takes focus on its Start").toBe(true); + // "What's shared" keeps everything the disclosure sheet said. + await card.getByRole("button", { name: /What’s shared/ }).click(); + const shared = await card.locator(".bk-voice-shared-list").textContent(); + for (const text of ["Fictional Gemini Live of Ithaca", "Host relay: ", "Independently selected agent backend:", "Starting voice sends bounded prior chat text", "Spoken refusal is unavailable"]) + expect(shared, `shared: ${text}`).toContain(text); + await nothingStarted(page, before, "S2"); + + // Change: this conversation only, never saved. + const writesBefore = writes.length; + await card.getByRole("button", { name: "Change service, now Gemini Live" }).click(); + await page.waitForLoadState("networkidle"); + await nothingStarted(page, before, "after Change"); + expect(await line(page)).toBe("GPT-Live hears you and reads this chat."); + expect(await card.locator(".bk-voice-shared-list").textContent(), "the disclosure follows the Change").toContain("Fictional GPT-Live of Ithaca"); + await page.waitForLoadState("networkidle"); + expect(writes.slice(writesBefore).filter((w) => "defaultProvider" in w.body), "CHANGE_IS_NOT_SAVED").toEqual([]); + + // V2: picking a persona also saves it as the default, and S3 names the default voice. + await card.getByRole("radio", { name: /Harbour storyteller/ }).click(); + await page.waitForLoadState("networkidle"); + await nothingStarted(page, before, "after a persona pick"); + for (let waited = 0; (await settings()).persona.value !== "harbour-storyteller" && waited < 5_000; waited += 50) await Bun.sleep(50); + expect((await settings()).persona.value, "V2_PICK_IS_SAVED").toBe("harbour-storyteller"); + await page.waitForFunction(() => (window as unknown as { __start: { state(): StartState } }).__start.state().persona === "harbour-storyteller"); + expect(writes.slice(writesBefore).map((w) => Object.keys(w.body)), "only the persona was written").toEqual([["persona"]]); + expect(await notice(page)).toBe("Harbour storyteller has no GPT-Live voice. The default voice (marin) is used this time."); + expect(await card.getByRole("radio", { name: /Harbour storyteller/ }).textContent()).toContain("no GPT-Live voice set"); + expect(await startButton(page).getAttribute("aria-disabled"), "S3 keeps Start").toBe(null); + await fits(page, width, height); + await shot(page, `start-s3-${width}`); + + // Start sends exactly what the card discloses. + const echo = await startAndWait(page); + expect(echo.providerId, "ECHO_SERVICE").toBe("gpt-live"); + expect(echo.disclosed.providerId).toBe("gpt-live"); + expect(echo.personaRef, "ECHO_PERSONA").toEqual({ id: "harbour-storyteller", revision: await revisionOf("harbour-storyteller") }); + expect(counts(), "the Change opened GPT-Live").toEqual({ gemini: before.gemini, gpt: before.gpt + 1 }); + expect(opened["gpt-live"].at(-1)!.options?.persona, "ECHO_DEFAULT_VOICE: no voice option, so the service default (marin)").toEqual({ instructions: PERSONAS["harbour-storyteller"].text }); + expect((await state(page)).source).toBe("change"); + expect((await settings()).defaultProvider, "CHANGE_IS_NOT_SAVED after Start").toBe("gemini-live"); + await leave(page); + }, 120_000); + + for (const [width, height] of SIZES) test(`${width}px: S3b a saved voice no longer offered blocks Start until the default voice is chosen for this time`, async () => { + await restart(["gemini-live"]); + await brainWith(["palace-herald", "ithaca-steward"], "palace-herald", null); + const page = await open(width, height); + const before = counts(); + const card = await enter(page, 3); + expect(await card.getByRole("button", { name: /Change service/ }).count(), "one service: no Change").toBe(0); + expect(await notice(page)).toBe("Palace herald’s saved voice, Orion, is no longer offered by Gemini Live. Use the default voice this time, or edit the persona."); + await fits(page, width, height); + await shot(page, `start-s3b-${width}`); + await startRefused(page, before, "S3b"); + await card.getByRole("button", { name: "Use the default voice this time" }).click(); + expect(await notice(page)).toBe("Palace herald’s saved voice, Orion, isn’t offered by Gemini Live. The default voice (Kore) is used this time."); + expect(await card.getByRole("radio", { name: /Palace herald/ }).textContent()).toContain("default voice Kore this time"); + await nothingStarted(page, before, "after choosing the default voice"); + const echo = await startAndWait(page); + expect(echo.personaRef, "ECHO_DEFAULT_VOICE_CHOICE").toEqual({ id: "palace-herald", revision: await revisionOf("palace-herald"), voice: "default" }); + expect(opened["gemini-live"].at(-1)!.options?.persona, "the service's default voice, not a substitute").toEqual({ instructions: PERSONAS["palace-herald"].text }); + expect((await settings()).persona.value, "the one-time voice choice saves nothing").toBe("palace-herald"); + await leave(page); + }, 120_000); + + for (const [width, height] of SIZES) test(`${width}px: S3c instructions over the service's cap block Start; Change to a service that takes them`, async () => { + await restart(["gemini-live", "gpt-live"]); + await brainWith(["long-bard", "ithaca-steward"], "long-bard", "gpt-live"); + const page = await open(width, height); + const before = counts(); + const card = await enter(page, 3); + expect(await notice(page)).toBe("Long-winded bard’s instructions are 1,709 bytes; GPT-Live takes 1,500. Shorten them or change the service."); + expect(await card.getByRole("button", { name: "Edit persona" }).count()).toBe(1); + await fits(page, width, height); + await shot(page, `start-s3c-${width}`); + await startRefused(page, before, "S3c"); + await card.getByRole("button", { name: "Change service, now GPT-Live" }).click(); + expect(await card.locator(".bk-voice-card-notice").count(), "Gemini Live takes them").toBe(0); + const echo = await startAndWait(page); + expect(echo.providerId).toBe("gemini-live"); + expect(echo.personaRef).toEqual({ id: "long-bard", revision: await revisionOf("long-bard") }); + expect(opened["gemini-live"].at(-1)!.options?.persona).toEqual({ voice: "Puck", instructions: PERSONAS["long-bard"].text.trim() }); + expect(counts()).toEqual({ gemini: before.gemini + 1, gpt: before.gpt }); + expect((await settings()).defaultProvider, "CHANGE_IS_NOT_SAVED").toBe("gpt-live"); + await leave(page); + }, 120_000); + + for (const [width, height] of SIZES) test(`${width}px: S3d the saved service is unavailable; an explicit pick is required and never substituted`, async () => { + await restart(["gemini-live", "gpt-live"]); + await brainWith(["ithaca-steward"], "ithaca-steward", "gpt-live"); + await restart(["gemini-live"], "gemini-live"); + const page = await open(width, height); + const before = counts(); + const card = await enter(page, 2); + expect(await line(page)).toBe("A live service hears you and reads this chat."); + expect(await notice(page)).toBe("Your saved service, GPT-Live, isn’t available here. Choose a service to start."); + expect(await card.locator(".bk-voice-service-name").textContent(), "S3D_NO_SUBSTITUTE").toBe("Choose a service"); + await fits(page, width, height); + // The required-service row keeps its key and its Choose on one line each, even at 320px. + for (const selector of [".bk-voice-service-key", ".bk-voice-service .bk-voice-link"]) + expect(await card.locator(selector).evaluate((node) => { const range = document.createRange(); range.selectNodeContents(node); return new Set([...range.getClientRects()].map((r) => Math.round(r.top))).size; }), `${selector} stays on one line`).toBe(1); + await shot(page, `start-s3d-${width}`); + await startRefused(page, before, "S3d"); + await card.getByRole("button", { name: "Choose a service" }).click(); + expect(await line(page)).toBe("Gemini Live hears you and reads this chat."); + await nothingStarted(page, before, "after the pick"); + const echo = await startAndWait(page); + expect(echo.providerId).toBe("gemini-live"); + expect(counts(), "S3D_PICK_OPENS").toEqual({ gemini: before.gemini + 1, gpt: before.gpt }); + expect((await settings()).defaultProvider, "the unavailable saved default is kept").toBe("gpt-live"); + await leave(page); + }, 120_000); + + for (const [width, height] of SIZES) test(`${width}px: a persona edited before Start is refused as a VoiceNotice; Start again reopens the card`, async () => { + await restart(["gemini-live"]); + await brainWith(["ithaca-steward"], "standard", null); + const page = await open(width, height); + const before = counts(); + const picked = await enter(page, 2); + // Picked on the card, so this Start is pinned to the revision the card showed, + // whenever the host's fresh persona status reaches the page. + await picked.getByRole("radio", { name: /Ithaca steward/ }).click(); + await page.waitForFunction(() => (window as unknown as { __start: { state(): StartState } }).__start.state().persona === "ithaca-steward"); + expect((await state(page)).personaChoice, "the card's pick is what Start sends").toEqual({ id: "ithaca-steward", revision: await revisionOf("ithaca-steward") }); + // Another device edits the persona after the card read it. + const p = PERSONAS["ithaca-steward"]; + await writeFile(resolve(brain, "_voice/personas/ithaca-steward.md"), `---\nschema: 1\nname: "${p.name}"\nvoices:\n gemini-live: "Kore"\n---\nSlower now.\n`); + await startButton(page).click(); + const stopped = page.locator("[data-conversation-field] .bk-voice-notice, [data-conversation-field] [role=alert], [data-conversation-field]").getByText("Live conversation stopped"); + await stopped.waitFor(); + expect(await page.locator("[data-conversation-field]").textContent()).toContain("The persona changed. Review it and select Start again."); + expect(counts(), "REFUSED_START_OPENS_NOTHING").toEqual(before); + await shot(page, `start-refused-${width}`); + await page.getByRole("button", { name: "Start again" }).click(); + const card = page.locator("[data-start-card]"); + await card.waitFor(); + await page.waitForFunction(() => document.querySelector("[data-start-card] [role=radio][aria-checked=true]")?.textContent?.includes("voice Kore")); + await startButton(page).click(); + await page.waitForFunction(() => (window as unknown as { __start: { state(): StartState } }).__start.state().opened !== null); + expect(opened["gemini-live"].at(-1)!.options?.persona, "the edited persona, as the card showed it").toEqual({ voice: "Kore", instructions: "Slower now." }); + await leave(page); + }, 120_000); +}); diff --git a/scripts/runtime-test-builds.ts b/scripts/runtime-test-builds.ts index f19ac637b1..d21af7694b 100644 --- a/scripts/runtime-test-builds.ts +++ b/scripts/runtime-test-builds.ts @@ -4,7 +4,7 @@ import { isAbsolute, join, resolve } from "node:path"; export const runtimeTestBuilds: Readonly> = Object.fromEntries([ "answer-delivery", "approval-recovery", "artifact-recovery", "attachment-read", "association-signout", "auth-expiry", "chat-focus", - "connection-continuity", "dictation-selection", "draft", "ended-question", "external-speech", "html-preview", "live-service", "local-work", "parallel-sessions", "persona-settings", "scratch-links", "tracker", "turn-journal", "untrusted-marks", + "connection-continuity", "dictation-selection", "draft", "ended-question", "external-speech", "html-preview", "live-service", "local-work", "parallel-sessions", "persona-settings", "scratch-links", "start-card", "tracker", "turn-journal", "untrusted-marks", ].map(name => [`packages/ui-react/tests/${name}-runtime.test.ts`, ["ui-react", "ui-server", "core"]])); const special: Readonly> = { "packages/ui-react/tests/haiku-model-runtime.test.ts": ["ui-react"], diff --git a/tests/runtime-build-selection.test.ts b/tests/runtime-build-selection.test.ts index ec93c8ba59..37607aa478 100644 --- a/tests/runtime-build-selection.test.ts +++ b/tests/runtime-build-selection.test.ts @@ -9,7 +9,7 @@ const root = resolve(import.meta.dir, ".."); test("every runtime package hook has one inventoried actual forward closure and no boolean bypass", async () => { const directory = join(root, "packages/ui-react/tests"); const hooks = readdirSync(directory).filter(name => name.endsWith(".test.ts") && readFileSync(join(directory, name), "utf8").includes("runtimePackageBuild(")); - expect(hooks).toHaveLength(23); + expect(hooks).toHaveLength(24); expect(hooks.map(name => `packages/ui-react/tests/${name}`).sort()).toEqual(Object.keys(runtimeBuildInventory).sort()); for (const file of hooks) { const text = readFileSync(join(directory, file), "utf8");