From d3ef9c279e0773584519bd83caf8f5f208cc49e9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:57:03 +0000 Subject: [PATCH 01/11] CONTRACT: feat(ui-server): register several live services and resolve each Start (#3616) createApp accepts conversationProviders and defaultConversationProviderId; conversationProvider still means a list of one. Startup fails on both options, duplicate ids or an unregistered host default. A new Start uses a one-time pick (conversation_start.providerId, which must equal the disclosed profile), else the saved default only if registered, else the host default or the only service when nothing is saved, else none. A saved but unusable default never falls through. A resume keeps the service its conversation opened with. server_hello adds conversationProfiles and liveDefault and keeps conversationProfile only while a service is effective (R1). A save sends live_settings to open connections. conversation_opened adds providerSource. GET/PUT /api/settings/voice read and save voice.live.defaultProvider in the settings store, behind a new owner-only write guard (owner password/passkey session or ambient human; 403 with an empty body otherwise), with 400 LIVE_PROVIDER_UNKNOWN and 409 LIVE_SETTINGS_CHANGED. Co-Authored-By: Claude Opus 5.5 --- api-report/ui-sdk.txt | 382 +++++++++++++++++- api-report/ui-server.txt | 12 + docs/http-api-coverage.md | 4 + docs/http-api.md | 36 +- .../hooks/websocket-handlers/connection.ts | 4 +- packages/ui-sdk/src/protocol.ts | 72 +++- packages/ui-sdk/src/schemas.ts | 33 ++ packages/ui-sdk/tests/server-schemas.test.ts | 32 ++ packages/ui-server/src/app.ts | 21 +- packages/ui-server/src/db/settings-writes.ts | 2 + packages/ui-server/src/db/settings.ts | 28 ++ .../ui-server/src/routes/live-settings.ts | 82 ++++ .../ui-server/src/voice/live-providers.ts | 73 ++++ packages/ui-server/src/ws/connection.ts | 4 +- packages/ui-server/src/ws/conversation.ts | 119 +++++- packages/ui-server/src/ws/host.ts | 25 +- .../tests/helpers/http-contract-app.ts | 3 + .../tests/helpers/http-mount-lifetimes.ts | 2 + .../tests/http-supported-mounts.test.ts | 2 + .../tests/live-provider-selection.test.ts | 310 ++++++++++++++ .../ui-server/tests/ws-conversation.test.ts | 4 +- 21 files changed, 1216 insertions(+), 34 deletions(-) create mode 100644 packages/ui-server/src/routes/live-settings.ts create mode 100644 packages/ui-server/src/voice/live-providers.ts create mode 100644 packages/ui-server/tests/live-provider-selection.test.ts diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 9b6bd7b28f..9daa5ab1dc 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -254,6 +254,8 @@ export "." (./src/index.ts) type Keyterm LIVENESS_CAPABILITY LOCAL_ANSWER_CLOSE + type LiveDefault + type LiveProviderSource type LocalAnswer type LocalExchange MAX_IMAGES_PER_MESSAGE @@ -350,6 +352,7 @@ export "." (./src/index.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -469,6 +472,8 @@ export "." (./src/index.ts) type V1ResolutionEffect type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -856,6 +861,8 @@ export "./client" (./src/client/index.ts) LIVENESS_RESPONSE_MS LOCAL_ANSWER_CLOSE LOCATION_PAYLOAD_SCHEMA + type LiveDefault + type LiveProviderSource type LivenessEvent type LocalAnswer type LocalExchange @@ -1006,6 +1013,7 @@ export "./client" (./src/client/index.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -1144,6 +1152,8 @@ export "./client" (./src/client/index.ts) type V1ResolutionEffect type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -1728,6 +1738,8 @@ export "./protocol" (./src/protocol.ts) type Keyterm LIVENESS_CAPABILITY LOCAL_ANSWER_CLOSE + type LiveDefault + type LiveProviderSource type LocalAnswer type LocalExchange MAX_IMAGES_PER_MESSAGE @@ -1819,6 +1831,7 @@ export "./protocol" (./src/protocol.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -1938,6 +1951,8 @@ export "./protocol" (./src/protocol.ts) type V1ResolutionEffect type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -2028,6 +2043,7 @@ export "./schemas" (./src/schemas.ts) conversationLimitsSchema conversationOutputRecordSchema conversationProfileSchema + conversationProfilesSchema conversationSampleRateSchema conversationWireEventSchema conversationWorkReceiptSchema @@ -2073,6 +2089,7 @@ export "./schemas" (./src/schemas.ts) inboxThreadSchema inboxViewSchema inboxWorkPayloadSchema + liveDefaultSchema localExchangeSchema messageBlockSchema messageSourceSchema @@ -2110,6 +2127,7 @@ export "./schemas" (./src/schemas.ts) serverHandoffDraftSchema serverHandoffReceiptSchema serverHelloSchema + serverLiveSettingsSchema serverLocalExchangeResultSchema serverLocationRequestSchema serverMaskRequestSchema @@ -2144,6 +2162,7 @@ export "./schemas" (./src/schemas.ts) turnScopeSummarySchema v1ResolutionEffectSchema validateResolutionEffect + voiceLiveSettingsSchema export "./server" (./src/server/index.ts) ACTIVITY_COMPUTE_CAPABILITY @@ -2583,6 +2602,8 @@ export "./server" (./src/server/index.ts) type LiveConversationOpenOptions type LiveConversationProvider type LiveConversationSession + type LiveDefault + type LiveProviderSource type LocalAnswer type LocalExchange type LocationFix @@ -2736,6 +2757,7 @@ export "./server" (./src/server/index.ts) type ServerHandoffDraft type ServerHandoffReceipt type ServerHello + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -2897,6 +2919,8 @@ export "./server" (./src/server/index.ts) type VersionRequirementCheck type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -6793,6 +6817,7 @@ signatures (every public export and the types it is made of) ClientConversationStart (packages/ui-sdk/src/protocol.ts) export interface ClientConversationStart { disclosed?: ConversationProfile; + providerId?: string; historyOwnerId?: string; contextualTasks?: boolean; type: "conversation_start"; @@ -8589,6 +8614,15 @@ signatures (every public export and the types it is made of) remote: "acknowledged" | "unknown"; }>; } + LiveDefault (packages/ui-sdk/src/protocol.ts) + export interface LiveDefault { + saved: string | null; + savedUsable: boolean; + effective: string | null; + source: Exclude; + } + LiveProviderSource (packages/ui-sdk/src/protocol.ts) + export type LiveProviderSource = "change" | "saved" | "host" | "only" | "none"; LivenessEvent (packages/ui-sdk/src/client/ws-client.ts) export type LivenessEvent = { type: "probe"; @@ -11109,6 +11143,7 @@ signatures (every public export and the types it is made of) epoch: number; sessionId?: string; providerId: string; + providerSource?: Exclude; capabilities: ConversationCapabilities; disclosure: ConversationDisclosure; limits: ConversationLimits; @@ -11180,6 +11215,8 @@ signatures (every public export and the types it is made of) export interface ServerHello { safetyCapabilities?: SafetyCapabilities; conversationProfile?: ConversationProfile; + conversationProfiles?: ConversationProfile[]; + liveDefault?: LiveDefault; type: "server_hello"; protocolRev: number; principalKey?: string; @@ -11187,6 +11224,12 @@ signatures (every public export and the types it is made of) sessionDraftLimits?: SessionDraftLimits; attachmentLimits?: AttachmentLimits; } + ServerLiveSettings (packages/ui-sdk/src/protocol.ts) + export interface ServerLiveSettings { + type: "live_settings"; + liveDefault: LiveDefault; + conversationProfiles: ConversationProfile[]; + } ServerLocalExchangeResult (packages/ui-sdk/src/protocol.ts) export interface ServerLocalExchangeResult extends SessionScoped { type: "local_exchange_result"; @@ -11209,7 +11252,7 @@ signatures (every public export and the types it is made of) instruction?: string; } ServerMessage (packages/ui-sdk/src/protocol.ts) - export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired | ServerAttachmentRead; + export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired | ServerAttachmentRead | ServerLiveSettings; ServerMessageBlocks (packages/ui-sdk/src/protocol.ts) export interface ServerMessageBlocks extends SessionScoped { type: "message_blocks"; @@ -12661,6 +12704,16 @@ signatures (every public export and the types it is made of) generatedAt: number; count: number; } + VoiceLiveSettings (packages/ui-sdk/src/protocol.ts) + export interface VoiceLiveSettings { + defaultProvider: string | null; + revision: number; + } + VoiceLiveSettingsUpdate (packages/ui-sdk/src/protocol.ts) + export interface VoiceLiveSettingsUpdate { + defaultProvider: string | null; + revision: number; + } VoiceMode (packages/ui-sdk/src/protocol.ts) export type VoiceMode = "idle" | "dictate" | "conversation"; VoiceProvidersResponse (packages/ui-sdk/src/protocol.ts) @@ -13252,6 +13305,7 @@ signatures (every public export and the types it is made of) providerId: z.ZodString; }, z.core.$strip>>>; historyOwnerId: z.ZodOptional; + providerId: z.ZodOptional; requestId: z.ZodOptional; sessionId: z.ZodOptional; type: z.ZodLiteral<"conversation_start">; @@ -13763,6 +13817,7 @@ signatures (every public export and the types it is made of) providerId: z.ZodString; }, z.core.$strip>>>; historyOwnerId: z.ZodOptional; + providerId: z.ZodOptional; requestId: z.ZodOptional; sessionId: z.ZodOptional; type: z.ZodLiteral<"conversation_start">; @@ -14037,6 +14092,56 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; providerId: z.ZodString; }, z.core.$strip>; + conversationProfilesSchema (packages/ui-sdk/src/schemas.ts) + const conversationProfilesSchema: z.ZodArray>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + providerId: z.ZodString; + }, z.core.$strip>>; conversationSampleRateSchema (packages/ui-sdk/src/schemas.ts) const conversationSampleRateSchema: z.ZodNumber; conversationWireEventSchema (packages/ui-sdk/src/schemas.ts) @@ -17848,6 +17953,18 @@ signatures (every public export and the types it is made of) const isWebToolName: (name: string) => name is WebToolName; killWrapped (packages/ui-sdk/src/server/exec-wrapper.ts) export function killWrapped(proc: KillableProcess, config?: ExecWrapperConfig, signal?: NodeJS.Signals, onFailure?: (message: string) => void, bounded?: WrappedKillOptions): void; + liveDefaultSchema (packages/ui-sdk/src/schemas.ts) + const liveDefaultSchema: z.ZodObject<{ + effective: z.ZodNullable; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>; localExchangeSchema (packages/ui-sdk/src/schemas.ts) const localExchangeSchema: z.ZodObject<{ answer: z.ZodUnknown; @@ -19898,6 +20015,12 @@ signatures (every public export and the types it is made of) maxUtterances: z.ZodNumber; }, z.core.$loose>; providerId: z.ZodString; + providerSource: z.ZodCatch>>; requestId: z.ZodOptional; resync: z.ZodObject<{ outputs: z.ZodNumber; @@ -20152,6 +20275,66 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; providerId: z.ZodString; }, z.core.$strip>>>>; + conversationProfiles: z.ZodCatch>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + providerId: z.ZodString; + }, z.core.$strip>>>>>; + liveDefault: z.ZodCatch; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>>>>; principalKey: z.ZodOptional; protocolRev: z.ZodNumber; safetyCapabilities: z.ZodCatch>>; type: z.ZodLiteral<"server_hello">; }, z.core.$loose>; + serverLiveSettingsSchema (packages/ui-sdk/src/schemas.ts) + const serverLiveSettingsSchema: z.ZodObject<{ + conversationProfiles: z.ZodArray>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + providerId: z.ZodString; + }, z.core.$strip>>; + liveDefault: z.ZodObject<{ + effective: z.ZodNullable; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>; + type: z.ZodLiteral<"live_settings">; + }, z.core.$loose>; serverLocalExchangeResultSchema (packages/ui-sdk/src/schemas.ts) const serverLocalExchangeResultSchema: z.ZodObject<{ exchangeId: z.ZodString; @@ -20880,6 +21127,66 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; providerId: z.ZodString; }, z.core.$strip>>>>; + conversationProfiles: z.ZodCatch>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + providerId: z.ZodString; + }, z.core.$strip>>>>>; + liveDefault: z.ZodCatch; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>>>>; principalKey: z.ZodOptional; protocolRev: z.ZodNumber; safetyCapabilities: z.ZodCatch; providerId: z.ZodString; + providerSource: z.ZodCatch>>; requestId: z.ZodOptional; resync: z.ZodObject<{ outputs: z.ZodNumber; @@ -24202,6 +24515,68 @@ signatures (every public export and the types it is made of) toolUseId: z.ZodString; turnId: z.ZodString; type: z.ZodLiteral<"conversation_permission">; + }, z.core.$loose>, z.ZodObject<{ + conversationProfiles: z.ZodArray>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + providerId: z.ZodString; + }, z.core.$strip>>; + liveDefault: z.ZodObject<{ + effective: z.ZodNullable; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>; + type: z.ZodLiteral<"live_settings">; }, z.core.$loose>], "type">; serverPongSchema (packages/ui-sdk/src/schemas.ts) const serverPongSchema: z.ZodObject<{ @@ -25950,6 +26325,11 @@ signatures (every public export and the types it is made of) export function validateVersionMinimum(value: unknown, owner: string, identity: string): string; visibleToolName (packages/ui-sdk/src/tool-contracts/contract.ts) export function visibleToolName(name: string, adapter: ToolAdapter): string; + voiceLiveSettingsSchema (packages/ui-sdk/src/schemas.ts) + const voiceLiveSettingsSchema: z.ZodObject<{ + defaultProvider: z.ZodNullable; + revision: z.ZodNumber; + }, z.core.$loose>; webToolProviders (packages/ui-sdk/src/tool-contracts/web.ts) export function webToolProviders(input: Record): readonly string[]; wrapCommand (packages/ui-sdk/src/server/exec-wrapper.ts) diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 928d9937dd..bed60fcd68 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -524,6 +524,8 @@ signatures (every public export and the types it is made of) speechProviders?: SpeechProvider[]; defaultSpeechProviderId?: string; conversationProvider?: LiveConversationProvider; + conversationProviders?: LiveConversationProvider[]; + defaultConversationProviderId?: string; labeller?: LabellerOptions; turnTimeoutMs?: number; registry?: BackendRegistry; @@ -1444,6 +1446,13 @@ signatures (every public export and the types it is made of) timeoutMs?: number; billing?: BillingMode; } + LiveProviderRegistry (packages/ui-server/src/voice/live-providers.ts) + export interface LiveProviderRegistry { + readonly providers: readonly LiveConversationProvider[]; + readonly hostDefault: string | null; + get(id: string): LiveConversationProvider | undefined; + resolve(saved: string | null): LiveDefault; + } LocalExchangeRecord (packages/ui-server/src/ws/local-exchanges.ts) export interface LocalExchangeRecord extends LocalExchange { seq: number; @@ -2348,6 +2357,7 @@ signatures (every public export and the types it is made of) maxConcurrentSessions: () => number; readonly observability: Observability; readonly isPrincipalAuthorized: (principalId: string) => boolean; + readonly liveProviders: LiveProviderRegistry; readonly dialogue: DialogueJournal; constructor(options: WsHostOptions); close(): Promise; @@ -2373,6 +2383,8 @@ signatures (every public export and the types it is made of) isPrincipalValid?: (principal: Principal) => boolean; isPrincipalAuthorized?: (principalId: string) => boolean; conversationProvider?: LiveConversationProvider; + conversationProviders?: LiveConversationProvider[]; + defaultConversationProviderId?: string; } apifyActorGrant (packages/common/src/governance-policy.ts) const apifyActorGrant: z.ZodObject<{ diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 5a2ef4cd8d..1801d8fe1d 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -145,6 +145,8 @@ row's real mounting check. They do not establish mounting by themselves. | `GET /api/voice/providers` | `mounted supported handler: GET /api/voice/providers` | R | | `GET /api/voice/dictation/settings` | `mounted supported handler: GET /api/voice/dictation/settings` | R | | `PUT /api/voice/dictation/settings` | `mounted supported handler: PUT /api/voice/dictation/settings` | R | +| `GET /api/settings/voice` | `mounted supported handler: GET /api/settings/voice` | LV | +| `PUT /api/settings/voice` | `mounted supported handler: PUT /api/settings/voice` | LV | | `GET /api/voice/capabilities` | `mounted supported handler: GET /api/voice/capabilities` | R | | `GET /api/voice/recordings/:recordingId/transcription` | `mounted supported handler: GET /api/voice/recordings/:recordingId/transcription` | R | | `PUT /api/voice/recordings/:recordingId/transcription` | `mounted supported handler: PUT /api/voice/recordings/:recordingId/transcription` | R | @@ -512,6 +514,8 @@ no inbox thread. Detailed parser/intake/containment checks live in **R** — [selectable-dictation.test.ts](../packages/ui-server/tests/selectable-dictation.test.ts) covers exact provider selection, settings revisions/authority and held mint/upload binding; [saved-transcription.test.ts](../packages/ui-server/tests/saved-transcription.test.ts): concurrent real-route claims/retries, server hashes, body caps, account access, terminal outcomes, tombstones and keyless provider transport. +**LV — Live-conversation service default.** [live-provider-selection.test.ts](../packages/ui-server/tests/live-provider-selection.test.ts) covers the owner-only write guard (403 with an empty body for a delegated principal, before body validation), revisions under concurrent writes, unknown ids, persistence in the settings store, the `live_settings` broadcast and that a save opens no provider. + **RV — User history restoration.** `turn-revert.test.ts` exercises raw restoration, Undo, partial conflicts, operation identity, authorization, original voice and cross-session refusal, and observed quarantine restoration on real SQLite and diff --git a/docs/http-api.md b/docs/http-api.md index 5eb16eb1f2..cb845de10c 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion and individual safety-review routes mounted by `createApp`: 179 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review and live-service default routes mounted by `createApp`: 181 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -187,6 +187,8 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/voice/providers` | S | Read registered dictation providers and effective selection; never mint | Authenticated discovery, no-store. | | GET | `/api/voice/dictation/settings` | S | Read brain-wide dictation choice, SMART mode and revision | Independent of live conversation settings. | | PUT | `/api/voice/dictation/settings` | S | Save dictation choice with If-Match revision | Human owner/ambient only; stale writes never overwrite. | +| GET | `/api/settings/voice` | S | Read the saved brain-wide default live-conversation service and revision | Human sessions only; independent of the model and dictation defaults. | +| PUT | `/api/settings/voice` | S | Save the default live-conversation service against its revision | Owner human session or ambient human only; 403 empty body otherwise; stale writes never overwrite. | | GET | `/api/voice/capabilities` | S | Read active-provider capabilities without minting a credential | Saved-audio discovery and independent clients; additive #1021 contract. | | GET | `/api/voice/recordings/:recordingId/transcription` | S | Read an account-owned durable transcription receipt | Saved-audio status recovery; never dispatches a provider. | | PUT | `/api/voice/recordings/:recordingId/transcription` | S | Explicitly upload or retry saved audio | Account ownership, verified hash, bounded body and durable claim protect idempotency. | @@ -212,7 +214,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 179 declared endpoints are mounted regardless of backend, renderer or +All 181 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -1423,6 +1425,36 @@ saved switch (initially true). A failed exact mint returns generic 500 `{ error: "Voice session failed" }` without provider diagnostics or credentials. Bodyless legacy requests retain their previous response/error shape. +## Live-conversation service default + +`GET /api/settings/voice` returns `VoiceLiveSettings` +`{ defaultProvider: string | null, revision: number }`, the saved brain-wide +default live-conversation service (#3616). Nothing saved reads as +`{ defaultProvider: null, revision: 0 }`; a corrupt or unknown `voice.live.defaultProvider` +row in the ui-server settings store reads the same. A saved id the host no +longer registers stays saved until changed here. Any authenticated human +session (an owner or the ambient principal) may read; other principals get 403 +with an empty body. + +`PUT /api/settings/voice` takes `application/json` `{ defaultProvider: string | null, +revision: number }`, where `revision` is the one last read and `null` clears the +default. The route has its own owner-only guard, checked before the body is +read: only the brain owner's human session (password or passkey) or the ambient +human principal passes. Delegated agent principals and any other principal get +403 with an empty body. A non-JSON media type is 415; a malformed body is 400 +`{ error: "LIVE_SETTINGS_INVALID" }`; an id that is not registered is 400 +`{ error: "LIVE_PROVIDER_UNKNOWN" }`; a stale revision is 409 +`{ error: "LIVE_SETTINGS_CHANGED", message, current }`. A successful write returns +200 with the new `{ defaultProvider, revision }` and sends `live_settings` on every +open WebSocket connection ([wire](integration-contract/wire.md#live-service-selection-additive-3616)). + +Both routes are `no-store`. Neither reads or reports a credential, key presence +or endpoint, opens a provider, captures audio or reads chat history. A save takes +effect at the next explicit Start and never retargets a running conversation. +The ordinary model default (`/api/models/default`) and the dictation choice +(`/api/voice/dictation/settings`) are separate settings with their own routes +and revisions. + ## Saved-audio transcription The protected `GET /api/voice/capabilities` returns `VoiceCapabilitiesResponse` diff --git a/packages/ui-react/src/hooks/websocket-handlers/connection.ts b/packages/ui-react/src/hooks/websocket-handlers/connection.ts index 51e2693dbf..2b2c5a4ad0 100644 --- a/packages/ui-react/src/hooks/websocket-handlers/connection.ts +++ b/packages/ui-react/src/hooks/websocket-handlers/connection.ts @@ -6,7 +6,7 @@ type ConnectionFrame = "safety_history" | "safety_update" | "safety_unavailable" | "server_hello" | "location_request" | "error" | "inbox_snapshot" | "inbox_delta" | "tool_resolution" | "session_queue" | "conversation_opened" | "conversation_closed" | "conversation_event" | "conversation_work" | "conversation_output" | "conversation_permission" | "chat_retired" - | "attachment_read"; + | "attachment_read" | "live_settings"; export const connectionFrameHandlers = { safety_history: () => {}, safety_update: () => {}, safety_unavailable: () => {}, @@ -53,6 +53,8 @@ export const connectionFrameHandlers = { // beside the demux, so nothing here touches a transcript. attachment_read: () => {}, conversation_opened: () => {}, + // The live-service default (#3616): the root conversation client reads it beside the demux. + live_settings: () => {}, conversation_closed: () => {}, conversation_event: () => {}, conversation_work: () => {}, diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 62d8ef351e..01dc94e8bb 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -964,7 +964,8 @@ export type ServerMessage = | ServerTurnJournal | ServerUsage | ServerChatRetired - | ServerAttachmentRead; + | ServerAttachmentRead + | ServerLiveSettings; /** * First frame a server sends after a socket opens (rev 2, additive). Clients @@ -976,8 +977,22 @@ export type ServerMessage = export interface ServerHello { /** Read sidecar only; absent means unavailable. */ safetyCapabilities?: SafetyCapabilities; - /** Known destination/profile before explicit Start; no provider has opened. */ + /** + * Known destination/profile before explicit Start; no provider has opened. + * Present only when the effective live service is non-null (#3616): it is + * that service's profile. A multi-service host with nothing saved and no + * host default, or with an unusable saved default, omits it, so a client + * that reads only this field shows live conversation as unavailable. + */ conversationProfile?: ConversationProfile; + /** + * Every registered live service's profile, in registration order (#3616). + * Present exactly when `capabilities.liveConversation` is true. Discovery + * only: registration is not proven provider health. + */ + conversationProfiles?: ConversationProfile[]; + /** How a new Start resolves its live service (#3616). Present with `conversationProfiles`. */ + liveDefault?: LiveDefault; type: "server_hello"; protocolRev: number; /** @@ -2304,6 +2319,13 @@ export interface ConversationOutputRecord { export interface ClientConversationStart { /** Exact profile explicitly disclosed at Start; absent legacy starts refuse. */ disclosed?: ConversationProfile; + /** + * The live service this Start is for (#3616): the effective one or a + * one-time pick. It must equal `disclosed.providerId` and name a + * registered service, or the start is refused. Absent means the effective + * service (legacy), and a start is refused when there is none. + */ + providerId?: string; /** Resume retained host-only history without pretending it is a backend session. */ historyOwnerId?: string; /** New clients opt into the provider capability; older clients stay reviewed. */ @@ -2382,6 +2404,50 @@ export interface ClientConversationStop { * re-executed or re-announced. One frame per record keeps every record whole: * a single snapshot frame could outgrow the per-frame cap and be clipped. */ +/** + * Why a live service is the one a Start uses (#3616): `change` is the one-time + * pick on the Start card, `saved` the brain-wide default, `host` the host's + * `defaultConversationProviderId`, `only` the single registered service, and + * `none` means a Start must name one. `change` appears only on + * `conversation_opened`, never in `liveDefault`. + */ +export type LiveProviderSource = "change" | "saved" | "host" | "only" | "none"; + +/** The live-service default as a new Start resolves it (#3616). Never names a credential. */ +export interface LiveDefault { + /** The saved brain-wide default, kept even when it is no longer registered. */ + saved: string | null; + /** Whether `saved` names a registered service; false when nothing is saved. */ + savedUsable: boolean; + /** The service a Start without a pick uses; null means a pick is required, or none exists. */ + effective: string | null; + source: Exclude; +} + +/** + * Server → Client (#3616, additive). Sent to every open connection after the + * saved live-service default changes, with the same fields `server_hello` + * carries. It never retargets a running conversation. Older clients ignore it. + */ +export interface ServerLiveSettings { + type: "live_settings"; + liveDefault: LiveDefault; + conversationProfiles: ConversationProfile[]; +} + +/** `GET`/`PUT /api/settings/voice` (#3616): the saved live-service default and its revision. */ +export interface VoiceLiveSettings { + /** A registered live service id, or null for nothing saved. */ + defaultProvider: string | null; + revision: number; +} + +/** `PUT /api/settings/voice` body (#3616). `revision` is the one last read. */ +export interface VoiceLiveSettingsUpdate { + defaultProvider: string | null; + revision: number; +} + export interface ServerConversationOpened { /** * Actual bounded startup text coverage; no semantic recall guarantee. @@ -2402,6 +2468,8 @@ export interface ServerConversationOpened { /** Chat session, once known. */ sessionId?: string; providerId: string; + /** How this conversation's live service was chosen (#3616). Absent from older hosts. */ + providerSource?: Exclude; capabilities: ConversationCapabilities; disclosure: ConversationDisclosure; limits: ConversationLimits; diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 9fb674eaae..90bb5bcff2 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -40,6 +40,9 @@ import type { ClientConversationPlayback, ClientConversationStart, ConversationProfile, + LiveDefault, + ServerLiveSettings, + VoiceLiveSettings, ClientConversationStop, ConversationAudioFormat, ConversationCapabilities, @@ -850,6 +853,7 @@ export const clientDialogueReadSchema = z.looseObject({ export const clientConversationStartSchema = z.looseObject({ disclosed: z.lazy(() => conversationProfileSchema).optional(), + providerId: id.optional(), type: z.literal("conversation_start"), historyOwnerId: id.optional(), contextualTasks: z.boolean().optional(), @@ -1192,6 +1196,9 @@ export const serverHelloSchema = z.looseObject({ safetyCapabilities: safetyCapabilitiesSchema.optional().catch(undefined), type: z.literal("server_hello"), conversationProfile: z.lazy(() => conversationProfileSchema).optional().catch(undefined), + // A malformed live-service roster is dropped rather than costing the whole hello (#3616). + conversationProfiles: z.lazy(() => conversationProfilesSchema).optional().catch(undefined), + liveDefault: z.lazy(() => liveDefaultSchema).optional().catch(undefined), protocolRev: z.number(), principalKey: z.string().max(MAX_ID_CHARS).optional(), capabilities: z.record(z.string(), z.boolean()).optional(), @@ -1760,6 +1767,30 @@ export const conversationProfileSchema = z.object({ disclosure: conversationDisclosureSchema, }) satisfies z.ZodType; +/** Registered live services, in registration order (#3616). Ids are unique. */ +export const conversationProfilesSchema = z.array(conversationProfileSchema).max(64) + .refine((profiles) => new Set(profiles.map((p) => p.providerId)).size === profiles.length, { message: "duplicate providerId" }); + +export const liveDefaultSchema = z.looseObject({ + saved: id.nullable(), + savedUsable: z.boolean(), + effective: id.nullable(), + source: z.enum(["saved", "host", "only", "none"]), +}) satisfies z.ZodType; + +/** Additive (#3616): the saved live-service default changed; same fields as hello. */ +export const serverLiveSettingsSchema = z.looseObject({ + type: z.literal("live_settings"), + liveDefault: liveDefaultSchema, + conversationProfiles: conversationProfilesSchema, +}) satisfies z.ZodType; + +/** `GET`/`PUT /api/settings/voice` response (#3616). */ +export const voiceLiveSettingsSchema = z.looseObject({ + defaultProvider: id.nullable(), + revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), +}) satisfies z.ZodType; + export const conversationAudioFormatSchema = z.looseObject({ encoding: z.literal("pcm16"), sampleRate: conversationSampleRateSchema, @@ -1909,6 +1940,7 @@ export const serverConversationOpenedSchema = z.looseObject({ epoch: conversationEpoch, sessionId: id.optional(), providerId: id, + providerSource: z.enum(["change", "saved", "host", "only"]).optional().catch(undefined), capabilities: conversationCapabilitiesSchema, disclosure: conversationDisclosureSchema, limits: conversationLimitsSchema, @@ -2071,6 +2103,7 @@ export const serverMessageSchema = z.discriminatedUnion("type", [ serverConversationWorkSchema, serverConversationOutputSchema, serverConversationPermissionSchema, + serverLiveSettingsSchema, ]) satisfies z.ZodType; /** diff --git a/packages/ui-sdk/tests/server-schemas.test.ts b/packages/ui-sdk/tests/server-schemas.test.ts index 5ccdfa848e..930a8e04ae 100644 --- a/packages/ui-sdk/tests/server-schemas.test.ts +++ b/packages/ui-sdk/tests/server-schemas.test.ts @@ -189,6 +189,9 @@ const SAMPLES: ServerMessage[] = [ warnUsd: 100, blockUsd: 200, blockTokens: 512_000_000, warning: false, blocked: false }] } }, { type: "scope_decision_receipt", sessionId: "s1", turnId: "turn-1", eventId: "cap-loom", submissionId: "athena", state: "accepted" }, { type: "pong", probeId: "probe-1" }, + { type: "live_settings", liveDefault: { saved: "gpt-live", savedUsable: true, effective: "gpt-live", source: "saved" }, + conversationProfiles: [{ providerId: "gpt-live", capabilities: { nonblockingWork: "supported", manualEndpoint: "supported", finalTranscript: "unproven", remoteOutputCancelAck: "unproven", exactPermissionSpeech: "unproven", echoIsolatedInput: "unproven", outputWordAlignment: "unproven" }, + disclosure: { voiceService: "Fictional GPT-Live of Ithaca", destinations: ["Microphone audio goes to the fictional voice service."] } }] }, ]; // Inspect input frame discriminators, including object → transform pipes. @@ -406,3 +409,32 @@ test("policy approval and live/replay receipts survive the validated additive bo expect(parse({ ...frames[1], policyChange: { ...policyChange, state: "approve_by_voice" } }).ok).toBe(false); expect(parse({ ...frames[1], policyChange: { ...policyChange, baseHash: undefined } }).ok).toBe(false); }); + +describe("live-service roster (#3616)", () => { + const profile = (providerId: string) => ({ providerId, capabilities: { nonblockingWork: "supported", manualEndpoint: "supported", finalTranscript: "unproven", remoteOutputCancelAck: "unproven", exactPermissionSpeech: "unproven", echoIsolatedInput: "unproven", outputWordAlignment: "unproven" }, + disclosure: { voiceService: `Fictional ${providerId}`, destinations: ["Microphone audio goes to the fictional voice service."] } }); + const hello = { type: "server_hello", protocolRev: 5, capabilities: { liveConversation: true } }; + test("a hello carries the roster and the resolution", () => { + const frame = { ...hello, conversationProfiles: [profile("gemini-live"), profile("gpt-live")], liveDefault: { saved: null, savedUsable: false, effective: null, source: "none" } }; + const result = parse(frame); + expect(result.ok && result.message).toEqual(frame); + }); + test("a malformed roster or resolution is dropped without losing the hello", () => { + for (const bad of [ + { conversationProfiles: [profile("gpt-live"), profile("gpt-live")] }, + { conversationProfiles: [{ providerId: "gpt-live" }] }, + { liveDefault: { saved: null, savedUsable: false, effective: null, source: "change" } }, + { liveDefault: { saved: 7, savedUsable: false, effective: null, source: "none" } }, + ]) { + const result = parse({ ...hello, ...bad }); + expect(result.ok).toBe(true); + if (result.ok && result.message.type === "server_hello") { + expect(result.message.conversationProfiles).toBeUndefined(); + expect(result.message.liveDefault).toBeUndefined(); + } + } + }); + test("live_settings with a malformed resolution is refused as a frame", () => { + expect(parse({ type: "live_settings", liveDefault: { saved: null, savedUsable: false, effective: null, source: "change" }, conversationProfiles: [] }).ok).toBe(false); + }); +}); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 29b2c923e4..0a696fa661 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -74,6 +74,7 @@ import { createTranscriptionWrites } from "./voice/transcription-writes.js"; import { createSettingsWrites } from "./db/settings-writes.js"; import { createSpeechProviderRegistry } from "./voice/speech-providers.js"; import { createVoiceRoutes } from "./routes/voice.js"; +import { createLiveSettingsRoutes } from "./routes/live-settings.js"; import { createFilesRoutes, HTML_PREVIEW_CSP, HTML_PREVIEW_PATH } from "./routes/files.js"; import { createInboxIntake } from "./inbox/intake.js"; import { createQueueRoutes } from "./routes/queue.js"; @@ -130,6 +131,7 @@ import { getCustomOpenRouterModels, getDefaultModelId, getHiddenModelIds, + getLiveDefaultProvider, getSetting, setSetting, getThinkingOverrides, @@ -251,6 +253,19 @@ export interface CreateAppOptions { * @experimental Part of the LiveConversationProvider seam until 1.0. */ conversationProvider?: LiveConversationProvider; + /** + * Several live-conversation providers, fixed at construction (#3616). + * Exclusive with `conversationProvider`, which means a list of one. Startup + * fails on both options, duplicate ids or an invalid provider. Registration + * is discovery only, never proof that a provider's key works. + * @experimental Part of the LiveConversationProvider seam until 1.0. + */ + conversationProviders?: LiveConversationProvider[]; + /** + * The host's default live service when nothing is saved in Settings › Voice + * (#3616). Must name a registered provider, or startup fails. + */ + defaultConversationProviderId?: string; /** * The small, fast model that labels working-session and pending follow-up * pills with a few words (#1004): any value of core's `CompletionProvider` @@ -813,7 +828,10 @@ export async function createApp(options: CreateAppOptions = {}): Promise activity.stream.pump() }, }), scratchPrune: () => scratchPrune.tick(), - ...(options.conversationProvider ? { conversationProvider: options.conversationProvider } : {}), + ...(options.conversationProvider !== undefined ? { conversationProvider: options.conversationProvider } : {}), + ...(options.conversationProviders !== undefined ? { conversationProviders: options.conversationProviders } : {}), + ...(options.defaultConversationProviderId !== undefined ? { defaultConversationProviderId: options.defaultConversationProviderId } : {}), + liveDefaultProvider: () => getLiveDefaultProvider(db).defaultProvider, ...(options.appName ? { appName: options.appName } : {}), // Explicit option wins; then the env-resolved config; then the host default. ...(options.turnTimeoutMs ?? config.turnTimeoutMs @@ -1199,6 +1217,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.conversations?.broadcastSettings() })); const transcriptions = createTranscriptionWrites(db, { brainPath: config.brainPath, authMode }, writer); app.route("/api", createTranscriptionRoutes({ store: transcriptions, keyterms, speechProviders, db })); app.route( diff --git a/packages/ui-server/src/db/settings-writes.ts b/packages/ui-server/src/db/settings-writes.ts index 6269d94b96..1543eae30e 100644 --- a/packages/ui-server/src/db/settings-writes.ts +++ b/packages/ui-server/src/db/settings-writes.ts @@ -10,6 +10,7 @@ export const url = import.meta.url; function operations(db: Database, log?: Logger) { return { saveDictationSettings: (expected: string, value: { defaultProvider: string | null; smart: boolean }) => settings.saveDictationSettings(db, expected, value), + saveLiveDefaultProvider: (expected: number, defaultProvider: string | null) => settings.saveLiveDefaultProvider(db, expected, defaultProvider), setSetting: (key: string, value: unknown) => settings.setSetting(db, key, value), setHiddenModelIds: (ids: string[]) => settings.setHiddenModelIds(db, ids), setDefaultModelId: (id: string | null) => settings.setDefaultModelId(db, id), @@ -57,6 +58,7 @@ export function createSettingsWrites(db: Database, writer?: SqliteWriter, log?: }); return { saveDictationSettings: (...args) => invoke("saveDictationSettings", args), + saveLiveDefaultProvider: (...args) => invoke("saveLiveDefaultProvider", args), setSetting: (...args) => invoke("setSetting", args), setHiddenModelIds: (...args) => invoke("setHiddenModelIds", args), setDefaultModelId: (...args) => invoke("setDefaultModelId", args), diff --git a/packages/ui-server/src/db/settings.ts b/packages/ui-server/src/db/settings.ts index 9b051d7178..e5f2c1bc92 100644 --- a/packages/ui-server/src/db/settings.ts +++ b/packages/ui-server/src/db/settings.ts @@ -14,6 +14,7 @@ import { type BillingMode, type DictationSettings, type ThinkingLevel, + type VoiceLiveSettings, } from "@schlessera/brain-ui-sdk/protocol"; const HIDDEN_MODELS_KEY = "models.hidden"; @@ -213,3 +214,30 @@ export function saveDictationSettings(db: Database, expected: string, value: { d return { saved: true, current: { ...value, revision: String(revision) } }; }).immediate(); } + +const LIVE_DEFAULT_KEY = "voice.live.defaultProvider"; +/** + * The saved brain-wide live-conversation default (#3616). The reader is + * total: corrupt or unknown data reads as nothing saved, revision 0. A saved + * id the host no longer registers stays saved until changed in Settings. + */ +export function getLiveDefaultProvider(db: Database): VoiceLiveSettings { + const fallback = { defaultProvider: null, revision: 0 }; + const value = getSetting(db, LIVE_DEFAULT_KEY, null); + if (!value || typeof value !== "object" || Array.isArray(value)) return fallback; + const row = value as Record; + if (!(row.value === null || typeof row.value === "string" && row.value.length > 0) || + typeof row.revision !== "number" || !Number.isSafeInteger(row.revision) || row.revision < 0) return fallback; + return { defaultProvider: row.value, revision: row.revision }; +} + +/** The revision comparison and write run in the same writer transaction. */ +export function saveLiveDefaultProvider(db: Database, expected: number, defaultProvider: string | null) { + return db.transaction(() => { + const current = getLiveDefaultProvider(db); + if (expected !== current.revision || current.revision >= Number.MAX_SAFE_INTEGER) return { saved: false, current }; + const revision = current.revision + 1; + setSetting(db, LIVE_DEFAULT_KEY, { value: defaultProvider, revision }); + return { saved: true, current: { defaultProvider, revision } }; + }).immediate(); +} diff --git a/packages/ui-server/src/routes/live-settings.ts b/packages/ui-server/src/routes/live-settings.ts new file mode 100644 index 0000000000..731bdbe74a --- /dev/null +++ b/packages/ui-server/src/routes/live-settings.ts @@ -0,0 +1,82 @@ +/** + * `GET`/`PUT /api/settings/voice` (#3616): the saved brain-wide default live + * service. It is independent of the ordinary model default and of dictation, + * which keep their own routes and revisions. + * + * Reading needs any authenticated human session of the brain. Writing has its + * own owner-only guard, enforced here rather than assumed from another route: + * only the owner's human session (password or passkey) or the ambient human + * principal passes. Delegated agent principals and anything else get 403 with + * an empty body. Neither route reads a credential, opens a provider, captures + * audio or reads history; a save only changes the next explicit Start. + */ + +import type { Database } from "bun:sqlite"; +import { Hono } from "hono"; +import type { VoiceLiveSettings } from "@schlessera/brain-ui-sdk/protocol"; +import type { AppEnv } from "../app-env.js"; +import { getLiveDefaultProvider } from "../db/settings.js"; +import type { SettingsWrites } from "../db/settings-writes.js"; +import { isUsablePrincipal, type Principal } from "../db/principals.js"; +import { readJsonBody } from "../middleware/body-limit.js"; +import { requireJson } from "../middleware/origin.js"; +import type { LiveProviderRegistry } from "../voice/live-providers.js"; + +interface LiveSettingsRoutesDeps { + db: Database; + settingsWrites: SettingsWrites; + live: LiveProviderRegistry; + /** Called after a save: tells open connections, retargets nothing. */ + changed?: () => void; + now?: () => number; +} + +/** Human readers only: the owner's sessions and the ambient principal. */ +function isHuman(principal: Principal | undefined, now: number): boolean { + if (!principal || !isUsablePrincipal(principal, now)) return false; + return principal.kind === "ambient" || principal.kind === "owner"; +} + +/** The owner-only write guard (#3616 §3): a human owner session, never a delegated principal. */ +export function isLiveSettingsWriter(principal: Principal | undefined, now: number): boolean { + if (!principal || !isUsablePrincipal(principal, now)) return false; + if (principal.kind === "ambient") return principal.authMethod === "ambient"; + return principal.kind === "owner" && (principal.authMethod === "password" || principal.authMethod === "passkey"); +} + +export function createLiveSettingsRoutes(deps: LiveSettingsRoutesDeps): Hono { + const { db, settingsWrites, live } = deps; + const now = deps.now ?? Date.now; + return new Hono() + .get("/settings/voice", (c) => { + c.header("Cache-Control", "no-store"); + if (!isHuman(c.get("principal"), now())) return c.body(null, 403); + const body: VoiceLiveSettings = getLiveDefaultProvider(db); + return c.json(body); + }) + .put("/settings/voice", async (c, next) => { + // Refuse before the body is read, whatever its media type. + c.header("Cache-Control", "no-store"); + if (!isLiveSettingsWriter(c.get("principal"), now())) return c.body(null, 403); + await next(); + }, requireJson(), async (c) => { + c.header("Cache-Control", "no-store"); + const body = await readJsonBody(c).catch(() => null); + if (body instanceof Response) return body; + const row = body as Record | null; + if (!row || typeof row !== "object" || Array.isArray(row) || + !(row.defaultProvider === null || typeof row.defaultProvider === "string" && row.defaultProvider.length > 0) || + typeof row.revision !== "number" || !Number.isSafeInteger(row.revision) || row.revision < 0) { + return c.json({ error: "LIVE_SETTINGS_INVALID", message: "Send { defaultProvider: string | null, revision: number }." }, 400); + } + const defaultProvider = row.defaultProvider as string | null; + if (defaultProvider !== null && !live.get(defaultProvider)) { + return c.json({ error: "LIVE_PROVIDER_UNKNOWN", message: "That live service isn't available on this host." }, 400); + } + const result = await settingsWrites.saveLiveDefaultProvider(row.revision, defaultProvider); + if (!result.saved) return c.json({ error: "LIVE_SETTINGS_CHANGED", message: "Changed on another device.", current: result.current }, 409); + deps.changed?.(); + const saved: VoiceLiveSettings = result.current; + return c.json(saved); + }); +} diff --git a/packages/ui-server/src/voice/live-providers.ts b/packages/ui-server/src/voice/live-providers.ts new file mode 100644 index 0000000000..c2e4cc98d4 --- /dev/null +++ b/packages/ui-server/src/voice/live-providers.ts @@ -0,0 +1,73 @@ +/** + * Registered live-conversation services and how a new Start resolves one + * (#3616). Registration is fixed at construction: "usable" means registered at + * boot, never a probed credential, so a key that fails later surfaces through + * the provider's own `provider_error` close and never selects another service. + * + * Precedence for a Start without a one-time pick: + * 1. the saved brain-wide default, only if it is registered; a saved but + * unregistered default stops here with no effective service (no + * fall-through to the host default or the only service); + * 2. the host default, only when nothing is saved; + * 3. the single registered service, only when nothing is saved; + * 4. otherwise none: a Start must name a service. + * + * Nothing here reads a credential, opens a provider or reads chat content. + */ + +import type { LiveDefault } from "@schlessera/brain-ui-sdk/protocol"; +import { assertLiveConversationProvider, type LiveConversationProvider } from "@schlessera/brain-ui-sdk/server"; + +interface LiveProviderOptions { + conversationProvider?: LiveConversationProvider; + conversationProviders?: LiveConversationProvider[]; + defaultConversationProviderId?: string; +} + +export interface LiveProviderRegistry { + /** Registration order. */ + readonly providers: readonly LiveConversationProvider[]; + readonly hostDefault: string | null; + get(id: string): LiveConversationProvider | undefined; + /** Resolve the effective service from the saved default (`null` = nothing saved). */ + resolve(saved: string | null): LiveDefault; +} + +/** + * Validate and freeze the registration. Throws on both options at once, + * duplicate ids, an invalid provider, or a host default that names no + * registered service. + */ +export function createLiveProviderRegistry(options: LiveProviderOptions): LiveProviderRegistry { + if (options.conversationProvider !== undefined && options.conversationProviders !== undefined) { + throw new Error("Pass either conversationProvider or conversationProviders, not both."); + } + if (options.conversationProviders !== undefined && !Array.isArray(options.conversationProviders)) { + throw new Error("conversationProviders must be an array of LiveConversationProvider."); + } + const providers = Object.freeze([...(options.conversationProviders ?? (options.conversationProvider ? [options.conversationProvider] : []))]); + const byId = new Map(); + for (const provider of providers) { + assertLiveConversationProvider(provider); + if (byId.has(provider.id)) throw new Error(`Duplicate live conversation provider id "${provider.id}".`); + byId.set(provider.id, provider); + } + const hostDefault = options.defaultConversationProviderId ?? null; + if (hostDefault !== null && !byId.has(hostDefault)) { + throw new Error(`defaultConversationProviderId "${hostDefault}" is not a registered live conversation provider.`); + } + return { + providers, + hostDefault, + get: (id) => byId.get(id), + resolve(saved) { + if (saved !== null) { + const usable = byId.has(saved); + return { saved, savedUsable: usable, effective: usable ? saved : null, source: usable ? "saved" : "none" }; + } + if (hostDefault !== null) return { saved: null, savedUsable: false, effective: hostDefault, source: "host" }; + if (providers.length === 1) return { saved: null, savedUsable: false, effective: providers[0]!.id, source: "only" }; + return { saved: null, savedUsable: false, effective: null, source: "none" }; + }, + }; +} diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index 06b7a33ad8..e1d4f7cc20 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -128,7 +128,9 @@ export function createWsHandlers(host: WsHost, principal: Principal) { }, // Beside `capabilities`, whose values every shipped client parses // as booleans (#979). - ...(host.conversations ? { conversationProfile: host.conversations.profile() } : {}), + // The effective service's profile only when one is effective, beside + // every registered profile and how a Start resolves one (#3616). + ...(host.conversations ? host.conversations.helloFields() : {}), ...(host.drafts ? { sessionDraftLimits: { ...host.drafts.limits } } : {}), ...(host.attachmentLimits ? { attachmentLimits: { ...host.attachmentLimits } } : {}), }); diff --git a/packages/ui-server/src/ws/conversation.ts b/packages/ui-server/src/ws/conversation.ts index b3a4bd205f..38f1272494 100644 --- a/packages/ui-server/src/ws/conversation.ts +++ b/packages/ui-server/src/ws/conversation.ts @@ -34,8 +34,11 @@ import { type ConversationCloseReason, type ConversationOutputRecord, type ConversationWorkReceipt, + type LiveDefault, + type LiveProviderSource, type ServerMessage, } from "@schlessera/brain-ui-sdk/protocol"; +import type { LiveProviderRegistry } from "../voice/live-providers.js"; import { assertLiveConversationSession, parseLiveConversationEvent, @@ -122,6 +125,10 @@ interface Epoch { } interface Conversation { + /** The live service this conversation opened with; a resume never changes it (#3616). */ + provider: LiveConversationProvider; + /** How that service was chosen, echoed on `conversation_opened`. */ + providerSource: Exclude; historyOwnerId?: string; historyGeneration?: number; lastEpoch: number; @@ -165,19 +172,80 @@ export class ConversationHost { constructor( private readonly host: WsHost, - readonly provider: LiveConversationProvider + readonly live: LiveProviderRegistry, + private readonly savedDefault: () => string | null = () => null ) {} - /** Public disclosure only; never opens a provider or reads chat content. */ - profile(contextualTasks = true): ConversationProfile { - return { providerId: this.provider.id, - capabilities: { ...this.provider.capabilities, contextualTasks: contextualTasks && this.provider.capabilities.contextualTasks === "supported" && !!this.host.catalog.saveConversationTask && !!this.host.catalog.saveConversationEpoch ? "supported" : "unsupported" }, - disclosure: { voiceService: this.provider.disclosure.voiceService, destinations: [...this.provider.disclosure.destinations] } }; + /** The saved default resolved against the registration (#3616). Reads no provider. */ + liveDefault(): LiveDefault { + let saved: string | null = null; + try { saved = this.savedDefault(); } catch { saved = null; } + return this.live.resolve(saved); } - private disclosed(msg: ClientConversationStart): boolean { + + /** Every registered service's public disclosure, in registration order (#3616). */ + profiles(contextualTasks = true): ConversationProfile[] { + return this.live.providers.map((provider) => this.profileOf(provider, contextualTasks)); + } + + /** + * Public disclosure of the effective service, or of `providerId`; never + * opens a provider or reads chat content. Undefined when there is none. + */ + profile(contextualTasks = true, providerId?: string): ConversationProfile | undefined { + const id = providerId ?? this.liveDefault().effective; + const provider = id === null ? undefined : this.live.get(id); + return provider ? this.profileOf(provider, contextualTasks) : undefined; + } + + /** The additive hello fields (#3616); `conversationProfile` only when a service is effective. */ + helloFields(): { conversationProfile?: ConversationProfile; conversationProfiles: ConversationProfile[]; liveDefault: LiveDefault } { + const liveDefault = this.liveDefault(); + const effective = liveDefault.effective === null ? undefined : this.profile(true, liveDefault.effective); + return { ...(effective ? { conversationProfile: effective } : {}), conversationProfiles: this.profiles(), liveDefault }; + } + + /** + * After the saved default changes (#3616): tell every open connection. A + * running conversation keeps its pinned service; nothing is retargeted. + */ + broadcastSettings(): void { + const { conversationProfiles, liveDefault } = this.helloFields(); + this.host.clients.broadcast({ type: "live_settings", liveDefault, conversationProfiles }); + } + + private profileOf(provider: LiveConversationProvider, contextualTasks: boolean): ConversationProfile { + return { providerId: provider.id, + capabilities: { ...provider.capabilities, contextualTasks: contextualTasks && provider.capabilities.contextualTasks === "supported" && !!this.host.catalog.saveConversationTask && !!this.host.catalog.saveConversationEpoch ? "supported" : "unsupported" }, + disclosure: { voiceService: provider.disclosure.voiceService, destinations: [...provider.disclosure.destinations] } }; + } + + /** + * The service this Start is for (#3616). An explicit `providerId` must equal + * the disclosed one and be registered. Without one, a resume keeps its + * conversation's pinned service and a new Start uses the effective one. + * Undefined refuses the start; nothing falls back to another service. + */ + private target(msg: ClientConversationStart): { provider: LiveConversationProvider; source: Exclude } | undefined { + const resolved = this.liveDefault(); + if (msg.providerId !== undefined) { + const provider = msg.disclosed?.providerId === msg.providerId ? this.live.get(msg.providerId) : undefined; + if (!provider) return undefined; + const pinned = msg.conversationId !== undefined ? this.conversations.get(msg.conversationId) : undefined; + if (pinned) return { provider: pinned.provider, source: pinned.providerSource }; + return { provider, source: resolved.effective === provider.id && resolved.source !== "none" ? resolved.source : "change" }; + } + const pinned = msg.conversationId !== undefined ? this.conversations.get(msg.conversationId) : undefined; + if (pinned) return { provider: pinned.provider, source: pinned.providerSource }; + if (resolved.effective === null || resolved.source === "none") return undefined; + const provider = this.live.get(resolved.effective); + return provider ? { provider, source: resolved.source } : undefined; + } + + private disclosed(msg: ClientConversationStart, provider: LiveConversationProvider): boolean { const canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>[k,canonical(v)])) : value; - return JSON.stringify(canonical(msg.disclosed)) === JSON.stringify(canonical(this.profile(msg.contextualTasks === true))); + return JSON.stringify(canonical(msg.disclosed)) === JSON.stringify(canonical(this.profileOf(provider, msg.contextualTasks === true))); } // --- client commands --- @@ -186,7 +254,9 @@ export class ConversationHost { if (connection.closed || !connection.authorization.valid || this.host.closing) return; // Privacy admission precedes even recovery reads and device takeover. if (!msg.disclosed) { this.refuse(ws,"CONVERSATION_CAPABILITY","Update this app before starting voice. Nothing was sent to the voice service.",msg.requestId); return; } - if (!this.disclosed(msg)) { this.refuse(ws,"CONVERSATION_DISCLOSURE","The voice service changed. Review its disclosure and select Start. Nothing was sent to the voice service.",msg.requestId); return; } + const target = this.target(msg); + if (!target || !this.disclosed(msg, target.provider)) { this.refuse(ws,"CONVERSATION_DISCLOSURE","The voice service changed. Review its disclosure and select Start. Nothing was sent to the voice service.",msg.requestId); return; } + const provider = target.provider; const principalId = connection.authorization.principalId; let conversation: Conversation; if (msg.conversationId !== undefined) { @@ -198,7 +268,7 @@ export class ConversationHost { // Another resume may have registered an owner while storage awaited. found = this.conversations.get(msg.conversationId); if (!found && stored && this.makeRoom()) { - found = { id: stored.id, principalId, lastEpoch: stored.epoch, + found = { provider, providerSource: target.source, id: stored.id, principalId, lastEpoch: stored.epoch, ...(stored.sessionId ? { sessionId: stored.sessionId } : {}), ...(stored.agentProviderId ? { agentProviderId: stored.agentProviderId } : {}), connection: null, ws: null, epoch: null, receipts: [], byRequestId: new Map(), usedRequestIds: new Set(stored.requestIds), queue: [], running: null, outputs: new Map(), announced: new Set() }; for (const receipt of stored.receipts) this.retainReceipt(found, { receipt, nativeHandle: receipt.nativeHandle, withdrawn: true, facts: stored.results?.find(r => r.requestId === receipt.requestId)?.facts ?? "", settled: true, sawResult: receipt.state === "completed", durableReady: true }); @@ -222,6 +292,10 @@ export class ConversationHost { this.refuse(ws, "CONVERSATION_LIMIT", "Stop this connection's conversation before resuming another."); return; } + // A resume keeps the service it opened with (#3616); another is a new disclosure. + if (found.provider !== provider) { + this.refuse(ws,"CONVERSATION_DISCLOSURE","The voice service changed. Review its disclosure and select Start. Nothing was sent to the voice service.",msg.requestId); return; + } conversation = found; if (conversation.connection && conversation.connection !== connection) { // Another device held it: that one's capture ends, this one continues. @@ -240,6 +314,8 @@ export class ConversationHost { return; } conversation = { + provider, + providerSource: target.source, id: crypto.randomUUID(), lastEpoch: 0, ...(!msg.sessionId && msg.agentProviderId ? { agentProviderId: msg.agentProviderId } : {}), @@ -271,7 +347,7 @@ export class ConversationHost { this.endEpoch(conversation, "replaced"); const epoch: Epoch = { number: ++conversation.lastEpoch, - contextualTasks: msg.contextualTasks === true && this.provider.capabilities.contextualTasks === "supported" && !!this.host.catalog.saveConversationTask && !!this.host.catalog.saveConversationEpoch, + contextualTasks: msg.contextualTasks === true && provider.capabilities.contextualTasks === "supported" && !!this.host.catalog.saveConversationTask && !!this.host.catalog.saveConversationEpoch, context: [], contextDigests: new Set(), nativeUsed: new Set(), ...(msg.requestId ? { requestId: msg.requestId } : {}), abort: new AbortController(), @@ -293,7 +369,7 @@ export class ConversationHost { }; let session: LiveConversationSession; try { - const owner = await this.host.dialogue.open({ conversationId: conversation.id, principalId, epoch: epoch.number, providerId: this.provider.id, + const owner = await this.host.dialogue.open({ conversationId: conversation.id, principalId, epoch: epoch.number, providerId: provider.id, ...(conversation.sessionId ? { sessionId: conversation.sessionId } : {}), ...(msg.historyOwnerId ? { historyOwnerId: msg.historyOwnerId } : {}) }); if (owner) {conversation.historyOwnerId = owner.id;conversation.historyGeneration=owner.generation;} if (epoch.closed || connection.closed || !connection.authorization.valid) return; @@ -309,11 +385,13 @@ export class ConversationHost { const retired = this.host.catalog.chatRetired; if (retired && (retired({ conversationId: conversation.id }) || (conversation.sessionId && retired({ sessionId: conversation.sessionId })) || (conversation.historyOwnerId && retired({ ownerId: conversation.historyOwnerId })))) throw new ChatRetiredError(); - if (!this.disclosed(msg)) { + // The default may have changed on another device while history was read: + // the exact echo still decides, and nothing falls back (#3616). + if (this.target(msg)?.provider !== provider || !this.disclosed(msg, provider)) { this.endEpoch(conversation,"refused",undefined,epoch); this.detach(conversation); this.refuse(ws,"CONVERSATION_DISCLOSURE","The voice service changed. Review its disclosure and select Start. Nothing was sent to the voice service.",msg.requestId); return; } - session = await this.provider.open(scope, { + session = await provider.open(scope, { orientation, ...(history ? { history } : {}), signal: epoch.abort.signal, @@ -329,7 +407,7 @@ export class ConversationHost { this.host.log.emit({ severityText: "WARN", body: "live conversation failed to open", - attributes: { "provider.id": this.provider.id, error: err instanceof Error ? err.message : String(err) }, + attributes: { "provider.id": provider.id, error: err instanceof Error ? err.message : String(err) }, }); this.endEpoch(conversation, "provider_error", "The voice service or prior chat context could not be opened. No work was replayed. Restore access before restarting voice.", epoch); return; @@ -351,7 +429,8 @@ export class ConversationHost { epoch: epoch.number, ...(conversation.sessionId !== undefined ? { sessionId: conversation.sessionId } : {}), ...(conversation.agentProviderId ? { agentProviderId: conversation.agentProviderId } : {}), - ...this.profile(epoch.contextualTasks), + ...this.profileOf(provider, epoch.contextualTasks), + providerSource: conversation.providerSource, limits: { ...CONVERSATION_LIMITS }, resync: { work: conversation.receipts.length, outputs: conversation.outputs.size }, }); @@ -541,7 +620,7 @@ export class ConversationHost { // or indeterminate store is never written to again, not even for an end. if (!msg.resumable && conversation.startedAt !== undefined && conversation.openedEpoch === conversation.lastEpoch && !conversation.epoch?.storageFailing) { this.host.dialogue.ended(conversation.id, conversation.principalId, { kind: "voice_end", conversationId: conversation.id, epoch: conversation.lastEpoch, - providerId: this.provider.id, startedAt: conversation.startedAt, endedAt: Math.max(conversation.startedAt, Date.now()) }); + providerId: conversation.provider.id, startedAt: conversation.startedAt, endedAt: Math.max(conversation.startedAt, Date.now()) }); } this.endEpoch(conversation, "stopped"); this.detach(conversation); @@ -675,7 +754,7 @@ export class ConversationHost { this.send(conversation, { type: "conversation_event", ...scope, event: { kind: "interrupted", ...(event.outputId ? { outputId: event.outputId } : {}), } }); - this.host.dialogue.interruption(conversation.id, { kind: "voice_interruption", conversationId: conversation.id, epoch: epoch.number, providerId: this.provider.id, + this.host.dialogue.interruption(conversation.id, { kind: "voice_interruption", conversationId: conversation.id, epoch: epoch.number, providerId: conversation.provider.id, ...(event.outputId ? { outputId: event.outputId } : {}) }, epoch.interruptions++); return; } @@ -1135,7 +1214,7 @@ export class ConversationHost { // The ledger outlives epochs: a reconnect re-lists a pending request but // never announces it a second time. Speech stays closed until the // provider has proven exact host-approved copy. - const announce = !conversation.announced.has(key) && this.provider.capabilities.exactPermissionSpeech === "supported"; + const announce = !conversation.announced.has(key) && conversation.provider.capabilities.exactPermissionSpeech === "supported"; conversation.announced.add(key); this.send(conversation, { type: "conversation_permission", @@ -1217,7 +1296,7 @@ export class ConversationHost { if (frame.type === "conversation_event" && (frame.event.kind === "input_fragment" || frame.event.kind === "unassigned_input_fragment" || frame.event.kind === "output_transcript")) { const epoch = conversation.epoch; const connection = conversation.connection; - const retained = this.host.dialogue.voice(conversation.id, { kind: "voice", conversationId: conversation.id, epoch: frame.epoch, providerId: this.provider.id, ...(epoch?.model ? {model:epoch.model} : {}), ...(epoch?.api ? {api:epoch.api} : {}), event: frame.event }, (saved) => { + const retained = this.host.dialogue.voice(conversation.id, { kind: "voice", conversationId: conversation.id, epoch: frame.epoch, providerId: conversation.provider.id, ...(epoch?.model ? {model:epoch.model} : {}), ...(epoch?.api ? {api:epoch.api} : {}), event: frame.event }, (saved) => { if (conversation.ws && conversation.epoch === epoch && !epoch?.closed && connection?.authorization.valid && !connection.closed) { try { this.host.sendMessage(conversation.ws, saved ? frame : {...frame,retention:"unsaved"}); } catch { /* Socket closure does not turn a committed record into unsaved text. */ } diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index 686c36cae8..59372183bf 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -27,7 +27,7 @@ import { spliceLocalExchanges, stripLocalContext } from "./local-exchanges.js"; import { FailureReplay } from "./turn-failures.js"; import type { AgentBackend, LiveConversationProvider } from "@schlessera/brain-ui-sdk/server"; import { createKeyedLock, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; -import { assertLiveConversationProvider } from "@schlessera/brain-ui-sdk/server"; +import { createLiveProviderRegistry, type LiveProviderRegistry } from "../voice/live-providers.js"; import { ConversationHost } from "./conversation.js"; import { turnLogAttributes, type TurnLogContext } from "./limits.js"; import type { Labeller } from "../labels/labeller.js"; @@ -204,6 +204,20 @@ export interface WsHostOptions { * @experimental Part of the LiveConversationProvider seam until 1.0. */ conversationProvider?: LiveConversationProvider; + /** + * Several live-conversation providers (#3616); exclusive with + * `conversationProvider`, which means a list of one. + * @experimental Part of the LiveConversationProvider seam until 1.0. + */ + conversationProviders?: LiveConversationProvider[]; + /** Must name a registered live-conversation provider (#3616). */ + defaultConversationProviderId?: string; + /** + * The saved brain-wide live-service default (#3616), read at each hello and + * Start. Absent reads as nothing saved. + * @internal Supplied by createApp. + */ + liveDefaultProvider?: () => string | null; /** * Host draft storage (#979). Present: `server_hello` advertises * `sessionDrafts` and an accepted `chat_message.draftRef` consumes its @@ -328,6 +342,8 @@ export class WsHost { * @internal Host wiring (#1053). */ readonly conversations: ConversationHost | null; + /** Registered live services, fixed at construction (#3616). */ + readonly liveProviders: LiveProviderRegistry; /** @internal Host wiring (#1053). */ readonly classifier: TurnClassifier | null; /** @@ -437,9 +453,10 @@ export class WsHost { this.drafts = options.drafts ?? null; this.attachmentLimits = options.drafts && options.attachmentLimits ? options.attachmentLimits : null; this.toolPermissions = options.toolPermissions ?? null; - if (options.conversationProvider) assertLiveConversationProvider(options.conversationProvider); - this.conversations = options.conversationProvider - ? new ConversationHost(this, options.conversationProvider) + const live = this.liveProviders = createLiveProviderRegistry(options); + const saved = options.liveDefaultProvider ?? (() => null); + this.conversations = live.providers.length > 0 + ? new ConversationHost(this, live, saved) : null; this.dialogue = new DialogueJournal(this.catalog, (page, principalId) => { this.clients.broadcast({ type: "dialogue_history", ...page }, undefined, "sessionDialogue", principalId); diff --git a/packages/ui-server/tests/helpers/http-contract-app.ts b/packages/ui-server/tests/helpers/http-contract-app.ts index fb07a77ae3..fb5d7b961c 100644 --- a/packages/ui-server/tests/helpers/http-contract-app.ts +++ b/packages/ui-server/tests/helpers/http-contract-app.ts @@ -29,6 +29,8 @@ export async function httpContractApp(options: { speechProvider?: SpeechProvider; speechProviders?: SpeechProvider[]; defaultSpeechProviderId?: string; + /** Live-conversation registration (#3616), passed through unchanged. */ + live?: Pick; } = {}) { const root = mkdtempSync(join(tmpdir(), "brain-http-contract-")); const brainPath = join(root, "brain"); @@ -87,6 +89,7 @@ else if (args[0] === "sync") console.log("Fixture sync complete"); defaultSpeechProviderId: options.defaultSpeechProviderId, registry: options.registry ?? createStaticBackendRegistry([backend]), ...(options.speechProvider ? { speechProvider: options.speechProvider } : {}), + ...options.live, ...(options.staticRoot ? { staticRoot } : {}), ...(options.renderer ? { renderer: options.renderer } : {}), }; diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 9acb8c595b..7c2b21f896 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -114,6 +114,8 @@ export const mountLifetimes: Record = { "GET /api/geo/coastline": { path: "/api/geo/coastline?bbox=15.6,38.2,15.8,38.32", body: { coastline: [], attribution: "© OpenStreetMap contributors" } }, "GET /api/voice/providers": { body: { dictation: { effective: "webspeech", source: "host" } } }, "GET /api/voice/dictation/settings": { body: { defaultProvider: null, smart: true, revision: "0" } }, + "GET /api/settings/voice": { body: { defaultProvider: null, revision: 0 } }, + "PUT /api/settings/voice": { init: json("PUT", { defaultProvider: null, revision: 0 }), body: { defaultProvider: null, revision: 1 } }, "PUT /api/voice/dictation/settings": { init: { method: "PUT", headers: { "If-Match": '"0"' }, body: JSON.stringify({ defaultProvider: "webspeech", smart: false }) }, body: { defaultProvider: "webspeech", smart: false, revision: "1" } }, "GET /api/voice/capabilities": { body: { providerId: "webspeech", capabilities: { savedAudio: false } } }, "GET /api/voice/recordings/:recordingId/transcription": { path: "/api/voice/recordings/00000000-0000-4000-8000-000000000001/transcription", status: 404, body: { error: "transcription_not_found" } }, diff --git a/packages/ui-server/tests/live-provider-selection.test.ts b/packages/ui-server/tests/live-provider-selection.test.ts new file mode 100644 index 0000000000..7cb5d4b8af --- /dev/null +++ b/packages/ui-server/tests/live-provider-selection.test.ts @@ -0,0 +1,310 @@ +// #3616: which registered live service a Start opens. Two keyless adapter +// doubles stand in for the two existing adapters; every assertion names the +// double whose `open` ran, or that neither did. +import { afterEach, describe, expect, test } from "bun:test"; +import type { LiveConversationProvider } from "@schlessera/brain-ui-sdk/server"; +import { parseServerMessage } from "@schlessera/brain-ui-sdk/schemas"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { createUiDb } from "../src/db/client"; +import type { WSContext } from "../src/ws/clients"; +import { createWsHandlers } from "../src/ws/connection"; +import { WsHost } from "../src/ws/host"; +import { createSessionCatalog } from "../src/ws/session-catalog"; +import { createLiveProviderRegistry } from "../src/voice/live-providers"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { fakeLiveProvider, type FakeLiveSession } from "./helpers/live-conversation"; +import { testPrincipal } from "./helpers/principal"; +import { httpContractApp } from "./helpers/http-contract-app"; +import { createPrincipal } from "../src/db/principals"; +import { getLiveDefaultProvider, getSetting } from "../src/db/settings"; +import { isLiveSettingsWriter } from "../src/routes/live-settings"; +import { generateSignedCookie } from "hono/cookie"; +import { Database } from "bun:sqlite"; +import { resolveAmbientPrincipal } from "../src/db/principals"; + +async function until(cond: () => boolean, timeoutMs = 2000): Promise { + const start = Date.now(); + while (!cond()) { + if (Date.now() - start > timeoutMs) throw new Error("until: timed out"); + await new Promise((r) => setTimeout(r, 5)); + } +} + +/** A fake adapter under its own id and disclosure; `sessions` records every `open`. */ +function double(id: string, voiceService: string): { provider: LiveConversationProvider; sessions: FakeLiveSession[] } { + const fake = fakeLiveProvider(); + return { provider: { ...fake.provider, id, disclosure: { ...fake.provider.disclosure, voiceService } }, sessions: fake.sessions }; +} + +let cleanup: (() => Promise) | null = null; +afterEach(async () => { await cleanup?.(); cleanup = null; }); + +function setup(options: { ids: ("gemini" | "gpt")[]; host?: string; saved?: string | null; legacy?: boolean }) { + const gemini = double("gemini-live", "Fictional Gemini Live of Ithaca"); + const gpt = double("gpt-live", "Fictional GPT-Live of Ithaca"); + const pick = { gemini, gpt }; + const providers = options.ids.map((id) => pick[id].provider); + const db = createUiDb(":memory:"); + let saved = options.saved ?? null; + const backend = makeFakeBackend({ id: "fake" }); + const host = new WsHost({ + registry: createStaticBackendRegistry([backend], backend.id), + catalog: createSessionCatalog(() => db), + ...(options.legacy ? { conversationProvider: providers[0]! } : { conversationProviders: providers }), + ...(options.host ? { defaultConversationProviderId: options.host } : {}), + liveDefaultProvider: () => saved, + }); + cleanup = async () => { await host.close(); db.close(); }; + const opened = () => ({ gemini: gemini.sessions.length, gpt: gpt.sessions.length }); + async function connect() { + const handlers = createWsHandlers(host, testPrincipal()); + const sent: string[] = []; + const ws = { send: (data: string) => sent.push(data) } as WSContext; + await handlers.onOpen(undefined as never, ws); + const frames = (type?: string): any[] => sent.map((s) => JSON.parse(s)).filter((f) => type === undefined || f.type === type); + const hello = frames("server_hello")[0]; + /** Start and wait for its answer: the opened frame, or the refusal. */ + async function start(frame: Record) { + const requestId = crypto.randomUUID(); + const before = sent.length; + await handlers.onMessage({ data: JSON.stringify({ type: "conversation_start", contextualTasks: true, requestId, ...frame }) } as MessageEvent, ws); + await until(() => sent.slice(before).some((s) => { const f = JSON.parse(s); return f.requestId === requestId && (f.type === "conversation_opened" || f.type === "error" || f.type === "conversation_closed"); })); + return sent.slice(before).map((s) => JSON.parse(s)).find((f) => f.requestId === requestId); + } + return { hello, frames, start, sent }; + } + return { host, gemini, gpt, opened, connect, setSaved: (id: string | null) => { saved = id; } }; +} + +const profileOf = (s: ReturnType, id: string) => s.host.conversations!.profile(true, id)!; + +describe("registration", () => { + const a = double("gemini-live", "A"), b = double("gpt-live", "B"); + test("startup fails on both options, duplicate ids or an unregistered host default", () => { + expect(() => createLiveProviderRegistry({ conversationProvider: a.provider, conversationProviders: [b.provider] })).toThrow("not both"); + expect(() => createLiveProviderRegistry({ conversationProviders: [a.provider, { ...b.provider, id: "gemini-live" }] })).toThrow('Duplicate live conversation provider id "gemini-live"'); + expect(() => createLiveProviderRegistry({ conversationProviders: [a.provider], defaultConversationProviderId: "gpt-live" })).toThrow("not a registered"); + expect(() => createLiveProviderRegistry({ defaultConversationProviderId: "gpt-live" })).toThrow("not a registered"); + expect(() => createLiveProviderRegistry({ conversationProviders: [{ ...a.provider, id: "Gemini" }] })).toThrow("lowercase"); + }); + test("the legacy option means a list of one and is accepted alone", () => { + expect(createLiveProviderRegistry({ conversationProvider: a.provider }).providers.map((p) => p.id)).toEqual(["gemini-live"]); + expect(createLiveProviderRegistry({}).providers).toEqual([]); + }); +}); + +// §4 of the design: every row, the hello a client sees and which double a +// Start without a pick opens. `effective: null` means no double opens. +const rows: { name: string; ids: ("gemini" | "gpt")[]; saved: string | null; host?: string; effective: string | null; source: string; legacy?: boolean }[] = [ + { name: "one, nothing saved, legacy option", ids: ["gemini"], saved: null, effective: "gemini-live", source: "only", legacy: true }, + { name: "one, nothing saved, host default", ids: ["gpt"], saved: null, host: "gpt-live", effective: "gpt-live", source: "host" }, + { name: "one, saved that one", ids: ["gemini"], saved: "gemini-live", effective: "gemini-live", source: "saved" }, + { name: "one, saved removed", ids: ["gemini"], saved: "gpt-live", effective: null, source: "none" }, + { name: "two, nothing saved, host default", ids: ["gemini", "gpt"], saved: null, host: "gpt-live", effective: "gpt-live", source: "host" }, + { name: "two, nothing saved, no host default", ids: ["gemini", "gpt"], saved: null, effective: null, source: "none" }, + { name: "two, saved usable over the host default", ids: ["gemini", "gpt"], saved: "gemini-live", host: "gpt-live", effective: "gemini-live", source: "saved" }, + { name: "two, saved unusable, host default not substituted", ids: ["gemini", "gpt"], saved: "retired-live", host: "gpt-live", effective: null, source: "none" }, +]; + +describe("compatibility table", () => { + for (const row of rows) test(row.name, async () => { + const s = setup({ ids: row.ids, host: row.host, saved: row.saved, legacy: row.legacy }); + const client = await s.connect(); + const ids: string[] = row.ids.map((id) => id === "gemini" ? "gemini-live" : "gpt-live"); + expect(client.hello.capabilities.liveConversation).toBe(true); + expect(client.hello.conversationProfiles.map((p: { providerId: string }) => p.providerId)).toEqual(ids); + expect(client.hello.liveDefault).toEqual({ saved: row.saved, savedUsable: row.saved !== null && ids.includes(row.saved), effective: row.effective, source: row.source }); + // The legacy field is the effective profile, and absent without one (R1). + if (row.effective) expect(client.hello.conversationProfile).toEqual(profileOf(s, row.effective)); + else expect("conversationProfile" in client.hello).toBe(false); + // An SDK client parses the additive hello whole. + const parsed = parseServerMessage(JSON.stringify(client.hello)); + expect(parsed.ok && parsed.message.type === "server_hello" && parsed.message.liveDefault).toEqual(client.hello.liveDefault); + expect(s.opened(), "discovery opens no provider").toEqual({ gemini: 0, gpt: 0 }); + + // A legacy Start (no providerId) echoes the hello's profile. Without an + // effective service, even a crafted echo of the host default or the only + // registered profile opens nothing. + const legacy = await client.start({ disclosed: client.hello.conversationProfile ?? profileOf(s, row.host ?? ids[0]!) }); + if (row.effective) { + expect(legacy.type).toBe("conversation_opened"); + expect(legacy.providerId).toBe(row.effective); + expect(legacy.providerSource).toBe(row.source); + expect(s.opened()).toEqual({ gemini: row.effective === "gemini-live" ? 1 : 0, gpt: row.effective === "gpt-live" ? 1 : 0 }); + } else { + expect(legacy).toMatchObject({ type: "error", code: "CONVERSATION_DISCLOSURE" }); + expect(s.opened(), "no effective service opens nothing, not the host default").toEqual({ gemini: 0, gpt: 0 }); + } + }); +}); + +describe("explicit pick", () => { + test("Change opens the picked service for this Start only and writes nothing", async () => { + const s = setup({ ids: ["gemini", "gpt"], saved: "gemini-live" }); + const client = await s.connect(); + const opened = await client.start({ providerId: "gpt-live", disclosed: profileOf(s, "gpt-live") }); + expect(opened).toMatchObject({ type: "conversation_opened", providerId: "gpt-live", providerSource: "change" }); + expect(s.opened()).toEqual({ gemini: 0, gpt: 1 }); + expect(s.host.conversations!.liveDefault()).toEqual({ saved: "gemini-live", savedUsable: true, effective: "gemini-live", source: "saved" }); + }); + + test("an unusable saved default needs an explicit pick, which then opens", async () => { + const s = setup({ ids: ["gemini", "gpt"], saved: "retired-live", host: "gemini-live" }); + const client = await s.connect(); + expect(await client.start({ disclosed: profileOf(s, "gemini-live") })).toMatchObject({ type: "error", code: "CONVERSATION_DISCLOSURE" }); + expect(s.opened(), "the host default is never substituted").toEqual({ gemini: 0, gpt: 0 }); + expect(await client.start({ providerId: "gpt-live", disclosed: profileOf(s, "gpt-live") })).toMatchObject({ type: "conversation_opened", providerId: "gpt-live" }); + expect(s.opened()).toEqual({ gemini: 0, gpt: 1 }); + }); + + test("a providerId that differs from the disclosed profile, or is unregistered, opens nothing", async () => { + const s = setup({ ids: ["gemini", "gpt"], host: "gemini-live" }); + const client = await s.connect(); + expect(await client.start({ providerId: "gpt-live", disclosed: profileOf(s, "gemini-live") })).toMatchObject({ type: "error", code: "CONVERSATION_DISCLOSURE" }); + expect(await client.start({ providerId: "retired-live", disclosed: { ...profileOf(s, "gemini-live"), providerId: "retired-live" } })).toMatchObject({ type: "error", code: "CONVERSATION_DISCLOSURE" }); + expect(s.opened()).toEqual({ gemini: 0, gpt: 0 }); + }); +}); + +describe("activation", () => { + test("a saved default applies at the next Start; a running conversation and its resume keep their service", async () => { + const s = setup({ ids: ["gemini", "gpt"], saved: "gemini-live" }); + const client = await s.connect(); + const first = await client.start({ disclosed: client.hello.conversationProfile }); + expect(first).toMatchObject({ type: "conversation_opened", providerId: "gemini-live", providerSource: "saved" }); + s.setSaved("gpt-live"); + s.host.conversations!.broadcastSettings(); + const update = client.frames("live_settings").at(-1); + expect(update.liveDefault).toEqual({ saved: "gpt-live", savedUsable: true, effective: "gpt-live", source: "saved" }); + expect(parseServerMessage(JSON.stringify(update)).ok).toBe(true); + expect(s.gemini.sessions[0]!.closed, "a save never closes or retargets the running conversation").toBe(false); + expect(s.opened()).toEqual({ gemini: 1, gpt: 0 }); + // Reconnect of the same conversation keeps gemini, with or without providerId. + const resumed = await client.start({ conversationId: first.conversationId, disclosed: profileOf(s, "gemini-live") }); + expect(resumed).toMatchObject({ type: "conversation_opened", providerId: "gemini-live", conversationId: first.conversationId, epoch: 2 }); + expect(await client.start({ conversationId: first.conversationId, providerId: "gpt-live", disclosed: profileOf(s, "gpt-live") })) + .toMatchObject({ type: "error", code: "CONVERSATION_DISCLOSURE" }); + expect(s.opened()).toEqual({ gemini: 2, gpt: 0 }); + // A new connection's next explicit Start uses the new default. + const other = await s.connect(); + expect(other.hello.conversationProfile.providerId).toBe("gpt-live"); + expect(await other.start({ disclosed: other.hello.conversationProfile })).toMatchObject({ type: "conversation_opened", providerId: "gpt-live", providerSource: "saved" }); + expect(s.opened()).toEqual({ gemini: 2, gpt: 1 }); + }); + + test("a default changed between disclosure and Start refuses a legacy Start", async () => { + const s = setup({ ids: ["gemini", "gpt"], saved: "gemini-live" }); + const client = await s.connect(); + const disclosed = client.hello.conversationProfile; + s.setSaved("gpt-live"); + expect(await client.start({ disclosed })).toMatchObject({ type: "error", code: "CONVERSATION_DISCLOSURE" }); + expect(s.opened()).toEqual({ gemini: 0, gpt: 0 }); + }); +}); + +describe("Settings › Voice live default route", () => { + const secret = "odysseus-live-settings-cookie-secret"; + const path = "/api/settings/voice"; + async function app() { + const gemini = double("gemini-live", "Fictional Gemini Live of Ithaca"); + const gpt = double("gpt-live", "Fictional GPT-Live of Ithaca"); + const t = await httpContractApp({ + env: { AUTH_MODE: "password", COOKIE_SECRET: secret, BRAIN_UI_PASSWORD_HASH: "fixture" }, + live: { conversationProviders: [gemini.provider, gpt.provider], defaultConversationProviderId: "gemini-live" }, + }); + const cookie = async (id: string) => ({ cookie: (await generateSignedCookie("brain_ui_session", id, secret)).split(";")[0]! }); + return { t, gemini, gpt, cookie }; + } + const put = (body: unknown, headers: Record) => ({ method: "PUT", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) }); + + test("owner-only writes, revisions, unknown ids and persistence across a restart", async () => { + const { t, gemini, gpt, cookie } = await app(); + try { + const owner = createPrincipal(t.app.db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const agent = createPrincipal(t.app.db, { authMethod: "delegated", label: "Eurylochus", createdBy: owner.id, ttlSeconds: 3600 }); + const ownerHeaders = await cookie(owner.id); + const agentHeaders = await cookie(agent.id); + expect((await t.fetch(path)).status).toBe(401); + const initial = await t.fetch(path, { headers: ownerHeaders }); + expect(initial.headers.get("cache-control")).toBe("no-store"); + expect(await initial.json()).toEqual({ defaultProvider: null, revision: 0 }); + + // The guard refuses a delegated principal with an empty body, before validation. + for (const body of [{ defaultProvider: "gpt-live", revision: 0 }, { nonsense: true }]) { + const refused = await t.fetch(path, put(body, agentHeaders)); + expect(refused.status, "LIVE_SETTINGS_OWNER_ONLY").toBe(403); + expect(await refused.text()).toBe(""); + } + expect((await t.fetch(path, { headers: agentHeaders })).status, "an agent principal does not read it either").toBe(403); + expect(getLiveDefaultProvider(t.app.db)).toEqual({ defaultProvider: null, revision: 0 }); + + expect((await t.fetch(path, { ...put({ defaultProvider: "gpt-live", revision: 0 }, ownerHeaders), headers: { ...ownerHeaders, "content-type": "text/plain" } })).status).toBe(415); + const invalid = await t.fetch(path, put({ defaultProvider: "gpt-live" }, ownerHeaders)); + expect(invalid.status).toBe(400); expect((await invalid.json()).error).toBe("LIVE_SETTINGS_INVALID"); + const unknown = await t.fetch(path, put({ defaultProvider: "retired-live", revision: 0 }, ownerHeaders)); + expect(unknown.status).toBe(400); + const unknownBody = await unknown.text(); + expect(JSON.parse(unknownBody).error).toBe("LIVE_PROVIDER_UNKNOWN"); + + const concurrent = await Promise.all([t.fetch(path, put({ defaultProvider: "gpt-live", revision: 0 }, ownerHeaders)), t.fetch(path, put({ defaultProvider: "gemini-live", revision: 0 }, ownerHeaders))]); + expect(concurrent.map((r) => r.status).sort()).toEqual([200, 409]); + const current = await concurrent.find((r) => r.status === 200)!.json(); + expect(current.revision).toBe(1); + expect(await concurrent.find((r) => r.status === 409)!.json()).toEqual({ error: "LIVE_SETTINGS_CHANGED", message: "Changed on another device.", current }); + const saved = await (await t.fetch(path, put({ defaultProvider: "gpt-live", revision: 1 }, ownerHeaders))).json(); + expect(saved).toEqual({ defaultProvider: "gpt-live", revision: 2 }); + expect(gemini.sessions.length + gpt.sessions.length, "a save opens no provider").toBe(0); + // Nothing secret: no credential, key presence or endpoint in any answer. + expect(JSON.stringify([current, saved, unknownBody])).not.toMatch(/key|token|wss?:|https?:/i); + + // The ordinary model default is independent. + expect(getSetting(t.app.db, "models.default", null)).toBe(null); + + // Persisted server state: another connection to the database file reads + // it, and a host started over it without that service keeps the saved + // id, unusable, with no host-default substitution. + const reader = new Database(t.app.config.dbPath); + let later: WsHost | undefined; + try { + expect(getLiveDefaultProvider(reader)).toEqual({ defaultProvider: "gpt-live", revision: 2 }); + later = new WsHost({ registry: createStaticBackendRegistry([makeFakeBackend({ id: "fake" })], "fake"), catalog: createSessionCatalog(() => reader), + conversationProviders: [gemini.provider], defaultConversationProviderId: "gemini-live", liveDefaultProvider: () => getLiveDefaultProvider(reader).defaultProvider }); + expect(later.conversations!.liveDefault()).toEqual({ saved: "gpt-live", savedUsable: false, effective: null, source: "none" }); + } finally { await later?.close(); reader.close(); } + } finally { + await t.close(); + } + }); + + test("an ambient human may write; a save tells every open connection without retargeting", async () => { + const gemini = double("gemini-live", "Fictional Gemini Live of Ithaca"); + const gpt = double("gpt-live", "Fictional GPT-Live of Ithaca"); + const t = await httpContractApp({ live: { conversationProviders: [gemini.provider, gpt.provider] } }); + try { + const sent: string[] = []; + const ws = { send: (data: string) => sent.push(data), close: () => {}, readyState: 1 } as unknown as WSContext; + const handlers = createWsHandlers(t.app.wsHost, resolveAmbientPrincipal(t.app.db, "none", "No authentication", "No authentication")); + await handlers.onOpen(undefined as never, ws); + expect(JSON.parse(sent[0]!).liveDefault).toEqual({ saved: null, savedUsable: false, effective: null, source: "none" }); + const saved = await t.fetch(path, put({ defaultProvider: "gpt-live", revision: 0 }, {})); + expect(saved.status).toBe(200); + const update = sent.map((s) => JSON.parse(s)).find((f) => f.type === "live_settings"); + expect(update).toEqual({ type: "live_settings", liveDefault: { saved: "gpt-live", savedUsable: true, effective: "gpt-live", source: "saved" }, + conversationProfiles: t.app.wsHost.conversations!.profiles() }); + expect(gemini.sessions.length + gpt.sessions.length).toBe(0); + await handlers.onClose({ code: 1000 } as CloseEvent, ws); + } finally { await t.close(); } + }); +}); + +test("the write guard: owner human sessions and the ambient human only", () => { + const base = testPrincipal(); + expect(isLiveSettingsWriter(base, 0)).toBe(true); + expect(isLiveSettingsWriter({ ...base, authMethod: "passkey" }, 0)).toBe(true); + expect(isLiveSettingsWriter({ ...base, kind: "ambient", authMethod: "ambient" }, 0)).toBe(true); + expect(isLiveSettingsWriter({ ...base, kind: "agent", authMethod: "delegated" }, 0)).toBe(false); + expect(isLiveSettingsWriter({ ...base, kind: "owner", authMethod: "delegated" }, 0)).toBe(false); + expect(isLiveSettingsWriter({ ...base, kind: "system", authMethod: "ambient" }, 0)).toBe(false); + expect(isLiveSettingsWriter({ ...base, revokedAt: 1 }, 2)).toBe(false); + expect(isLiveSettingsWriter(undefined, 0)).toBe(false); +}); diff --git a/packages/ui-server/tests/ws-conversation.test.ts b/packages/ui-server/tests/ws-conversation.test.ts index c525393f99..49c49d3d2b 100644 --- a/packages/ui-server/tests/ws-conversation.test.ts +++ b/packages/ui-server/tests/ws-conversation.test.ts @@ -1364,7 +1364,7 @@ test("a fresh host instance recovers scoped outcomes into a later epoch without await until(() => !s.host.coordinator.isTurnActive()); await s.host.catalog.settled!(); s.host.conversations!.closeAll(); - Object.defineProperty(s.host, "conversations", { value: new ConversationHost(s.host, s.live.provider), configurable: true }); + Object.defineProperty(s.host, "conversations", { value: new ConversationHost(s.host, s.host.liveProviders), configurable: true }); const resumed = await s.connect(); const next = await resumed.open({ conversationId: c.id, contextualTasks: true }); expect(next.epoch).toBe(2); @@ -1394,7 +1394,7 @@ test("concurrent durable recovery has one owner and monotonically distinct epoch const c = await initial.open({ contextualTasks: true }); s.host.conversations!.closeAll(); await s.host.catalog.settled!(); - Object.defineProperty(s.host, "conversations", { value: new ConversationHost(s.host, s.live.provider), configurable: true }); + Object.defineProperty(s.host, "conversations", { value: new ConversationHost(s.host, s.host.liveProviders), configurable: true }); const load = s.host.catalog.loadConversation!.bind(s.host.catalog); const releases: (() => void)[] = []; Object.defineProperty(s.host.catalog, "loadConversation", { value: async (...args: Parameters) => { From 7cfd3b7f3f419fddad6f24937267ac519b4544eb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:57:03 +0000 Subject: [PATCH 02/11] =?UTF-8?q?feat(ui-kit):=20Live=20service=20group=20?= =?UTF-8?q?for=20Settings=20=E2=80=BA=20Voice=20(#3616)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LiveServiceSettings draws the registered services as 52px radio rows with saved default, host default and in use now marks, a dashed unavailable row that cannot be chosen, the zero and one service variants, saving, stale and failed states and the read-only owner line. A wide container puts the label in a 140px column and two services side by side. Stories cover every state at 320px and desktop in both themes, plus the full pane with Dictation and Persona neighbours. Co-Authored-By: Claude Opus 5.5 --- api-report/ui-kit.txt | 38 +++ packages/ui-kit/src/index.ts | 1 + packages/ui-kit/src/tokens.css | 113 +++++++++ .../ui-kit/src/voice/LiveServiceSettings.tsx | 152 +++++++++++ .../stories/voice/LiveService.stories.tsx | 240 ++++++++++++++++++ 5 files changed, 544 insertions(+) create mode 100644 packages/ui-kit/src/voice/LiveServiceSettings.tsx create mode 100644 packages/ui-kit/stories/voice/LiveService.stories.tsx diff --git a/api-report/ui-kit.txt b/api-report/ui-kit.txt index 54c0c126a6..b4471ce1e9 100644 --- a/api-report/ui-kit.txt +++ b/api-report/ui-kit.txt @@ -160,6 +160,10 @@ export "." (./src/index.ts) ListRow type ListRowProps type ListRowVariant + type LiveServiceOption + LiveServiceSettings + type LiveServiceSettingsProps + type LiveServiceStatus type MapCluster type MapLand type MapPath @@ -1590,6 +1594,40 @@ signatures (every public export and the types it is made of) } ListRowVariant (packages/ui-kit/src/types.ts) export type ListRowVariant = "group" | "card" | "launcher" | "plain"; + LiveServiceOption (packages/ui-kit/src/voice/LiveServiceSettings.tsx) + export interface LiveServiceOption { + id: string; + name: string; + detail?: string; + } + LiveServiceSettings (packages/ui-kit/src/voice/LiveServiceSettings.tsx) + export function LiveServiceSettings(p: LiveServiceSettingsProps): import("react").JSX.Element; + LiveServiceSettingsProps (packages/ui-kit/src/voice/LiveServiceSettings.tsx) + export interface LiveServiceSettingsProps { + services: LiveServiceOption[]; + checked: string | null; + saved?: string | null; + hostDefault?: string | null; + inUse?: string | null; + savedUnavailable?: LiveServiceOption | null; + status?: LiveServiceStatus | null; + readOnly?: boolean; + disabled?: boolean; + loading?: boolean; + loadError?: boolean; + onChoose?: (id: string) => void; + onRetry?: () => void; + onReload?: () => void; + } + LiveServiceStatus (packages/ui-kit/src/voice/LiveServiceSettings.tsx) + export type LiveServiceStatus = { + kind: "saving"; + } | { + kind: "stale"; + } | { + kind: "failed"; + text: string; + }; MAILTO_ADDRESSES_MAX (packages/render-template/src/links.ts) recorded in api-report/render-template.txt MailVerdict (packages/render-template/src/links.ts) recorded in api-report/render-template.txt MapCluster (packages/ui-kit/src/blocks/MapView.tsx) diff --git a/packages/ui-kit/src/index.ts b/packages/ui-kit/src/index.ts index 05b4cb445b..00dcf68587 100644 --- a/packages/ui-kit/src/index.ts +++ b/packages/ui-kit/src/index.ts @@ -247,6 +247,7 @@ export { VoiceField, VoiceText, type VoiceFieldLabel, type VoiceFieldProps, type export { MicButton, type MicButtonProps, type MicPhase } from "./voice/MicButton.js"; export { VoiceNotice, type VoiceNoticeAction, type VoiceNoticeProps } from "./voice/VoiceNotice.js"; export { StartCard, type StartCardNotice, type StartCardPersona, type StartCardProps } from "./voice/StartCard.js"; +export { LiveServiceSettings, type LiveServiceOption, type LiveServiceSettingsProps, type LiveServiceStatus } from "./voice/LiveServiceSettings.js"; export { ConversationEndDivider, CutOffTag, diff --git a/packages/ui-kit/src/tokens.css b/packages/ui-kit/src/tokens.css index 825f1c7617..6f2848ba71 100644 --- a/packages/ui-kit/src/tokens.css +++ b/packages/ui-kit/src/tokens.css @@ -2951,3 +2951,116 @@ html:has(dialog.bk-overlay[open]:modal) { overflow: hidden; } [data-motion="reduce"] .bk-voice-ring-fill { transition: none; } [data-motion="reduce"] .bk-voice-cursor, [data-motion="reduce"] .bk-voice-ctl-spin, [data-motion="reduce"] .bk-voice-spin { animation: none; } [data-motion="reduce"] .bk-spoken-turn[data-details] .bk-transcript-reveal { transition: none; } + +/* Settings › Voice, Live service group (#3616). Phone: label above the rows. + A wide container puts the label in a 140px column, and exactly two + services side by side. Rows are 52px with the whole row as the target. */ +.bk-live-service { + /* An inline-size container takes no width from its content: fill the column. */ + container-type: inline-size; + box-sizing: border-box; + width: 100%; + min-width: 0; +} +.bk-live-service-grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 8px; + min-width: 0; +} +.bk-live-service-label { + margin: 0; + font: 600 11px/1.4 'JetBrains Mono', ui-monospace, monospace; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--bk-color-ink-mute); +} +.bk-live-service-body, +.bk-live-service-stack { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} +.bk-live-service-options { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 8px; +} +.bk-live-service-row { + display: flex; + align-items: flex-start; + gap: 12px; + box-sizing: border-box; + min-height: 52px; + padding: 10px 12px; + border: 1px solid var(--bk-color-edge); + border-radius: 10px; + background: var(--bk-color-surface); + color: var(--bk-color-ink); + flex-direction: column; + justify-content: center; +} +label.bk-live-service-row { + flex-direction: row; + justify-content: flex-start; + align-items: center; + cursor: pointer; +} +.bk-live-service-row[data-checked] { + border-color: var(--bk-choice-border-selected); + background: var(--bk-choice-tint-selected); +} +.bk-live-service-row[data-disabled] { + cursor: not-allowed; + opacity: 0.6; +} +.bk-live-service-row[data-unavailable] { + border-style: dashed; + background: transparent; + gap: 2px; +} +.bk-live-service-radio { + width: 20px; + height: 20px; + margin: 0; + flex: none; + accent-color: var(--bk-teal-ink); +} +.bk-live-service-text { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} +.bk-live-service-name { + font: 600 13px/1.35 'Plus Jakarta Sans', sans-serif; +} +.bk-live-service-mark { + font-size: 10px; + line-height: 1.4; + color: var(--bk-color-ink-mute); +} +.bk-live-service-detail, +.bk-live-service-note, +.bk-live-service-hint { + margin: 0; + font: 400 12px/1.45 'Plus Jakarta Sans', sans-serif; + color: var(--bk-color-ink-mute); +} +.bk-live-service-hint { + font-weight: 600; + color: var(--bk-color-ink); +} +.bk-live-service-status:empty { + display: none; +} +@container (min-width: 560px) { + .bk-live-service-grid { + grid-template-columns: 140px minmax(0, 1fr); + column-gap: 16px; + } + .bk-live-service[data-count="2"] .bk-live-service-options { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} diff --git a/packages/ui-kit/src/voice/LiveServiceSettings.tsx b/packages/ui-kit/src/voice/LiveServiceSettings.tsx new file mode 100644 index 0000000000..27c8068271 --- /dev/null +++ b/packages/ui-kit/src/voice/LiveServiceSettings.tsx @@ -0,0 +1,152 @@ +import { useId } from "react"; + +import { Button } from "../primitives/Button.js"; +import { Callout } from "../primitives/Callout.js"; +import { font } from "../tokens.js"; + +export interface LiveServiceOption { + id: string; + /** Short display name: `Gemini Live`. */ + name: string; + /** One plain line on where audio goes. Never a credential or an endpoint. */ + detail?: string; +} + +export type LiveServiceStatus = + | { kind: "saving" } + /** A 409: another device saved first; the latest value is shown. */ + | { kind: "stale" } + | { kind: "failed"; text: string }; + +export interface LiveServiceSettingsProps { + /** Registered (usable) services, in the host's order. */ + services: LiveServiceOption[]; + /** The checked radio. `null` checks nothing ("Pick a default"). */ + checked: string | null; + /** The saved brain-wide default, marked `saved default`. */ + saved?: string | null; + /** The host's default, marked `host default` while nothing is saved. */ + hostDefault?: string | null; + /** The service a running conversation uses, marked `in use now`. */ + inUse?: string | null; + /** A saved default the host no longer registers: a dashed row that cannot be chosen. */ + savedUnavailable?: LiveServiceOption | null; + status?: LiveServiceStatus | null; + /** Not the owner: the radios stay disabled and say why. */ + readOnly?: boolean; + /** No write is possible right now (read-only, or still loading). */ + disabled?: boolean; + loading?: boolean; + /** The saved value could not be read. */ + loadError?: boolean; + onChoose?: (id: string) => void; + onRetry?: () => void; + onReload?: () => void; +} + +const mono = font.mono; + +/** + * The Live service group of Settings › Voice (#3616): which live-conversation + * service a new Start uses when the Start card names none. One radio row per + * registered service, saved the moment it is picked; a dashed row for a saved + * default the host no longer registers, which cannot be chosen. A save applies + * from the next Start and never retargets a running conversation. + * + * Presentation only: it opens no provider, no microphone and reads no history. + * On a wide container the label sits in a 140px column and exactly two + * services sit side by side. + */ +export function LiveServiceSettings(p: LiveServiceSettingsProps) { + const id = useId(); + const heading = `${id}-heading`; + const owner = `${id}-owner`; + const services = p.services; + const unavailable = p.savedUnavailable ?? null; + const single = services.length === 1 && !unavailable; + const disabled = p.disabled === true || p.readOnly === true; + const marks = (service: LiveServiceOption) => [ + p.saved === service.id ? "saved default" : p.saved == null && p.hostDefault === service.id ? "host default" : null, + p.inUse === service.id ? "in use now" : null, + ].filter(Boolean).join(" · "); + + return ( +
+
+

Live service

+
+ {p.loading ?

Loading the live services…

: null} + {p.loadError ? ( +
+ + {p.onReload ?
: null} +
+ ) : null} + + {!p.loading && services.length === 0 ? ( +

Live conversation isn{"’"}t set up on this host.

+ ) : null} + + {!p.loading && single ? ( +
+ {services[0]!.name} + The only live service on this host{services[0]!.detail ? `. ${services[0]!.detail}` : ""} +
+ ) : null} + + {!p.loading && !single && services.length > 0 ? ( + <> + {unavailable ? ( +
+ {unavailable.name} + saved default · not available + Not on this host now. Each Start asks you to choose until you pick a new default. +
+ ) : null} + {p.checked === null && !unavailable ?

Pick a default

: null} +
+ {services.map((service) => { + const isChecked = service.id === p.checked; + const mark = marks(service); + return ( + + ); + })} +
+ + ) : null} + + {!p.loading && services.length > 0 ? ( +

Used from the next Start. A running conversation keeps its service.

+ ) : null} + {p.readOnly ?

Only the owner can change this.

: null} +
+ {p.status?.kind === "saving" ? "Saving…" : p.status?.kind === "stale" ? "Changed on another device. Showing the latest." : ""} +
+ {p.status?.kind === "failed" ? ( +
+ + {p.onRetry ?
: null} +
+ ) : null} +
+
+
+ ); +} diff --git a/packages/ui-kit/stories/voice/LiveService.stories.tsx b/packages/ui-kit/stories/voice/LiveService.stories.tsx new file mode 100644 index 0000000000..663cc3debe --- /dev/null +++ b/packages/ui-kit/stories/voice/LiveService.stories.tsx @@ -0,0 +1,240 @@ +import preview from "#.storybook/preview"; +import { useState } from "react"; +import { expect, userEvent } from "storybook/test"; + +import { ScreenHeader } from "../../src/chrome/ScreenHeader.js"; +import { Toggle } from "../../src/primitives/Toggle.js"; +import { LiveServiceSettings, type LiveServiceOption, type LiveServiceSettingsProps } from "../../src/voice/LiveServiceSettings.js"; +import { stage } from "../_stage.js"; +import { voiceA11y } from "./_checks.js"; + +/** + * Settings › Voice, the Live service group (#3616). Which live-conversation + * service a new Start uses when the Start card names none. A pick saves the + * brain-wide default at once; it applies from the next Start, never to a + * running conversation. A saved default the host no longer registers is a + * dashed row that cannot be chosen: each Start then asks for a pick (S3d), + * and the host default is never substituted. + */ +const meta = preview.meta({ + title: "Voice/Settings · Live service", + decorators: [stage], +}); + +const GEMINI: LiveServiceOption = { id: "gemini-live", name: "Gemini Live", detail: "Audio and this chat's text go to Google." }; +const GPT: LiveServiceOption = { id: "gpt-live", name: "GPT-Live", detail: "Audio and this chat's text go to OpenAI." }; + +/** Every row, measured: 52px rows, 44px targets, nothing outside the column. */ +async function rows(root: HTMLElement) { + await voiceA11y(root); + for (const row of root.querySelectorAll(".bk-live-service-row")) { + await expect(Math.round(row.getBoundingClientRect().height), "52px row").toBeGreaterThanOrEqual(52); + // The radio starts every row at its padding, whatever the name's length. + const radio = row.querySelector("input"); + if (radio) await expect(Math.round(radio.getBoundingClientRect().left - row.getBoundingClientRect().left), "radio at the row's start").toBeLessThanOrEqual(14); + } +} + +/** Interactive: the group as a pane draws it, saving on pick. */ +function Live(p: Partial & { initial?: string | null }) { + const [checked, setChecked] = useState(p.initial ?? p.checked ?? null); + return { setChecked(id); p.onChoose?.(id); }} />; +} + +/** No live service is registered: the honest unavailable line, nothing to choose. */ +export const Zero = meta.story({ + name: "Zero services", + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + await expect(canvas.getByText("Live conversation isn’t set up on this host.")).toBeVisible(); + await expect(canvas.queryByRole("radio")).toBeNull(); + }, +}); + +/** One service: a read-only row, no radio. */ +export const One = meta.story({ + name: "One service", + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + await expect(canvas.queryByRole("radio")).toBeNull(); + await expect(canvas.getByText(/The only live service on this host/)).toBeVisible(); + }, +}); + +/** Several, nothing saved and no host default: nothing checked, "Pick a default". */ +export const SeveralNoDefault = meta.story({ + name: "Several · pick a default", + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + const group = canvas.getByRole("radiogroup", { name: "Live service" }); + await expect(group).toBeVisible(); + await expect(canvas.getByText("Pick a default")).toBeVisible(); + for (const radio of canvas.getAllByRole("radio")) await expect(radio).not.toBeChecked(); + // A pick checks the row and marks it the saved default. + await userEvent.click(canvas.getByRole("radio", { name: /GPT-Live/ })); + await expect(canvas.getByRole("radio", { name: /GPT-Live/ })).toBeChecked(); + await expect(canvas.getByText("saved default")).toBeVisible(); + }, +}); + +/** Several, nothing saved, a host default: it is checked and marked "host default". */ +export const SeveralHostDefault = meta.story({ + name: "Several · host default", + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + await expect(canvas.getByRole("radio", { name: /GPT-Live/ })).toBeChecked(); + await expect(canvas.getByText("host default")).toBeVisible(); + }, +}); + +/** The saved default runs a conversation now; another is marked "in use now". Arrow keys move and select. */ +export const SavedAndInUse = meta.story({ + name: "Several · saved, another in use", + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + await expect(canvas.getByText("saved default")).toBeVisible(); + await expect(canvas.getByText("in use now")).toBeVisible(); + await expect(canvas.getByText("Used from the next Start. A running conversation keeps its service.")).toBeVisible(); + const gemini = canvas.getByRole("radio", { name: /Gemini Live/ }); + gemini.focus(); + await userEvent.keyboard("{ArrowDown}"); + await expect(canvas.getByRole("radio", { name: /GPT-Live/ })).toBeChecked(); + await expect(canvas.getByRole("radio", { name: /GPT-Live/ })).toHaveFocus(); + }, +}); + +/** A saved default the host no longer registers: dashed, announced, never selectable. */ +export const SavedUnavailable = meta.story({ + name: "Saved default · not available", + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + const dashed = canvasElement.querySelector("[data-live-service-unavailable]")!; + await expect(dashed.textContent).toContain("GPT-Live"); + await expect(dashed.textContent).toContain("saved default · not available"); + await expect(getComputedStyle(dashed).borderTopStyle).toBe("dashed"); + await expect(canvas.queryByRole("radio", { name: /GPT-Live/ }), "the unavailable default is not a choice").toBeNull(); + await expect(canvas.getByRole("radio", { name: /Gemini Live/ })).not.toBeChecked(); + }, +}); + +/** Saving, then a 409: the latest value is shown with an inline line. */ +export const SavingAndStale = meta.story({ + name: "Saving · changed on another device", + render: () =>
+ + +
, + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + await expect(canvas.getByText("Saving…")).toBeVisible(); + await expect(canvas.getByText("Changed on another device. Showing the latest.")).toBeVisible(); + }, +}); + +/** A failed save reverts and offers Try again; a non-owner sees why the radios are off. */ +export const FailedAndReadOnly = meta.story({ + name: "Save failed · read-only", + render: () =>
+ {}} /> + +
, + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + await expect(canvas.getByRole("alert")).toHaveTextContent("Couldn't save. Your live service is unchanged."); + await expect(canvas.getByRole("button", { name: "Try again" })).toBeVisible(); + await expect(canvas.getByText("Only the owner can change this.")).toBeVisible(); + const readOnly = canvas.getAllByRole("radiogroup")[1]!; + for (const radio of readOnly.querySelectorAll("input")) await expect(radio).toBeDisabled(); + }, +}); + +/** Desktop: the label in a 140px column, exactly two services side by side. */ +export const Desktop = meta.story({ + name: "Desktop · two side by side", + parameters: { stageWidth: "none" }, + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + const label = canvas.getByRole("heading", { name: "Live service" }).getBoundingClientRect(); + const [a, b] = canvas.getAllByRole("radio").map((r) => r.closest("label")!.getBoundingClientRect()); + await expect(Math.round(label.width), "140px label column").toBe(140); + await expect(Math.round(a!.top), "two services side by side").toBe(Math.round(b!.top)); + await expect(a!.left).toBeGreaterThan(label.right); + }, +}); + +/** The 320px phone column: stacked, nothing overflows. */ +export const Phone320 = meta.story({ + name: "320 · stacked", + parameters: { stageWidth: 320 }, + render: () => , + play: async ({ canvas, canvasElement }) => { + await rows(canvasElement); + const [a, b] = canvas.getAllByRole("radio").map((r) => r.closest("label")!.getBoundingClientRect()); + await expect(b!.top, "stacked at 320").toBeGreaterThan(a!.bottom - 1); + }, +}); + +/** + * The full pane: Dictation, Live service and Persona as independent siblings. + * Picking a live service touches neither neighbour. + */ +function Pane() { + const [smart, setSmart] = useState(true); + const [persona, setPersona] = useState("steward"); + return
+ +
+
+

Dictation

+
+ Clean up as I speak + setSmart((v) => !v)} /> +
+
+ +
+

Persona

+
+ {[["steward", "Ithaca steward"], ["herald", "Herald of the assembly"]].map(([id, name]) => ( + + ))} +
+
+
+
; +} + +async function independent(canvasElement: HTMLElement) { + const radio = (name: RegExp) => [...canvasElement.querySelectorAll("input[type=radio]")].find((i) => name.test(i.closest("label")?.textContent ?? ""))!; + await rows(canvasElement); + const toggle = canvasElement.querySelector("[role=switch]")!; + const before = toggle.getAttribute("aria-checked"); + await userEvent.click(radio(/GPT-Live/)); + await expect(radio(/GPT-Live/)).toBeChecked(); + await expect(radio(/Ithaca steward/), "persona untouched").toBeChecked(); + await expect(toggle.getAttribute("aria-checked"), "dictation untouched").toBe(before); +} + +export const FullPane = meta.story({ + name: "Full pane · 320", + parameters: { stageWidth: 320 }, + render: () => , + play: async ({ canvasElement }) => independent(canvasElement), +}); + +export const FullPaneDesktop = meta.story({ + name: "Full pane · desktop", + parameters: { stageWidth: "none" }, + render: () => , + play: async ({ canvasElement }) => independent(canvasElement), +}); From a54b0c9c7851302362cc2100665318bae3f22e33 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:57:03 +0000 Subject: [PATCH 03/11] =?UTF-8?q?CONTRACT:=20feat(ui-react):=20choose=20th?= =?UTF-8?q?e=20live=20service=20in=20Settings=20=E2=80=BA=20Voice=20and=20?= =?UTF-8?q?before=20Start=20(#3616)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings › Voice adds the Live service group under Dictation. Picks save brain-wide at once through a root-owned, latest-wins queue; 403 turns the group read-only, 409 reloads with "Changed on another device". The conversation client reads the hello roster and live_settings, pins the service an explicit Start agreed to for that entry, and exposes chooseService() for a one-time pick that is never saved; Start sends providerId. The disclosure sheet offers that pick when several services are usable or the saved default is unavailable, as a minimal stand-in until the Start card (#3698). Co-Authored-By: Claude Opus 5.5 --- api-report/ui-react.txt | 8 + packages/ui-react/README.md | 23 ++ .../settings/live-service-settings.tsx | 67 ++++ .../src/components/settings/voice-tab.tsx | 12 +- .../components/voice/conversation-field.tsx | 20 +- packages/ui-react/src/lib/api-client.ts | 7 + .../ui-react/src/voice/conversation-client.ts | 82 ++++- packages/ui-react/src/voice/live-service.ts | 49 +++ .../ui-react/src/voice/live-settings-save.ts | 110 ++++++ .../tests/fixtures/live-service-client.tsx | 28 ++ .../tests/live-service-runtime.test.ts | 338 ++++++++++++++++++ 11 files changed, 728 insertions(+), 16 deletions(-) create mode 100644 packages/ui-react/src/components/settings/live-service-settings.tsx create mode 100644 packages/ui-react/src/voice/live-service.ts create mode 100644 packages/ui-react/src/voice/live-settings-save.ts create mode 100644 packages/ui-react/tests/fixtures/live-service-client.tsx create mode 100644 packages/ui-react/tests/live-service-runtime.test.ts diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index e8d2e6e01d..aac7b45102 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -358,6 +358,9 @@ signatures (every public export and the types it is made of) disclosureOpen: boolean; profile: ServerConversationOpened | null; conversationProfile: ConversationProfile | null; + conversationProfiles: ConversationProfile[]; + liveDefault: LiveDefault | null; + serviceChoice: string | null; durableAvailable: boolean; sessionId: string | null; agentProviderId: string | null; @@ -1129,6 +1132,7 @@ signatures (every public export and the types it is made of) hygieneMediaUndo: (journalId: string) => Promise; hygienePreview: (request: HygienePreviewRequest, signal?: AbortSignal) => Promise; hygieneReview: () => Promise; + liveSettings: () => Promise; login: (password: string) => Promise<{ ok: true; }>; @@ -1231,6 +1235,7 @@ signatures (every public export and the types it is made of) }>; refreshModels: () => Promise; saveDictationSettings: (settings: DictationSettings) => Promise; + saveLiveSettings: (update: VoiceLiveSettingsUpdate) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1382,6 +1387,7 @@ signatures (every public export and the types it is made of) connect: () => () => void; conversation: { attachControls(): () => void; + chooseService(providerId: null | string): void; commit: (own: number) => boolean; details(): void; discard(): void; @@ -1633,6 +1639,7 @@ signatures (every public export and the types it is made of) hygieneMediaUndo: (journalId: string) => Promise; hygienePreview: (request: import("@schlessera/brain-ui-sdk").HygienePreviewRequest, signal?: AbortSignal) => Promise; hygieneReview: () => Promise; + liveSettings: () => Promise; login: (password: string) => Promise<{ ok: true; }>; @@ -1735,6 +1742,7 @@ signatures (every public export and the types it is made of) }>; refreshModels: () => Promise; saveDictationSettings: (settings: import("@schlessera/brain-ui-sdk").DictationSettings) => Promise; + saveLiveSettings: (update: import("@schlessera/brain-ui-sdk").VoiceLiveSettingsUpdate) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; diff --git a/packages/ui-react/README.md b/packages/ui-react/README.md index 004a44d537..375334ae66 100644 --- a/packages/ui-react/README.md +++ b/packages/ui-react/README.md @@ -126,6 +126,29 @@ changes keep it; a new take or a send clears it. It is announced once politely, never takes focus, and offers no automatic restart. Distinct local microphone notices remain visible afterward. +### Choosing the live-conversation service + +The Live service group of Settings › Voice, below Dictation, holds the +brain-wide default live-conversation service (#3616). It lists the services +the host registered, from the connection's `server_hello`, and reads and +writes `GET`/`PUT /api/settings/voice` against its revision; a pick saves at +once. Rows are marked "saved default", "host default" (while nothing is saved) +and "in use now"; a saved default the host no longer registers is a dashed +"saved default · not available" row that cannot be chosen. With one service the +group is a read-only row; with none it says live conversation isn't set up. +Only the owner can change it: the route refuses anyone else, and the group then +says so. A save applies from the next Start and never retargets a running +conversation; opening or saving the group opens no provider, no microphone and +reads no history. A save another device overtook says "Changed on another +device. Showing the latest." and reloads; a failed save reverts and offers +**Try again**. + +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. ### Recording on the device Set `localCapture: true` and a stable `storagePrefix` on a persistent root to diff --git a/packages/ui-react/src/components/settings/live-service-settings.tsx b/packages/ui-react/src/components/settings/live-service-settings.tsx new file mode 100644 index 0000000000..ac413e6821 --- /dev/null +++ b/packages/ui-react/src/components/settings/live-service-settings.tsx @@ -0,0 +1,67 @@ +import { useEffect } from "react"; +import { useStore } from "zustand"; +import { LiveServiceSettings, type LiveServiceOption, type LiveServiceStatus } from "@schlessera/brain-ui-kit"; +import { useBrainUiRoot, useRootStore } from "../../root-context.js"; +import { conversationService } from "../../voice/conversation-client.js"; +import { liveSettingsStore, loadLiveSettings, saveLiveDefault } from "../../voice/live-settings-save.js"; + +/** + * The Live service group of Settings › Voice (#3616): the brain-wide default + * live-conversation service, saved the moment one is picked. The registered + * services come from the connection's hello; the saved value and its + * revision from `GET /api/settings/voice`. It is independent of Dictation and + * of the ordinary model default. Opening or saving it opens no provider, no + * microphone and reads no history; a save applies from the next Start and a + * running conversation keeps its service. + */ +export function LiveServiceGroup({ active }: { active: boolean }) { + const root = useBrainUiRoot(); + const client = root.connection.conversation; + const profiles = useStore(client.state, (s) => s.conversationProfiles); + const legacy = useStore(client.state, (s) => s.liveDefault ? null : s.conversationProfile); + const liveDefault = useStore(client.state, (s) => s.liveDefault); + const inUse = useStore(client.state, (s) => s.active && s.profile ? s.profile.providerId : null); + const connected = useRootStore("connection", (s) => s.wsStatus === "connected"); + const store = liveSettingsStore(root); + const live = useStore(store); + + useEffect(() => { + // Opening Settings reads the saved value; it writes nothing. + if (active) void loadLiveSettings(root); + }, [active, root]); + // Another device saved: read the new revision, unless a pick is on its way. + const remoteSaved = liveDefault?.saved; + useEffect(() => { + if (!active || live.pending !== undefined || !live.settings || remoteSaved === undefined || remoteSaved === live.settings.defaultProvider) return; + void loadLiveSettings(root); + }, [active, root, remoteSaved, live.pending, live.settings]); + + const roster = profiles.length ? profiles : legacy ? [legacy] : []; + const services: LiveServiceOption[] = roster.map((p) => ({ id: p.providerId, name: conversationService(p.providerId), detail: p.disclosure.voiceService })); + const saved = live.pending !== undefined ? live.pending : live.settings ? live.settings.defaultProvider : liveDefault?.saved ?? null; + const usable = (id: string | null) => id !== null && services.some((s) => s.id === id); + const hostDefault = liveDefault?.source === "host" ? liveDefault.effective : null; + const checked = saved !== null ? (usable(saved) ? saved : null) : hostDefault ?? (services.length === 1 ? services[0]!.id : null); + const savedUnavailable = saved !== null && !usable(saved) ? { id: saved, name: conversationService(saved) } : null; + const status: LiveServiceStatus | null = live.status?.kind === "failed" ? { kind: "failed", text: live.status.text } : live.status; + const retry = live.status?.kind === "failed" ? live.status.retry : undefined; + + return
+ { if (live.load === "loaded") void saveLiveDefault(root, id); }} + onRetry={() => { if (retry !== undefined) void saveLiveDefault(root, retry); }} + onReload={() => void loadLiveSettings(root)} + /> +
; +} diff --git a/packages/ui-react/src/components/settings/voice-tab.tsx b/packages/ui-react/src/components/settings/voice-tab.tsx index ccc47424e4..236648ba32 100644 --- a/packages/ui-react/src/components/settings/voice-tab.tsx +++ b/packages/ui-react/src/components/settings/voice-tab.tsx @@ -1,18 +1,20 @@ import { ScreenHeader } from "@schlessera/brain-ui-kit"; import { DictationSettings } from "./dictation-settings.js"; +import { LiveServiceGroup } from "./live-service-settings.js"; /** * Settings › This brain › Voice (#3709, plan §7). The pane is a frame of - * independent groups: Dictation here, and the live-conversation service - * (#3616) beside it later. Each group owns its own route, revision and state, - * so saving one never touches the other, and nothing in the pane opens the - * microphone, mints a credential or sends audio. + * independent groups: Dictation, then the live-conversation service (#3616). + * Each group owns its own route, revision and state, so saving one never + * touches the other, and nothing in the pane opens the microphone, mints a + * credential or sends audio. */ export function VoiceTab({ active }: { active: boolean }) { return
- +
+
; } diff --git a/packages/ui-react/src/components/voice/conversation-field.tsx b/packages/ui-react/src/components/voice/conversation-field.tsx index 45fd6a22a1..e26ce0386e 100644 --- a/packages/ui-react/src/components/voice/conversation-field.tsx +++ b/packages/ui-react/src/components/voice/conversation-field.tsx @@ -4,6 +4,7 @@ import { Button, Overlay, VoiceControlButton, VoiceField, VoiceNotice, VoiceText 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"; /** 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"; @@ -124,6 +125,11 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea 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"; @@ -172,7 +178,19 @@ export function ConversationField({ backend, onLeave }: { backend: string; onLea }
-

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

+ {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.

diff --git a/packages/ui-react/src/lib/api-client.ts b/packages/ui-react/src/lib/api-client.ts index 109c0268f5..3cc84fd11c 100644 --- a/packages/ui-react/src/lib/api-client.ts +++ b/packages/ui-react/src/lib/api-client.ts @@ -19,6 +19,8 @@ import type { VoiceSessionRequest, VoiceProvidersResponse, DictationSettings, + VoiceLiveSettings, + VoiceLiveSettingsUpdate, PronunciationOverride, ProviderInfo, UnavailableProfileInfo, @@ -517,6 +519,11 @@ export function createBrainApi( fetchJson("/voice/dictation/settings", { method: "PUT", headers: { "If-Match": `"${settings.revision}"` }, body: JSON.stringify({ defaultProvider: settings.defaultProvider, smart: settings.smart }) }), + /** The saved default live-conversation service and its revision (#3616). Never opens a provider. */ + liveSettings: () => fetchJson("/settings/voice", { cache: "no-store" }), + saveLiveSettings: (update: VoiceLiveSettingsUpdate) => + fetchJson("/settings/voice", { method: "PUT", body: JSON.stringify({ defaultProvider: update.defaultProvider, revision: update.revision }) }), + /** @deprecated use voiceSession(); kept during client transition. */ voiceToken: () => fetchJson("/voice/token", { method: "POST" }), diff --git a/packages/ui-react/src/voice/conversation-client.ts b/packages/ui-react/src/voice/conversation-client.ts index 309d658d44..911f7f4964 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, ServerConversationClosed, ConversationWireEvent, ConversationWorkReceipt, ConversationOutputRecord, DialoguePage, DialogueRecord } from "@schlessera/brain-ui-sdk/protocol"; +import type { ClientMessage, ServerMessage, ServerConversationOpened, ConversationProfile, LiveDefault, 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"; @@ -69,7 +69,18 @@ export interface ConversationClientState { interaction: "Listening" | "Sending soon" | "Review before sending" | "Working" | "Speaking" | "Checking whether the reply stopped" | "Answering question"; disclosureOpen: boolean; profile: ServerConversationOpened | null; + /** + * What explicit Start discloses and opens: the service this entry started + * with while it runs, else the one-time pick, else the effective service + * (#3616). Null when a pick is required or the host has none. + */ conversationProfile: ConversationProfile | null; + /** Every registered live service (#3616); empty on a host that predates the roster. */ + conversationProfiles: ConversationProfile[]; + /** How a new Start resolves its service (#3616); null on a host that predates it. */ + liveDefault: LiveDefault | null; + /** The one-time pick for this entry's Start (#3616 L1/L2). Never saved. */ + serviceChoice: string | null; durableAvailable: boolean; sessionId: string | null; agentProviderId: string | null; @@ -117,7 +128,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, 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, 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(); @@ -159,6 +170,22 @@ export function createConversationClient(root: BrainUiServices, send: (message: let inputLevel = 0; let agreedDisclosure: string | undefined; let agreedEntry: number | undefined; + // The legacy hello profile, for a host without a service roster (#3616). + let advertisedProfile: ConversationProfile | null = null; + // The service an explicit Start agreed to; it holds until Leave, so a saved + // default changed meanwhile never retargets this entry or its reconnects. + let startedService: string | null = null; + function liveProfile(): ConversationProfile | null { + const s = state.getState(); + if (!s.conversationProfiles.length || !s.liveDefault) return advertisedProfile; + const id = (s.active ? startedService : null) ?? (s.active ? s.serviceChoice : null) ?? s.liveDefault.effective; + return s.conversationProfiles.find((p) => p.providerId === id) ?? null; + } + function applyLiveProfile() { + const profile = liveProfile(); + if (profile !== state.getState().conversationProfile) state.setState({ conversationProfile: profile }); + return profile; + } let draftId: string | null = null; let draftOrigin: string | null = null; let savedVoice = ""; @@ -469,7 +496,9 @@ export function createConversationClient(root: BrainUiServices, send: (message: entryLifetime++; agreedEntry = undefined; agreedDisclosure = undefined; pause(false, false); fragments.clear(); lastInput = undefined; utterance = null; - state.setState(s => ({ active: false, text: "", disclosureOpen: false, recognition: s.recognition.filter(f => f.unsaved || f.finalization !== "interim") })); + startedService = null; + state.setState(s => ({ active: false, serviceChoice: 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) { const key = `dialogue:${retainedOwner}`; @@ -496,7 +525,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: sequence = 0; utterance = null; ended = false; clearTimers(); resetRecovery(); const s = state.getState(); openingId = crypto.randomUUID(); openingEntry = entryLifetime; - send({ type: "conversation_start", disclosed: advertised, contextualTasks: true, requestId: openingId, ...((!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 } : {}) }); + send({ type: "conversation_start", disclosed: advertised, ...(s.conversationProfiles.length ? { providerId: advertised.providerId } : {}), contextualTasks: true, requestId: openingId, ...((!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(); @@ -638,7 +667,8 @@ export function createConversationClient(root: BrainUiServices, send: (message: permissions.clear(); localTones.clear(); fragments.clear(); capturedInputs.clear(); retiredInputs.clear(); manualReview.clear(); incompleteReview.clear(); unassignedThrough=-1; seenRecognition.clear(); lastInput=undefined; utterance=null; draftId=null; draftOrigin=null; savedVoice=""; - state.setState({active:false,token:generation,profile:null,conversationProfile:null,voiceDraft:null,dialogue:{},dialogueRestoredThrough:{},dialogueNotice:"",work:{},outputs:[],unassigned:[],recognition:[],unassignedWork:0,available:false}); + advertisedProfile=null; startedService=null; + state.setState({active:false,token:generation,profile:null,conversationProfile:null,conversationProfiles:[],liveDefault:null,serviceChoice:null,voiceDraft:null,dialogue:{},dialogueRestoredThrough:{},dialogueNotice:"",work:{},outputs:[],unassigned:[],recognition:[],unassignedWork:0,available:false}); if (root.stores.voice.getState().mode === "conversation") root.stores.voice.getState().setMode("idle"); } let inputFormat: Extract["input"] | undefined; @@ -738,12 +768,25 @@ export function createConversationClient(root: BrainUiServices, send: (message: } if (!unsavedOverflow) state.setState({dialogueNotice: dialogueDiagnostic(message.code)}); return null; } + if (message.type === "live_settings") { + // A saved default changed (#3616). The next Start uses it; a running + // entry keeps the service it started with. + state.setState({ conversationProfiles: message.conversationProfiles, liveDefault: message.liveDefault }); + applyLiveProfile(); + return null; + } if (message.type === "server_hello") { - const profile = message.conversationProfile ?? null; - state.setState({ conversationProfile: profile, available: !!profile && message.capabilities?.liveConversation === true && message.capabilities?.conversationPause === true }); + advertisedProfile = message.conversationProfile ?? null; + const roster = message.conversationProfiles && message.liveDefault ? message.conversationProfiles : []; + const live = message.capabilities?.liveConversation === true && message.capabilities?.conversationPause === true; + state.setState({ conversationProfiles: roster, liveDefault: roster.length ? message.liveDefault! : null }); + const profile = liveProfile(); + // With a roster, a host whose Start needs a pick is still available: the pick comes first. + state.setState({ conversationProfile: profile, available: live && (!!profile || roster.length > 0) }); if (state.getState().active) { if (profile && !requireCurrentDisclosure()) startEpoch(); - else if (!profile) { agreedEntry=undefined; entryLifetime++; pause(false,true); state.setState({disclosureOpen:true,notice:"Voice is unavailable until this host supplies its disclosure."}); } + // A pick still to be made before Start is not a missing disclosure (#3616). + else if (!profile && (startedService !== null || !roster.length)) { agreedEntry=undefined; entryLifetime++; pause(false,true); state.setState({disclosureOpen:true,notice:"Voice is unavailable until this host supplies its disclosure."}); } } } if (message.type === "session_info" && message.requestId) { @@ -984,7 +1027,7 @@ export function createConversationClient(root: BrainUiServices, send: (message: }); const unwatchProvider = root.stores.provider.subscribe(() => { requireCurrentDisclosure(); }); const unwatchConnection = root.stores.connection.subscribe((next, previous) => { - if(next.wsStatus !== previous.wsStatus && next.wsStatus !== "connected") {dialogueReads.clear(); state.setState({conversationProfile:null,available:false});} + if(next.wsStatus !== previous.wsStatus && next.wsStatus !== "connected") {dialogueReads.clear(); advertisedProfile=null; state.setState({conversationProfile:null,conversationProfiles:[],liveDefault:null,available:false});} if (!state.getState().active || next.wsStatus === previous.wsStatus) return; if (next.wsStatus !== "connected") suspend(); else { state.setState({ connection: "Reconnecting" }); startEpoch(); announce(consent ? "Reconnected. Restoring listening." : "Reconnected. Microphone off."); } @@ -1031,19 +1074,38 @@ export function createConversationClient(root: BrainUiServices, send: (message: const agentProviderId = providers.available.some((provider) => provider.id === providers.selectedId) ? providers.selectedId : null; entryLifetime++; entryProfileId = providers.pinnedId ?? agentProviderId; + startedService = null; + state.setState({ serviceChoice: 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; + applyLiveProfile(); root.stores.voice.getState().setMode("conversation"); agreedEntry = undefined; setConsent(false, "idle"); permissions.refresh(); }, start() { - const profile = state.getState().conversationProfile; + const profile = applyLiveProfile(); if (!state.getState().active || !profile || (typeof document !== "undefined" && document.hidden) || root.stores.connection.getState().wsStatus !== "connected") return; + // The service is fixed for this entry from here, whatever is saved later. + if (state.getState().conversationProfiles.length) startedService = profile.providerId; agreedDisclosure = disclosureKey(profile); agreedEntry = entryLifetime; setConsent(true); state.setState({ disclosureOpen: false }); startEpoch(); void capture(); }, details() { state.setState({ disclosureOpen: true }); }, + /** + * The one-time service pick before Start (#3616 L1/L2): Change when + * several services are usable, or the explicit pick a missing default + * requires. It applies to this entry's Start only and is never saved; + * `null` returns to the effective service. Ignored once Start was agreed, + * and for an id the host does not register. + */ + chooseService(providerId: string | null) { + const s = state.getState(); + if (!s.active || startedService !== null || agreedEntry === entryLifetime) return; + if (providerId !== null && !s.conversationProfiles.some((p) => p.providerId === providerId)) return; + state.setState({ serviceChoice: providerId }); + applyLiveProfile(); + }, 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/src/voice/live-service.ts b/packages/ui-react/src/voice/live-service.ts new file mode 100644 index 0000000000..719468627c --- /dev/null +++ b/packages/ui-react/src/voice/live-service.ts @@ -0,0 +1,49 @@ +// What a Start can use for its live-conversation service (#3616), derived +// from the conversation client's state. The Start card (#3698) draws its +// Service row, Change and the S3d pick from this; Settings › Voice draws the +// Live service group from the same roster. Nothing here opens a provider. + +import type { ConversationProfile, LiveDefault, LiveProviderSource } from "@schlessera/brain-ui-sdk/protocol"; +import type { ConversationClientState } from "./conversation-client.js"; + +interface LiveServiceView { + /** Every usable (registered) service, in the host's order. Empty: live conversation isn't set up. */ + services: ConversationProfile[]; + /** The service explicit Start would disclose and open now; null when a pick is required. */ + selected: ConversationProfile | null; + /** + * Why `selected` is the one: `change` for this entry's one-time pick, else + * the host's resolution. `legacy` for a host that sends no roster. + */ + source: LiveProviderSource | "legacy"; + /** A saved default the host no longer registers (S3d); it stays saved until changed in Settings. */ + savedUnavailable: string | null; + /** Start needs an explicit pick from `services` first (S3d, or several with no default). */ + pickRequired: boolean; + /** Show Change: two or more usable services (L1). */ + canChange: boolean; + /** The host's resolution, unchanged, for presentation; null on a legacy host. */ + liveDefault: LiveDefault | null; +} + +type Source = Pick; + +export function liveServiceView(s: Source): LiveServiceView { + if (!s.liveDefault || s.conversationProfiles.length === 0) { + return { services: s.conversationProfile ? [s.conversationProfile] : [], selected: s.conversationProfile, source: "legacy", + savedUnavailable: null, pickRequired: false, canChange: false, liveDefault: null }; + } + const services = s.conversationProfiles; + const choice = s.serviceChoice !== null ? services.find((p) => p.providerId === s.serviceChoice) ?? null : null; + const selected = s.conversationProfile; + const savedUnavailable = s.liveDefault.saved !== null && !s.liveDefault.savedUsable ? s.liveDefault.saved : null; + return { + services, + selected, + source: choice && selected?.providerId === choice.providerId ? "change" : s.liveDefault.source, + savedUnavailable, + pickRequired: selected === null, + canChange: services.length >= 2, + liveDefault: s.liveDefault, + }; +} diff --git a/packages/ui-react/src/voice/live-settings-save.ts b/packages/ui-react/src/voice/live-settings-save.ts new file mode 100644 index 0000000000..90e5f16c41 --- /dev/null +++ b/packages/ui-react/src/voice/live-settings-save.ts @@ -0,0 +1,110 @@ +// The saved brain-wide live-conversation default (#3616), read and written +// for Settings › Voice. The state belongs to the root, not to the pane: a pick +// the pane accepted is written even if the pane closes meanwhile. Writes are +// latest-wins and one at a time, each against the newest revision the root +// knows. Nothing here opens a provider, a microphone or reads history; a save +// changes only the next explicit Start. + +import { createStore, type StoreApi } from "zustand/vanilla"; +import type { VoiceLiveSettings } from "@schlessera/brain-ui-sdk/protocol"; +import { ApiRequestError } from "../lib/api-client.js"; +import type { BrainUiRoot } from "../root.js"; + +type LiveSettingsStatus = { kind: "saving" } | { kind: "stale" } | { kind: "failed"; text: string; retry: string | null }; + +interface LiveSettingsState { + settings: VoiceLiveSettings | null; + /** `forbidden`: this principal is not the owner (the server's answer). */ + load: "idle" | "loading" | "loaded" | "forbidden" | "failed"; + /** The pick on its way; `undefined` when none is. */ + pending: string | null | undefined; + status: LiveSettingsStatus | null; +} + +interface Queue { desired: string | null | undefined; running: Promise | null; epoch: number } +const stores = new WeakMap; queue: Queue }>(); + +function entry(root: BrainUiRoot) { + let found = stores.get(root.stores); + if (!found) { + found = { store: createStore(() => ({ settings: null, load: "idle", pending: undefined, status: null })), queue: { desired: undefined, running: null, epoch: root.authLock.epoch() } }; + stores.set(root.stores, found); + } + // A new auth generation ends what the last one read or queued. + if (found.queue.epoch !== root.authLock.epoch()) { + found.queue = { desired: undefined, running: null, epoch: root.authLock.epoch() }; + found.store.setState({ settings: null, load: "idle", pending: undefined, status: null }); + } + return found; +} + +export function liveSettingsStore(root: BrainUiRoot): StoreApi { + return entry(root).store; +} + +/** Read the saved default. A 403 means this principal may neither read nor write it. */ +export async function loadLiveSettings(root: BrainUiRoot): Promise { + const { store, queue } = entry(root); + if (!store.getState().settings) store.setState({ load: "loading" }); + try { + const settings = await root.api.liveSettings(); + if (queue !== entry(root).queue) return; + store.setState({ settings, load: "loaded" }); + } catch (error) { + if (queue !== entry(root).queue) return; + store.setState({ load: error instanceof ApiRequestError && error.status === 403 ? "forbidden" : "failed" }); + } +} + +/** Accept a pick (`null` clears the default). It is written for the root's life while the auth generation holds. */ +export function saveLiveDefault(root: BrainUiRoot, defaultProvider: string | null): Promise { + const { store, queue } = entry(root); + queue.desired = defaultProvider; + store.setState({ pending: defaultProvider, status: { kind: "saving" } }); + return queue.running ??= drain(root, queue).finally(() => { queue.running = null; }); +} + +async function drain(root: BrainUiRoot, queue: Queue): Promise { + const { store } = entry(root); + const over = () => queue !== entry(root).queue; + while (!over() && queue.desired !== undefined) { + const want = queue.desired; + const base = store.getState().settings; + if (!base) { + queue.desired = undefined; + store.setState({ pending: undefined, status: { kind: "failed", text: "Couldn't save. Your live service is unchanged.", retry: want } }); + return; + } + try { + const saved = await root.api.saveLiveSettings({ defaultProvider: want, revision: base.revision }); + if (over()) return; + store.setState({ settings: saved }); + if (queue.desired === want) queue.desired = undefined; + } catch (error) { + if (over()) return; + const status = error instanceof ApiRequestError ? error.status : 0; + const code = error instanceof Error ? error.message : ""; + if (status === 403) { + // The server is the authority: nothing queued can land. + queue.desired = undefined; + store.setState({ pending: undefined, status: null, load: "forbidden" }); + return; + } + if (status === 409) { + // Changed on another device: a pick made against the old value is dropped with it. + queue.desired = undefined; + store.setState({ pending: undefined, status: { kind: "stale" } }); + await loadLiveSettings(root); + return; + } + // A newer pick made meanwhile supersedes the one that failed. + if (queue.desired !== want) continue; + queue.desired = undefined; + const unknown = code === "LIVE_PROVIDER_UNKNOWN"; + store.setState({ pending: undefined, status: { kind: "failed", text: unknown ? "That live service isn't available on this host." : "Couldn't save. Your live service is unchanged.", retry: want } }); + if (unknown) await loadLiveSettings(root); + return; + } + } + if (!over()) store.setState({ pending: undefined, status: null }); +} diff --git a/packages/ui-react/tests/fixtures/live-service-client.tsx b/packages/ui-react/tests/fixtures/live-service-client.tsx new file mode 100644 index 0000000000..ddb6e46fec --- /dev/null +++ b/packages/ui-react/tests/fixtures/live-service-client.tsx @@ -0,0 +1,28 @@ +// #3616: the real chat page, its live-conversation disclosure and Settings › +// Voice, against a real server with two keyless live-service doubles. The +// server, not this page, records which double a Start opened. +import { createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { BrainUiProvider, ChatPage, createBrainUiRoot } from "@schlessera/brain-ui-react"; + +const root = createBrainUiRoot({ storagePrefix: "odysseus-live-service", storage: localStorage }); +const renderer = createRoot(document.getElementById("app")!); +renderer.render(createElement(BrainUiProvider, { root, children: createElement(ChatPage) })); +const conversation = root.connection.conversation; +Object.assign(window, { + __live: { + ready: () => root.stores.connection.getState().wsStatus === "connected" && conversation.state.getState().available, + connected: () => root.stores.connection.getState().wsStatus === "connected", + openSettings: () => root.stores.ui.getState().openSettings("voice"), + closeSettings: () => root.stores.ui.getState().setSettingsPanelOpen(false), + enter: () => conversation.enter(), + leave: () => conversation.leave(), + state: () => { + const s = conversation.state.getState(); + return { active: s.active, available: s.available, disclosureOpen: s.disclosureOpen, disclosed: s.conversationProfile?.providerId ?? null, + opened: s.profile?.providerId ?? null, source: s.profile?.providerSource ?? null, choice: s.serviceChoice, liveDefault: s.liveDefault, + services: s.conversationProfiles.map((p) => p.providerId) }; + }, + }, +}); +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 new file mode 100644 index 0000000000..34b26fe5a4 --- /dev/null +++ b/packages/ui-react/tests/live-service-runtime.test.ts @@ -0,0 +1,338 @@ +import { runtimePackageBuild } from "./fixtures/runtime-package-build"; +// #3616: choosing the default live-conversation service in Settings › Voice, +// and which service the next explicit Start opens, in real Chrome against a +// real password-mode server. Two keyless live-service doubles stand in for +// Gemini Live and GPT-Live, registered through `createApp({ +// conversationProviders })`; the server records every `open`, so it, not the +// page, says where a Start went. The app restarts over the same database to +// prove persistence and to remove a service. Every state is checked 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("Live service runtime proof requires real Chrome"); +if (!executablePath) console.warn("SKIPPING live service runtime proof: no Chrome; Settings › Voice and Start binding are unverified locally."); + +const repo = resolve(import.meta.dir, "../../.."); +const SECRET = "live-service-runtime-secret-0123456789"; +const WIDTHS = [320, 1280] as const; +const SHOTS = process.env.BRAIN_LIVE_SERVICE_SCREENSHOTS; +const hook = runtimeHookPhases("live-service-runtime"); + +type Id = "gemini-live" | "gpt-live"; +/** 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, 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 }); + +let fixture = "", brain = "", assets = "", origin = "", port = 0; +let app: Awaited> | undefined; +let server: ReturnType | undefined; +let browser: Browser | undefined; +const cookies = { owner: "", reader: "" }; +/** Every `/api/settings/voice` request, in order. */ +const log: Array<{ method: string; status: number }> = []; + +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: "live-fixture" })], "live-fixture"), + staticRoot: assets, observability: createRecordingObservability(), + conversationProviders: ids.map(double), + ...(hostDefault ? { defaultConversationProviderId: hostDefault } : {}), + })); + const current = app; + const handle = async (request: Request, bun: unknown) => { + const response = await current.fetch(request, bun as never); + const url = new URL(request.url); + if (url.pathname === "/api/settings/voice") log.push({ method: request.method, status: response?.status ?? 0 }); + 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-live-service-")); + 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/live-service-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(`Live service client build failed (${code}): ${out}\n${err}`); + await writeFile(resolve(assets, "index.html"), 'Odysseus live service
'); + 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 owner = createPrincipal(app!.db, { authMethod: "password", label: "Penelope's phone", ttlSeconds: 3600 }); + const reader = createPrincipal(app!.db, { authMethod: "delegated", createdBy: owner.id, label: "Telemachus agent", ttlSeconds: 3600 }); + for (const [who, principal] of [["owner", owner], ["reader", reader]] as const) { + const signed = await generateSignedCookie("brain_ui_session", principal.id, SECRET); + cookies[who] = signed.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 saved default as the owner's other device sets it, through the real route. */ +async function otherDevice(defaultProvider: string | null) { + const headers = { cookie: `brain_ui_session=${cookies.owner}`, origin, "content-type": "application/json" }; + const current = await (await fetch(`${origin}/api/settings/voice`, { headers })).json() as { defaultProvider: string | null; revision: number }; + if (current.defaultProvider === defaultProvider) return current; + const response = await fetch(`${origin}/api/settings/voice`, { method: "PUT", headers, body: JSON.stringify({ defaultProvider, revision: current.revision }) }); + expect(response.status, "the other device saved").toBe(200); + return await response.json() as { defaultProvider: string | null; revision: number }; +} +const saved = async () => (await (await fetch(`${origin}/api/settings/voice`, { headers: { cookie: `brain_ui_session=${cookies.owner}` } })).json() as { defaultProvider: string | null }).defaultProvider; + +const contexts: BrowserContext[] = []; +async function open(width: number, who: "owner" | "reader" = "owner"): Promise { + const context = await browser!.newContext({ viewport: { width, height: width < 900 ? 720 : 860 }, hasTouch: width < 900 }); + contexts.push(context); + await context.addCookies([{ name: "brain_ui_session", value: cookies[who], 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 the page makes, from its first script on. + await context.addInitScript(() => { + const scope = window as unknown as { __gum: number }; + scope.__gum = 0; + const media = navigator.mediaDevices; + const original = media.getUserMedia.bind(media); + media.getUserMedia = (constraints) => { scope.__gum++; return original(constraints); }; + }); + const page = await context.newPage(); + await page.goto(origin); + await page.waitForFunction("window.__live?.connected()"); + return page; +} +async function closeAll() { for (const context of contexts.splice(0)) await context.close(); } + +type LiveState = { active: boolean; available: boolean; disclosureOpen: boolean; disclosed: string | null; opened: string | null; source: string | null; choice: string | null; services: string[]; + liveDefault: { saved: string | null; savedUsable: boolean; effective: string | null; source: string } | null }; +const live = (page: Page) => page.evaluate(() => (window as unknown as { __live: { state(): LiveState } }).__live.state()); +const gum = (page: Page) => page.evaluate(() => (window as unknown as { __gum: number }).__gum); +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`) }); +} +/** No horizontal page scroll, and every row in the selector at least 44px tall. */ +async function fits(page: Page, width: number, selector: string) { + expect(await page.evaluate(() => document.documentElement.scrollWidth), `no horizontal scroll at ${width}px`).toBeLessThanOrEqual(width); + const heights = await page.locator(selector).evaluateAll((nodes) => nodes.map((node) => Math.round(node.getBoundingClientRect().height))); + expect(heights.length, `${selector} rows at ${width}px`).toBeGreaterThan(0); + for (const height of heights) expect(height, `${selector} target at ${width}px`).toBeGreaterThanOrEqual(44); +} +/** Opens Settings › Voice and waits until the Live service group has read the saved value. */ +async function settings(page: Page) { + const before = log.filter((entry) => entry.method === "GET").length; + await page.evaluate(() => (window as unknown as { __live: { openSettings(): void } }).__live.openSettings()); + const group = page.locator("[data-live-service-settings]"); + await group.waitFor(); + for (let waited = 0; log.filter((entry) => entry.method === "GET").length <= before; waited += 10) { if (waited > 10_000) throw new Error("Settings never read the live default"); await Bun.sleep(10); } + await page.waitForFunction(() => !document.querySelector("[data-live-service-settings]")?.getAttribute("aria-busy")); + return group; +} +async function closeSettings(page: Page) { + await page.evaluate(() => (window as unknown as { __live: { closeSettings(): void } }).__live.closeSettings()); +} +/** Pick a radio and wait until the server answered the save and the pane shows no pending save. */ +async function pick(page: Page, name: RegExp) { + const before = log.filter((entry) => entry.method === "PUT").length; + await page.locator("[data-live-service-settings]").getByRole("radio", { name }).check(); + 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. */ +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"]'); +} +async function startAndWait(page: Page) { + await page.getByRole("button", { name: "Start", exact: true }).click(); + await page.waitForFunction(() => (window as unknown as { __live: { state(): LiveState } }).__live.state().opened !== null); +} +async function leave(page: Page) { + await page.evaluate(() => (window as unknown as { __live: { leave(): void } }).__live.leave()); + await page.waitForFunction(() => !(window as unknown as { __live: { state(): LiveState } }).__live.state().active); +} + +describe.skipIf(!executablePath)("Settings › Voice live service and the next Start, against mounted routes", () => { + for (const width of WIDTHS) test(`${width}px: pick, reload, restart; Settings opens no microphone or provider`, async () => { + await restart(["gemini-live", "gpt-live"]); + await otherDevice(null); + const before = counts(); + let page = await open(width); + const group = await settings(page); + // Several services, nothing saved, no host default: nothing checked. + expect(await group.locator("[data-live-service-pick]").textContent()).toBe("Pick a default"); + expect(await group.getByRole("radio", { checked: true }).count(), "nothing is checked").toBe(0); + expect(await group.getByRole("radiogroup", { name: "Live service" }).count()).toBe(1); + await fits(page, width, "[data-live-service-option]"); + await shot(page, `live-pick-${width}`); + if (width >= 900) { + // Desktop: exactly two services side by side, the label in its column. + const [a, b] = await group.locator("[data-live-service-option]").evaluateAll((rows) => rows.map((row) => row.getBoundingClientRect().top)); + expect(Math.round(a!), "two services side by side").toBe(Math.round(b!)); + } + + await pick(page, /GPT-Live/); + expect(await saved(), "the pick was saved brain-wide").toBe("gpt-live"); + expect(await group.getByText("saved default").count()).toBe(1); + // Keyboard: the arrow moves the choice and saves it. + await group.getByRole("radio", { name: /GPT-Live/ }).focus(); + const puts = log.filter((entry) => entry.method === "PUT").length; + await page.keyboard.press(width >= 900 ? "ArrowLeft" : "ArrowUp"); + for (let waited = 0; log.filter((entry) => entry.method === "PUT").length <= puts; waited += 10) { if (waited > 10_000) throw new Error("Arrow key did not save"); await Bun.sleep(10); } + await page.waitForFunction(() => !document.querySelector("[data-live-service-settings] [role=status]")?.textContent?.includes("Saving")); + expect(await saved()).toBe("gemini-live"); + await pick(page, /GPT-Live/); + + // Reload: the saved default is still checked. + await page.reload(); + await page.waitForFunction("window.__live?.connected()"); + let again = await settings(page); + expect(await again.getByRole("radio", { name: /GPT-Live/ }).isChecked(), "LIVE_DEFAULT_RELOAD_PERSISTS").toBe(true); + // Restart over the same database: still saved. + await restart(["gemini-live", "gpt-live"]); + page = await open(width); + again = await settings(page); + expect(await again.getByRole("radio", { name: /GPT-Live/ }).isChecked(), "LIVE_DEFAULT_RESTART_PERSISTS").toBe(true); + expect(await gum(page), "SETTINGS_OPENS_NO_MICROPHONE").toBe(0); + expect(counts(), "SETTINGS_OPENS_NO_PROVIDER").toEqual(before); + await closeSettings(page); + }, 120_000); + + for (const width of WIDTHS) test(`${width}px: the next Start opens the saved default; Change applies once and is not saved`, async () => { + await restart(["gemini-live", "gpt-live"]); + await otherDevice("gpt-live"); + const page = await open(width); + const before = counts(); + let sheet = await enter(page); + // The disclosure names the saved default before any Start. + 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 shot(page, `live-sheet-${width}`); + await startAndWait(page); + expect(counts(), "SAVED_DEFAULT_OPENS").toEqual({ gemini: before.gemini, gpt: before.gpt + 1 }); + expect((await live(page)).source).toBe("saved"); + + // A save from another device does not retarget the running conversation. + await otherDevice("gemini-live"); + await page.waitForFunction(() => (window as unknown as { __live: { state(): LiveState } }).__live.state().liveDefault?.saved === "gemini-live"); + const running = await live(page); + expect(running.opened, "RUNNING_KEEPS_SERVICE").toBe("gpt-live"); + expect(running.disclosed).toBe("gpt-live"); + expect(opened["gpt-live"].at(-1)!.closed).toBe(false); + expect(counts()).toEqual({ gemini: before.gemini, gpt: before.gpt + 1 }); + await leave(page); + + // 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(); + 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); + expect(counts(), "CHANGE_OPENS_PICK").toEqual({ gemini: before.gemini, gpt: before.gpt + 2 }); + expect((await live(page)).source).toBe("change"); + expect(await saved(), "CHANGE_IS_NOT_SAVED").toBe("gemini-live"); + await leave(page); + + // The pick ended with that entry: the next Start is the saved default again. + sheet = await enter(page); + expect((await live(page)).disclosed).toBe("gemini-live"); + await startAndWait(page); + expect(counts()).toEqual({ gemini: before.gemini + 1, gpt: before.gpt + 2 }); + await leave(page); + }, 120_000); + + for (const width of WIDTHS) test(`${width}px: an unavailable saved default needs an explicit pick and is kept`, async () => { + await restart(["gemini-live", "gpt-live"]); + await otherDevice("gpt-live"); + await restart(["gemini-live"], "gemini-live"); + const page = await open(width); + const group = await settings(page); + const dashed = group.locator("[data-live-service-unavailable]"); + expect(await dashed.textContent()).toContain("saved default · not available"); + expect(await group.getByRole("radio", { name: /GPT-Live/ }).count(), "the unavailable default cannot be chosen").toBe(0); + expect(await group.getByRole("radio", { name: /Gemini Live/ }).isChecked(), "the host default is not substituted").toBe(false); + await fits(page, width, "[data-live-service-settings] .bk-live-service-row"); + await shot(page, `live-unavailable-${width}`); + await closeSettings(page); + + 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(counts(), "S3D_NO_SUBSTITUTE").toEqual(before); + await shot(page, `live-s3d-${width}`); + await sheet.getByRole("radio", { name: "Gemini Live" }).check(); + 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"); + await leave(page); + }, 120_000); + + for (const width of WIDTHS) test(`${width}px: a non-owner sees the default read-only and cannot write it`, async () => { + await restart(["gemini-live", "gpt-live"], "gemini-live"); + await otherDevice(null); + const page = await open(width, "reader"); + const group = page.locator("[data-live-service-settings]"); + await page.evaluate(() => (window as unknown as { __live: { openSettings(): void } }).__live.openSettings()); + await group.locator("[data-live-service-owner]").waitFor(); + expect(await group.getByRole("radio", { name: /Gemini Live/ }).isChecked(), "the host default is shown").toBe(true); + for (const radio of await group.getByRole("radio").all()) expect(await radio.isDisabled()).toBe(true); + const refused = await page.evaluate(async () => (await fetch("/api/settings/voice", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ defaultProvider: "gpt-live", revision: 0 }) })).status); + expect(refused, "LIVE_SETTINGS_OWNER_ONLY").toBe(403); + expect(await saved()).toBe(null); + }, 120_000); +}); From c63641164b9ba373ba6b4a36e86c072bd7cf938c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:57:03 +0000 Subject: [PATCH 04/11] docs: document the live-service default, its precedence and activation (#3616) Co-Authored-By: Claude Opus 5.5 --- .changeset/3616-live-service-default.md | 13 ++++++ docs/decisions/live-conversation.md | 29 ++++++++++++ docs/extending/README.md | 2 +- docs/extending/speech.md | 37 +++++++++++++++ docs/integration-contract.md | 23 ++++++++++ docs/integration-contract/http.md | 16 +++++++ docs/integration-contract/package-api.md | 28 ++++++++++++ docs/integration-contract/wire.md | 58 +++++++++++++++++++++++- docs/live-conversation-guidance.md | 2 +- 9 files changed, 204 insertions(+), 4 deletions(-) create mode 100644 .changeset/3616-live-service-default.md diff --git a/.changeset/3616-live-service-default.md b/.changeset/3616-live-service-default.md new file mode 100644 index 0000000000..b0b4125dcf --- /dev/null +++ b/.changeset/3616-live-service-default.md @@ -0,0 +1,13 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +"@schlessera/brain-ui-kit": minor +--- + +Choose the default live-conversation service in Settings › Voice (#3616). + +- **Server.** `createApp` accepts `conversationProviders` (several live services) and `defaultConversationProviderId`; `conversationProvider` still means a list of one. Startup fails on both options, duplicate ids or a default that is not registered. `GET`/`PUT /api/settings/voice` read and save the brain-wide default against its revision. Writing has its own owner-only guard: the owner's password or passkey session or the ambient human; anyone else gets 403 with an empty body. Unknown ids are 400 `LIVE_PROVIDER_UNKNOWN`, stale revisions 409 `LIVE_SETTINGS_CHANGED`. +- **Wire.** `server_hello` adds `conversationProfiles` and `liveDefault`, and sends `conversationProfile` only while a service is effective, so a single-provider host is unchanged. A save sends `live_settings` to open connections. `conversation_start` accepts `providerId`, which must equal the disclosed profile's; `conversation_opened` adds `providerSource`. +- **Selection.** A Start uses a one-time pick, else the saved default if it is still registered, else the host default or the only service when nothing is saved. A saved default that is no longer registered requires an explicit pick and is never replaced by the host default. A save applies from the next explicit Start; a running conversation and its reconnects keep their service. Nothing probes a credential, and saving opens no provider, microphone or history. +- **App.** Settings › Voice gains the Live service group (kit `LiveServiceSettings`), and the pre-Start disclosure sheet offers the one-time pick when several services are usable or the saved default is unavailable. diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 4cdebecd99..24ee7e5c3a 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -572,3 +572,32 @@ it neither authenticates typed dialogue nor blocks the rest of the chat. Native assistant text remains historical assistant data. Missing or evicted contextual receipts cannot classify a user. Actual source read errors and contradictory positive source/retained receipt identities refuse startup before provider open. + +## Choosing the service in Settings — 2026-11-08 (#3616) + +A host may register both adapters, so the brain's owner chooses the default +live service in Settings › Voice instead of at host registration. The +maintainer's rulings on #3616 bind it: + +- **L1.** The Start screen offers a one-time **Change** when two or more + services are usable. It applies to that conversation only and is never saved. +- **L2.** A saved default the host no longer registers requires an explicit + pick at Start. The host default is never substituted, even with a notice; + the saved value stays until it is changed in Settings. +- **L3.** The shared pane is named **Voice**; the live service is a group + beside Dictation, with its own route and revision. +- **R1.** A client that reads only `conversationProfile` sees live conversation + as unavailable on a multi-service host with nothing effective. There is no + deterministic legacy fallback, which would contradict L2. + +The default is brain-wide and server-side, and it takes effect at the next +explicit Start. A save never retargets a running conversation, and a reconnect +keeps the service the conversation opened with: the destination a user agreed +to is the one their audio and history reach. "Usable" means registered at boot, +with no credential probing, so discovery never costs a provider call and a key +that fails later is an ordinary provider error that selects nothing else. +Writing has its own owner-only guard rather than inheriting the Models route's: +the owner's human session or the ambient human, never a delegated principal. +The [wire](../integration-contract/wire.md#live-service-selection-additive-3616) +and [HTTP](../http-api.md#live-conversation-service-default) contracts give +the exact shapes. diff --git a/docs/extending/README.md b/docs/extending/README.md index 76953db2c1..8925b51991 100644 --- a/docs/extending/README.md +++ b/docs/extending/README.md @@ -144,7 +144,7 @@ The first six live in core. The self-hosted chat UI adds six in session per conversation epoch and reports normalized, evidence-qualified events. The host commits input, runs work through the ordinary backend and permission bridge, and returns bounded results; the provider never executes - tools or settles permissions. Pass one to `createApp({ conversationProvider })`. + tools or settles permissions. Pass one to `createApp({ conversationProvider })`, or several to `createApp({ conversationProviders, defaultConversationProviderId })` (#3616). Contract: `packages/ui-sdk/src/server/conversation.ts`. - **`ToolRenderer`** (client) — per-tool rendering for the chat timeline (icon, summary, input/output React components), registered at build time in diff --git a/docs/extending/speech.md b/docs/extending/speech.md index 93ad248f0f..ae8a138920 100644 --- a/docs/extending/speech.md +++ b/docs/extending/speech.md @@ -379,6 +379,43 @@ promise zero retention. The [conversation contract](../integration-contract/wire.md#live-conversation-additive-957) describes the guarded correlation, bounded result appends and close receipts. +## Registering both live services + +A host may register both adapters and let the brain's owner choose between +them in Settings › Voice (#3616). `conversationProviders` replaces the single +`conversationProvider` (which still means a list of one; passing both fails +startup), and `defaultConversationProviderId` names the host's default: + +```ts +const app = await createApp({ + // Supply the remaining host options as usual. + conversationProviders: [ + createGeminiConversationProvider(geminiKey), + createGptLiveConversationProvider(openAiKey), + ], + defaultConversationProviderId: "gemini-live", +}); +``` + +Startup also fails on duplicate ids or a default that names no registered +service. Registration is discovery, not proof the key works: "usable" means +registered at boot, and a key that fails later ends that conversation with the +ordinary provider error and never selects another service. + +A new Start uses, in order: a one-time pick made before Start (it is never +saved); the saved brain-wide default from Settings › Voice, only if it is still +registered; the host default, only when nothing is saved; the single registered +service, only when nothing is saved. A saved default that is no longer +registered stops there: each Start asks for an explicit pick until the default +is changed in Settings, and the host default is not substituted. Several +services with nothing saved and no host default also need a pick. A saved +default applies from the next explicit Start; a running conversation, and any +reconnect of it, keeps the service it started with. Saving opens no provider, +captures no audio and reads no history. A client that only reads the legacy +`conversationProfile` sees live conversation as unavailable whenever no service +is effective. See [the wire contract](../integration-contract/wire.md#live-service-selection-additive-3616) +and [the HTTP route](../http-api.md#live-conversation-service-default). + ## Live conversation in Chat The shipped conversation client uses the separately registered diff --git a/docs/integration-contract.md b/docs/integration-contract.md index f648d4c178..52d2588e5f 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -64,6 +64,29 @@ shape changes. See [the package API](integration-contract/package-api.md#dictation-speech-integration-and-conformance). This ships in a minor. +## Choosing the live-conversation service (additive, 0.45.0, #3616) + +`CreateAppOptions` adds `conversationProviders?: LiveConversationProvider[]` and +`defaultConversationProviderId?: string`; `conversationProvider` keeps meaning a +list of one, and both together, duplicate ids or an unregistered default fail +startup. `server_hello` adds `conversationProfiles` and `liveDefault`, and keeps +`conversationProfile` only while a service is effective (R1). A new +`live_settings` frame follows a save, `conversation_start` accepts an optional +`providerId` that must equal the disclosed one, and `conversation_opened` adds +`providerSource`. `GET`/`PUT /api/settings/voice` read and save the brain-wide +default behind a new owner-only write guard. The SDK exports `LiveDefault`, +`LiveProviderSource`, `ServerLiveSettings`, `VoiceLiveSettings`, +`VoiceLiveSettingsUpdate` and their schemas; the kit adds `LiveServiceSettings`. +In `@schlessera/brain-ui-react`, the conversation client's state adds +`conversationProfiles`, `liveDefault` and `serviceChoice`, the client adds +`chooseService(providerId | null)` for a one-time pick before Start, and the +REST client adds `liveSettings()` and `saveLiveSettings()`. +Single-provider hosts and existing clients keep their behaviour. See +[wire](integration-contract/wire.md#live-service-selection-additive-3616), +[HTTP](integration-contract/http.md#live-conversation-service-default-additive-3616) +and [the package API](integration-contract/package-api.md#live-service-registration-additive-3616). +This ships in a minor. + ## Bounded multi-read (additive, 0.45.0, #3642) A new read tool, `brain_read_many`, on the MCP server and the pi backend, and a diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index e39d819d57..1159d481e7 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1134,6 +1134,22 @@ headers preserve effective-provider resolution. Retry provider changes return error codes, response schemas and operation binding are supported HTTP promises. +### Live-conversation service default (additive, #3616) + +[`GET`/`PUT /api/settings/voice`](../http-api.md#live-conversation-service-default) +read and save the brain-wide default live-conversation service as +`VoiceLiveSettings` `{ defaultProvider: string | null, revision: number }`. +Reading needs a human session (owner or ambient); writing has its own +owner-only guard: the owner's password or passkey session, or the ambient human, +and 403 with an empty body for anyone else, before the body is read. Unknown +ids are 400 `LIVE_PROVIDER_UNKNOWN`, malformed bodies 400 `LIVE_SETTINGS_INVALID`, +stale revisions 409 `LIVE_SETTINGS_CHANGED` with `current`. A save sends +[`live_settings`](wire.md#live-service-selection-additive-3616) and applies from +the next explicit Start. It is independent of `/api/models/default` and +`/api/voice/dictation/settings`. The route shapes, error codes and the guard are +supported HTTP promises. + + ### Checkpoint cleanup diagnostics (additive, #3815) Authenticated `GET /api/status` adds `journalCleanup`: `retained` contains diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 30bfe177f3..b80da8048d 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1569,6 +1569,34 @@ retention, cost and the error table) is specified in the the two suites above. Boat's environment variable for its own CLI is never read. + + +### Live-service registration (additive, #3616) + +`CreateAppOptions` (`@schlessera/brain-ui-server`) adds +`conversationProviders?: LiveConversationProvider[]`, fixed at construction in +registration order, and `defaultConversationProviderId?: string`, the host's +default while nothing is saved. `conversationProvider` still registers one and +means a list of one. Construction fails when both are given, on duplicate ids, +on an invalid provider, or when `defaultConversationProviderId` names no +registered provider. The saved brain-wide default lives in the ui-server +settings store under `voice.live.defaultProvider` as +`{ value: string | null, revision: number }`; corrupt rows read as nothing +saved, revision 0. It is persisted server state, not part of the disposable +content index. How a Start resolves the service is in +[the wire contract](wire.md#live-service-selection-additive-3616). + +`@schlessera/brain-ui-sdk/protocol` exports `LiveDefault`, `LiveProviderSource`, +`ServerLiveSettings`, `VoiceLiveSettings` and `VoiceLiveSettingsUpdate`; +`ServerHello` adds `conversationProfiles?` and `liveDefault?`, +`ClientConversationStart` adds `providerId?` and `ServerConversationOpened` adds +`providerSource?`. `@schlessera/brain-ui-sdk/schemas` exports +`conversationProfilesSchema`, `liveDefaultSchema`, `serverLiveSettingsSchema` +and `voiceLiveSettingsSchema`; a malformed roster or `liveDefault` is dropped +from a hello without losing the frame. `@schlessera/brain-ui-kit` exports the +presentational `LiveServiceSettings` group (`LiveServiceOption`, +`LiveServiceSettingsProps`, `LiveServiceStatus`), which opens nothing itself. + ### Dictation speech integration and conformance diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 9693e44bbb..784c6aab20 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -1278,8 +1278,11 @@ text, native call ids and generated speech are evidence, never authority. **Registration and discovery.** `CreateAppOptions.conversationProvider?: LiveConversationProvider` (`@schlessera/brain-ui-server`) registers one -provider by value; it is validated at startup and an invalid one throws. Only -then does `server_hello` carry `capabilities.liveConversation: true`. Without +provider by value; it is validated at startup and an invalid one throws. +`conversationProviders` registers several, and the +[live-service selection](#live-service-selection-additive-3616) below says how a +Start chooses among them. Only with at least one does `server_hello` carry +`capabilities.liveConversation: true`. Without one, every `conversation_*` frame is answered with `error` code `CONVERSATION_UNAVAILABLE`. No existing frame, route or rev-3 rule changes, and these additions do not change `PROTOCOL_REV`. @@ -1305,6 +1308,57 @@ server → { type: "conversation_permission", conversationId, epoch, sessionId, turnId, toolUseId, toolName, announce } ``` + + +### Live-service selection (additive, #3616) + +A host registers one live service (`conversationProvider`, a list of one) or +several (`conversationProviders`), plus an optional +`defaultConversationProviderId`. The brain owner saves a brain-wide default +through [`/api/settings/voice`](../http-api.md#live-conversation-service-default). +"Usable" means registered at boot; nothing probes a credential. A Start without +a pick uses the saved default only if it is usable (a saved but unusable +default means no service, never a fall-through), then the host default only +when nothing is saved, then the single registered service only when nothing is +saved, else none. + +``` +server → server_hello { …, conversationProfile?, conversationProfiles: ConversationProfile[], + liveDefault: { saved: string | null, savedUsable, effective: string | null, + source: "saved" | "host" | "only" | "none" } } +server → { type: "live_settings", liveDefault, conversationProfiles } +client → { type: "conversation_start", …, disclosed, providerId? } +server → { type: "conversation_opened", …, providerId, + providerSource?: "change" | "saved" | "host" | "only" } +``` + +- `conversationProfiles` lists every registered service in registration + order, and `liveDefault` says how a Start resolves one. Both are present + exactly when `liveConversation` is. +- `conversationProfile` is present **only when `liveDefault.effective` is + non-null**, and is that service's profile. A single-provider host therefore + sends exactly what it sent before. A client that reads only this field shows + live conversation as unavailable on a multi-service host with nothing + effective (maintainer ruling R1); there is no legacy fallback. +- `live_settings` goes to every open connection after a save, with the same + two fields. It never retargets a running conversation. Clients that predate + it drop it as an unknown frame (`parseServerMessage` reports it; nothing + else changes). +- `conversation_start.providerId` names the service the client disclosed: the + effective one or a one-time pick. The host opens a provider only when + `providerId === disclosed.providerId` and the id is registered; otherwise it + answers `CONVERSATION_DISCLOSURE` and opens nothing. Without `providerId` a + new Start uses the effective service and is refused the same way when there + is none. A resume of a known `conversationId` keeps the service the + conversation opened with, with or without `providerId`; naming another is + refused. The disclosure echo is rechecked after the history reads, so a + default changed on another device in between refuses a Start that named no + service. +- `providerSource` says how the conversation's service was chosen: `change` + for a pick that differs from the effective service, otherwise the + resolution it came from. Older hosts omit it. +- No frame carries a credential, key presence or endpoint. + **Capabilities are evidence.** `capabilities` has seven keys — `nonblockingWork`, `manualEndpoint`, `finalTranscript`, `remoteOutputCancelAck`, `exactPermissionSpeech`, `echoIsolatedInput`, diff --git a/docs/live-conversation-guidance.md b/docs/live-conversation-guidance.md index b85f3ca2af..df10c302ed 100644 --- a/docs/live-conversation-guidance.md +++ b/docs/live-conversation-guidance.md @@ -179,7 +179,7 @@ Keyless source, startup-frame, admission, identity, omission, replacement and prefix tests establish request assembly and host behavior. Scripted audio and prompt substrings do not establish model obedience, recognition, judgment, audible acknowledgement or semantic recall. Actual-provider comparison remains -with #3131/#961; persona/provider Settings remain #3617/#3616. +with #3131/#961; persona Settings remain #3617; the live-service default is in Settings › Voice (#3616). Useful listening scenarios are: From 63c9a48a86442c4363027a4c6f9a8d48994f8c11 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:59:19 +0000 Subject: [PATCH 05/11] test(ui-react): re-audit the connection handler map for live_settings (#3616) Co-Authored-By: Claude Opus 5.5 --- scripts/source-browser-dispatch.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts index eacaa6c5a3..033eb5fd6a 100644 --- a/scripts/source-browser-dispatch.ts +++ b/scripts/source-browser-dispatch.ts @@ -48,10 +48,12 @@ const declarations=[ // Re-audited for #3589: the added attachment_read handler is a no-op // that reads no runtime input, like chat_retired. Re-audited for #3155: // only its comment changed; the reads client takes the frame instead. + // Re-audited for #3616: the added live_settings handler is a no-op that + // reads no runtime input; the root conversation client reads the frame. { "owner": "packages/ui-react/src/hooks/websocket-handlers/connection.ts", "name": "connectionFrameHandlers", - "source": "c3a9fa4ce4132cf1d659ee6e59087c82cc980d468e377addae5bbdc0fcadd244" + "source": "434f740fa556f7faa42b88d82bcd6d3ceba99c9eb7d8abace519ba6ccb525a6d" }, { "owner": "packages/ui-react/src/hooks/websocket-handlers/handoff.ts", From 5453e00877829d5ea897747113ca27ba51e83c64 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:14:20 +0000 Subject: [PATCH 06/11] test(ui-sdk): type the live roster hello comparison (#3616) Co-Authored-By: Claude Opus 5.5 --- packages/ui-sdk/tests/server-schemas.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-sdk/tests/server-schemas.test.ts b/packages/ui-sdk/tests/server-schemas.test.ts index 930a8e04ae..2130105f53 100644 --- a/packages/ui-sdk/tests/server-schemas.test.ts +++ b/packages/ui-sdk/tests/server-schemas.test.ts @@ -417,7 +417,7 @@ describe("live-service roster (#3616)", () => { test("a hello carries the roster and the resolution", () => { const frame = { ...hello, conversationProfiles: [profile("gemini-live"), profile("gpt-live")], liveDefault: { saved: null, savedUsable: false, effective: null, source: "none" } }; const result = parse(frame); - expect(result.ok && result.message).toEqual(frame); + expect(result.ok && result.message).toEqual(frame as never); }); test("a malformed roster or resolution is dropped without losing the hello", () => { for (const bad of [ From 3a9e97637097d615d8bf15a258637bb39afa4ad1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 01:15:15 +0000 Subject: [PATCH 07/11] CONTRACT: docs: the live-service default shares /api/settings/voice with personas (#3616) Co-Authored-By: Claude Opus 5.5 --- .changeset/3616-live-service-default.md | 2 +- api-report/ui-react.txt | 8 + api-report/ui-sdk.txt | 418 ++++++++++++++++++++++- docs/integration-contract.md | 6 +- docs/integration-contract/package-api.md | 4 +- 5 files changed, 432 insertions(+), 6 deletions(-) diff --git a/.changeset/3616-live-service-default.md b/.changeset/3616-live-service-default.md index b0b4125dcf..177df16383 100644 --- a/.changeset/3616-live-service-default.md +++ b/.changeset/3616-live-service-default.md @@ -7,7 +7,7 @@ Choose the default live-conversation service in Settings › Voice (#3616). -- **Server.** `createApp` accepts `conversationProviders` (several live services) and `defaultConversationProviderId`; `conversationProvider` still means a list of one. Startup fails on both options, duplicate ids or a default that is not registered. `GET`/`PUT /api/settings/voice` read and save the brain-wide default against its revision. Writing has its own owner-only guard: the owner's password or passkey session or the ambient human; anyone else gets 403 with an empty body. Unknown ids are 400 `LIVE_PROVIDER_UNKNOWN`, stale revisions 409 `LIVE_SETTINGS_CHANGED`. +- **Server.** `createApp` accepts `conversationProviders` (several live services) and `defaultConversationProviderId`; `conversationProvider` still means a list of one. Startup fails on both options, duplicate ids or a default that is not registered. `GET`/`PUT /api/settings/voice`, shared with the persona selection, add a top-level `defaultProvider`/`revision` pair for the brain-wide default with its own revision. Writing has its own owner-only guard: the owner's password or passkey session or the ambient human; anyone else gets 403 with an empty body. Unknown ids are 400 `LIVE_PROVIDER_UNKNOWN`, stale revisions 409 `LIVE_SETTINGS_CHANGED`. - **Wire.** `server_hello` adds `conversationProfiles` and `liveDefault`, and sends `conversationProfile` only while a service is effective, so a single-provider host is unchanged. A save sends `live_settings` to open connections. `conversation_start` accepts `providerId`, which must equal the disclosed profile's; `conversation_opened` adds `providerSource`. - **Selection.** A Start uses a one-time pick, else the saved default if it is still registered, else the host default or the only service when nothing is saved. A saved default that is no longer registered requires an explicit pick and is never replaced by the host default. A save applies from the next explicit Start; a running conversation and its reconnects keep their service. Nothing probes a credential, and saving opens no provider, microphone or history. - **App.** Settings › Voice gains the Live service group (kit `LiveServiceSettings`), and the pre-Start disclosure sheet offers the one-time pick when several services are usable or the saved default is unavailable. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index 08dc1f0261..eb49090367 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -358,6 +358,9 @@ signatures (every public export and the types it is made of) disclosureOpen: boolean; profile: ServerConversationOpened | null; conversationProfile: ConversationProfile | null; + conversationProfiles: ConversationProfile[]; + liveDefault: LiveDefault | null; + serviceChoice: string | null; livePersona: LivePersonaStatus | null; durableAvailable: boolean; sessionId: string | null; @@ -1134,6 +1137,7 @@ signatures (every public export and the types it is made of) hygieneReview: () => Promise; livePersona: (id: string) => Promise; livePersonas: () => Promise; + liveSettings: () => Promise; login: (password: string) => Promise<{ ok: true; }>; @@ -1237,6 +1241,7 @@ signatures (every public export and the types it is made of) refreshModels: () => Promise; saveDictationSettings: (settings: DictationSettings) => Promise; saveLivePersonaSelection: (value: string, revision: number) => Promise; + saveLiveSettings: (update: VoiceLiveSettingsUpdate) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; @@ -1390,6 +1395,7 @@ signatures (every public export and the types it is made of) connect: () => () => void; conversation: { attachControls(): () => void; + chooseService(providerId: null | string): void; commit: (own: number) => boolean; details(): void; discard(): void; @@ -1645,6 +1651,7 @@ signatures (every public export and the types it is made of) hygieneReview: () => Promise; livePersona: (id: string) => Promise; livePersonas: () => Promise; + liveSettings: () => Promise; login: (password: string) => Promise<{ ok: true; }>; @@ -1748,6 +1755,7 @@ signatures (every public export and the types it is made of) refreshModels: () => Promise; saveDictationSettings: (settings: import("@schlessera/brain-ui-sdk").DictationSettings) => Promise; saveLivePersonaSelection: (value: string, revision: number) => Promise; + saveLiveSettings: (update: import("@schlessera/brain-ui-sdk").VoiceLiveSettingsUpdate) => Promise; sessionRecovery: (sessionId: string, opts?: { signal?: AbortSignal; }) => Promise; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 6d07a320e9..8dcc4380e0 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -257,6 +257,7 @@ export "." (./src/index.ts) LIVENESS_CAPABILITY LIVE_PERSONA_LIMITS LOCAL_ANSWER_CLOSE + type LiveDefault type LivePersona type LivePersonaCreateRequest type LivePersonaInvalidReason @@ -265,6 +266,7 @@ export "." (./src/index.ts) type LivePersonaStatus type LivePersonaSummary type LivePersonaUpdateRequest + type LiveProviderSource type LocalAnswer type LocalExchange MAX_IMAGES_PER_MESSAGE @@ -364,6 +366,7 @@ export "." (./src/index.ts) type ServerHandoffReceipt type ServerHello type ServerLivePersona + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -483,6 +486,8 @@ export "." (./src/index.ts) type V1ResolutionEffect type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -875,6 +880,7 @@ export "./client" (./src/client/index.ts) LIVE_PERSONA_LIMITS LOCAL_ANSWER_CLOSE LOCATION_PAYLOAD_SCHEMA + type LiveDefault type LivePersona type LivePersonaCreateRequest type LivePersonaInvalidReason @@ -883,6 +889,7 @@ export "./client" (./src/client/index.ts) type LivePersonaStatus type LivePersonaSummary type LivePersonaUpdateRequest + type LiveProviderSource type LivenessEvent type LocalAnswer type LocalExchange @@ -1036,6 +1043,7 @@ export "./client" (./src/client/index.ts) type ServerHandoffReceipt type ServerHello type ServerLivePersona + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -1174,6 +1182,8 @@ export "./client" (./src/client/index.ts) type V1ResolutionEffect type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -1763,6 +1773,7 @@ export "./protocol" (./src/protocol.ts) LIVENESS_CAPABILITY LIVE_PERSONA_LIMITS LOCAL_ANSWER_CLOSE + type LiveDefault type LivePersona type LivePersonaCreateRequest type LivePersonaInvalidReason @@ -1771,6 +1782,7 @@ export "./protocol" (./src/protocol.ts) type LivePersonaStatus type LivePersonaSummary type LivePersonaUpdateRequest + type LiveProviderSource type LocalAnswer type LocalExchange MAX_IMAGES_PER_MESSAGE @@ -1865,6 +1877,7 @@ export "./protocol" (./src/protocol.ts) type ServerHandoffReceipt type ServerHello type ServerLivePersona + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -1984,6 +1997,8 @@ export "./protocol" (./src/protocol.ts) type V1ResolutionEffect type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -2077,6 +2092,7 @@ export "./schemas" (./src/schemas.ts) conversationOutputRecordSchema conversationPersonaRefSchema conversationProfileSchema + conversationProfilesSchema conversationSampleRateSchema conversationVoiceSchema conversationWireEventSchema @@ -2123,6 +2139,7 @@ export "./schemas" (./src/schemas.ts) inboxThreadSchema inboxViewSchema inboxWorkPayloadSchema + liveDefaultSchema livePersonaListResponseSchema livePersonaProviderStatusSchema livePersonaSchema @@ -2166,6 +2183,7 @@ export "./schemas" (./src/schemas.ts) serverHandoffReceiptSchema serverHelloSchema serverLivePersonaSchema + serverLiveSettingsSchema serverLocalExchangeResultSchema serverLocationRequestSchema serverMaskRequestSchema @@ -2200,6 +2218,7 @@ export "./schemas" (./src/schemas.ts) turnScopeSummarySchema v1ResolutionEffectSchema validateResolutionEffect + voiceLiveSettingsSchema voiceSettingsResponseSchema export "./server" (./src/server/index.ts) @@ -2644,6 +2663,7 @@ export "./server" (./src/server/index.ts) type LiveConversationOpenOptions type LiveConversationProvider type LiveConversationSession + type LiveDefault type LivePersona type LivePersonaCreateRequest type LivePersonaInvalidReason @@ -2652,6 +2672,7 @@ export "./server" (./src/server/index.ts) type LivePersonaStatus type LivePersonaSummary type LivePersonaUpdateRequest + type LiveProviderSource type LocalAnswer type LocalExchange type LocationFix @@ -2808,6 +2829,7 @@ export "./server" (./src/server/index.ts) type ServerHandoffReceipt type ServerHello type ServerLivePersona + type ServerLiveSettings type ServerLocalExchangeResult type ServerLocationRequest type ServerMaskRequest @@ -2969,6 +2991,8 @@ export "./server" (./src/server/index.ts) type VersionRequirementCheck type VoiceCapabilitiesResponse type VoiceKeytermsResponse + type VoiceLiveSettings + type VoiceLiveSettingsUpdate type VoiceMode type VoiceProvidersResponse type VoiceSessionRequest @@ -6867,6 +6891,7 @@ signatures (every public export and the types it is made of) ClientConversationStart (packages/ui-sdk/src/protocol.ts) export interface ClientConversationStart { disclosed?: ConversationProfile; + providerId?: string; personaRef?: ConversationPersonaRef; historyOwnerId?: string; contextualTasks?: boolean; @@ -8696,6 +8721,13 @@ signatures (every public export and the types it is made of) remote: "acknowledged" | "unknown"; }>; } + LiveDefault (packages/ui-sdk/src/protocol.ts) + export interface LiveDefault { + saved: string | null; + savedUsable: boolean; + effective: string | null; + source: Exclude; + } LivePersona (packages/ui-sdk/src/protocol.ts) export interface LivePersona extends LivePersonaSummary { instructions: string; @@ -8750,6 +8782,8 @@ signatures (every public export and the types it is made of) voices: Record; instructions: string; } + LiveProviderSource (packages/ui-sdk/src/protocol.ts) + export type LiveProviderSource = "change" | "saved" | "host" | "only" | "none"; LivenessEvent (packages/ui-sdk/src/client/ws-client.ts) export type LivenessEvent = { type: "probe"; @@ -11274,6 +11308,7 @@ signatures (every public export and the types it is made of) epoch: number; sessionId?: string; providerId: string; + providerSource?: Exclude; capabilities: ConversationCapabilities; disclosure: ConversationDisclosure; limits: ConversationLimits; @@ -11345,6 +11380,8 @@ signatures (every public export and the types it is made of) export interface ServerHello { safetyCapabilities?: SafetyCapabilities; conversationProfile?: ConversationProfile; + conversationProfiles?: ConversationProfile[]; + liveDefault?: LiveDefault; livePersona?: LivePersonaStatus; type: "server_hello"; protocolRev: number; @@ -11358,6 +11395,12 @@ signatures (every public export and the types it is made of) type: "live_persona"; livePersona: LivePersonaStatus; } + ServerLiveSettings (packages/ui-sdk/src/protocol.ts) + export interface ServerLiveSettings { + type: "live_settings"; + liveDefault: LiveDefault; + conversationProfiles: ConversationProfile[]; + } ServerLocalExchangeResult (packages/ui-sdk/src/protocol.ts) export interface ServerLocalExchangeResult extends SessionScoped { type: "local_exchange_result"; @@ -11380,7 +11423,7 @@ signatures (every public export and the types it is made of) instruction?: string; } ServerMessage (packages/ui-sdk/src/protocol.ts) - export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerLivePersona | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired | ServerAttachmentRead; + export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerLivePersona | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired | ServerAttachmentRead | ServerLiveSettings; ServerMessageBlocks (packages/ui-sdk/src/protocol.ts) export interface ServerMessageBlocks extends SessionScoped { type: "message_blocks"; @@ -12832,6 +12875,16 @@ signatures (every public export and the types it is made of) generatedAt: number; count: number; } + VoiceLiveSettings (packages/ui-sdk/src/protocol.ts) + export interface VoiceLiveSettings { + defaultProvider: string | null; + revision: number; + } + VoiceLiveSettingsUpdate (packages/ui-sdk/src/protocol.ts) + export interface VoiceLiveSettingsUpdate { + defaultProvider: string | null; + revision: number; + } VoiceMode (packages/ui-sdk/src/protocol.ts) export type VoiceMode = "idle" | "dictate" | "conversation"; VoiceProvidersResponse (packages/ui-sdk/src/protocol.ts) @@ -12867,7 +12920,7 @@ signatures (every public export and the types it is made of) capabilities: SpeechCapabilities; } VoiceSettingsResponse (packages/ui-sdk/src/protocol.ts) - export interface VoiceSettingsResponse { + export interface VoiceSettingsResponse extends VoiceLiveSettings { persona: { value: string; revision: number; @@ -12876,6 +12929,8 @@ signatures (every public export and the types it is made of) } VoiceSettingsUpdateRequest (packages/ui-sdk/src/protocol.ts) export interface VoiceSettingsUpdateRequest { + defaultProvider?: string | null; + revision?: number; persona?: { value: string; revision: number; @@ -13449,6 +13504,7 @@ signatures (every public export and the types it is made of) revision: z.ZodString; voice: z.ZodOptional>; }, z.core.$strip>>>; + providerId: z.ZodOptional; requestId: z.ZodOptional; sessionId: z.ZodOptional; type: z.ZodLiteral<"conversation_start">; @@ -13971,6 +14027,7 @@ signatures (every public export and the types it is made of) revision: z.ZodString; voice: z.ZodOptional>; }, z.core.$strip>>>; + providerId: z.ZodOptional; requestId: z.ZodOptional; sessionId: z.ZodOptional; type: z.ZodLiteral<"conversation_start">; @@ -14257,6 +14314,62 @@ signatures (every public export and the types it is made of) label: z.ZodString; }, z.core.$strip>>>>; }, z.core.$strip>; + conversationProfilesSchema (packages/ui-sdk/src/schemas.ts) + const conversationProfilesSchema: z.ZodArray>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + defaultVoice: z.ZodCatch>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; + providerId: z.ZodString; + voices: z.ZodCatch>>>; + }, z.core.$strip>>; conversationSampleRateSchema (packages/ui-sdk/src/schemas.ts) const conversationSampleRateSchema: z.ZodNumber; conversationVoiceSchema (packages/ui-sdk/src/schemas.ts) @@ -18073,6 +18186,18 @@ signatures (every public export and the types it is made of) const isWebToolName: (name: string) => name is WebToolName; killWrapped (packages/ui-sdk/src/server/exec-wrapper.ts) export function killWrapped(proc: KillableProcess, config?: ExecWrapperConfig, signal?: NodeJS.Signals, onFailure?: (message: string) => void, bounded?: WrappedKillOptions): void; + liveDefaultSchema (packages/ui-sdk/src/schemas.ts) + const liveDefaultSchema: z.ZodObject<{ + effective: z.ZodNullable; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>; livePersonaListResponseSchema (packages/ui-sdk/src/schemas.ts) const livePersonaListResponseSchema: z.ZodObject<{ personas: z.ZodArray; providerId: z.ZodString; + providerSource: z.ZodCatch>>; requestId: z.ZodOptional; resync: z.ZodObject<{ outputs: z.ZodNumber; @@ -20488,6 +20619,72 @@ signatures (every public export and the types it is made of) label: z.ZodString; }, z.core.$strip>>>>; }, z.core.$strip>>>>; + conversationProfiles: z.ZodCatch>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + defaultVoice: z.ZodCatch>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; + providerId: z.ZodString; + voices: z.ZodCatch>>>; + }, z.core.$strip>>>>>; + liveDefault: z.ZodCatch; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>>>>; livePersona: z.ZodCatch>; @@ -20600,6 +20797,76 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; type: z.ZodLiteral<"live_persona">; }, z.core.$loose>; + serverLiveSettingsSchema (packages/ui-sdk/src/schemas.ts) + const serverLiveSettingsSchema: z.ZodObject<{ + conversationProfiles: z.ZodArray>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + defaultVoice: z.ZodCatch>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; + providerId: z.ZodString; + voices: z.ZodCatch>>>; + }, z.core.$strip>>; + liveDefault: z.ZodObject<{ + effective: z.ZodNullable; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>; + type: z.ZodLiteral<"live_settings">; + }, z.core.$loose>; serverLocalExchangeResultSchema (packages/ui-sdk/src/schemas.ts) const serverLocalExchangeResultSchema: z.ZodObject<{ exchangeId: z.ZodString; @@ -21298,6 +21565,72 @@ signatures (every public export and the types it is made of) label: z.ZodString; }, z.core.$strip>>>>; }, z.core.$strip>>>>; + conversationProfiles: z.ZodCatch>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + defaultVoice: z.ZodCatch>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; + providerId: z.ZodString; + voices: z.ZodCatch>>>; + }, z.core.$strip>>>>>; + liveDefault: z.ZodCatch; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>>>>; livePersona: z.ZodCatch>; @@ -24439,6 +24772,12 @@ signatures (every public export and the types it is made of) maxUtterances: z.ZodNumber; }, z.core.$loose>; providerId: z.ZodString; + providerSource: z.ZodCatch>>; requestId: z.ZodOptional; resync: z.ZodObject<{ outputs: z.ZodNumber; @@ -24694,6 +25033,74 @@ signatures (every public export and the types it is made of) toolUseId: z.ZodString; turnId: z.ZodString; type: z.ZodLiteral<"conversation_permission">; + }, z.core.$loose>, z.ZodObject<{ + conversationProfiles: z.ZodArray>; + echoIsolatedInput: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + exactPermissionSpeech: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + finalTranscript: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + manualEndpoint: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + nonblockingWork: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + outputWordAlignment: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + remoteOutputCancelAck: z.ZodEnum<{ + supported: "supported"; + unproven: "unproven"; + unsupported: "unsupported"; + }>; + }, z.core.$loose>; + defaultVoice: z.ZodCatch>; + disclosure: z.ZodObject<{ + destinations: z.ZodArray; + voiceService: z.ZodString; + }, z.core.$loose>; + personaInstructionBytes: z.ZodCatch>; + providerId: z.ZodString; + voices: z.ZodCatch>>>; + }, z.core.$strip>>; + liveDefault: z.ZodObject<{ + effective: z.ZodNullable; + saved: z.ZodNullable; + savedUsable: z.ZodBoolean; + source: z.ZodEnum<{ + host: "host"; + none: "none"; + only: "only"; + saved: "saved"; + }>; + }, z.core.$loose>; + type: z.ZodLiteral<"live_settings">; }, z.core.$loose>], "type">; serverPongSchema (packages/ui-sdk/src/schemas.ts) const serverPongSchema: z.ZodObject<{ @@ -26442,8 +26849,14 @@ signatures (every public export and the types it is made of) export function validateVersionMinimum(value: unknown, owner: string, identity: string): string; visibleToolName (packages/ui-sdk/src/tool-contracts/contract.ts) export function visibleToolName(name: string, adapter: ToolAdapter): string; + voiceLiveSettingsSchema (packages/ui-sdk/src/schemas.ts) + const voiceLiveSettingsSchema: z.ZodObject<{ + defaultProvider: z.ZodNullable; + revision: z.ZodNumber; + }, z.core.$loose>; voiceSettingsResponseSchema (packages/ui-sdk/src/schemas.ts) const voiceSettingsResponseSchema: z.ZodObject<{ + defaultProvider: z.ZodNullable; livePersona: z.ZodObject<{ persona: z.ZodObject<{ builtIn: z.ZodOptional>; @@ -26484,6 +26897,7 @@ signatures (every public export and the types it is made of) revision: z.ZodNumber; value: z.ZodString; }, z.core.$strip>; + revision: z.ZodNumber; }, z.core.$loose>; webToolProviders (packages/ui-sdk/src/tool-contracts/web.ts) export function webToolProviders(input: Record): readonly string[]; diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 04a714189c..7146d1dc0c 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -94,8 +94,10 @@ startup. `server_hello` adds `conversationProfiles` and `liveDefault`, and keeps `conversationProfile` only while a service is effective (R1). A new `live_settings` frame follows a save, `conversation_start` accepts an optional `providerId` that must equal the disclosed one, and `conversation_opened` adds -`providerSource`. `GET`/`PUT /api/settings/voice` read and save the brain-wide -default behind a new owner-only write guard. The SDK exports `LiveDefault`, +`providerSource`. `GET`/`PUT /api/settings/voice`, shared with the persona +selection (#3617), add the top-level `defaultProvider`/`revision` pair for the +brain-wide default, each group with its own revision, and the route's writes +gain a new owner-only guard. The SDK exports `LiveDefault`, `LiveProviderSource`, `ServerLiveSettings`, `VoiceLiveSettings`, `VoiceLiveSettingsUpdate` and their schemas; the kit adds `LiveServiceSettings`. In `@schlessera/brain-ui-react`, the conversation client's state adds diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 89ec41067d..4a08bc5f44 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -1590,7 +1590,9 @@ content index. How a Start resolves the service is in `ServerLiveSettings`, `VoiceLiveSettings` and `VoiceLiveSettingsUpdate`; `ServerHello` adds `conversationProfiles?` and `liveDefault?`, `ClientConversationStart` adds `providerId?` and `ServerConversationOpened` adds -`providerSource?`. `@schlessera/brain-ui-sdk/schemas` exports +`providerSource?`. `VoiceSettingsResponse` (the shared `/api/settings/voice` +body, #3617) extends `VoiceLiveSettings`, and `VoiceSettingsUpdateRequest` adds +optional `defaultProvider` and `revision`. `@schlessera/brain-ui-sdk/schemas` exports `conversationProfilesSchema`, `liveDefaultSchema`, `serverLiveSettingsSchema` and `voiceLiveSettingsSchema`; a malformed roster or `liveDefault` is dropped from a hello without losing the frame. `@schlessera/brain-ui-kit` exports the From 233872b3da2124533918592fbb8e153b47cb8966 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 02:02:59 +0000 Subject: [PATCH 08/11] test: inventory the live service runtime proof (#3616) Co-Authored-By: Claude Opus 5.5 --- scripts/runtime-test-builds.ts | 2 +- tests/runtime-build-selection.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/runtime-test-builds.ts b/scripts/runtime-test-builds.ts index d90848b1df..f19ac637b1 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", "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", "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 fed77a66ac..ec93c8ba59 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(22); + expect(hooks).toHaveLength(23); 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"); From 2b2d4591ccdd5c3c63cdb9ac10e7dc67f17168fa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 02:35:01 +0000 Subject: [PATCH 09/11] CONTRACT: feat(ui-react,ui-kit): wire the Start card for service, persona and recovery (#3698) Live conversation opens on the kit StartCard instead of the pre-Start disclosure sheet. The card names the service Start would open, carries the full former disclosure behind "What's shared", shows Change only with two or more usable services (one-time, never saved), requires an explicit Choose when the saved service is unavailable, and saves a picked persona as the default (V2). S3/S3b/S3c and an unusable persona render as the card's notice, with one-time "Use the default voice this time" and "Use Standard this time". The conversation client gains personaChoice/choosePersona so Start sends exactly the persona and voice the card shows; a refused first Start may pick again. The kit Service row no longer breaks its key and link at 320px. Co-Authored-By: Claude Opus 5.5 --- .changeset/3698-start-card.md | 11 + api-report/ui-react.txt | 2 + docs/integration-contract.md | 14 + docs/integration-contract/package-api.md | 17 + packages/ui-kit/src/tokens.css | 4 +- packages/ui-react/README.md | 28 +- .../components/voice/conversation-field.tsx | 49 +-- .../src/components/voice/start-card.tsx | 196 +++++++++ .../ui-react/src/voice/conversation-client.ts | 43 +- .../browser/conversation-controls.offline.tsx | 10 +- .../tests/browser/conversation.offline.tsx | 9 +- .../browser/dialogue-qualifiers.offline.tsx | 23 +- .../tests/fixtures/start-card-client.tsx | 26 ++ .../tests/live-service-runtime.test.ts | 16 +- .../ui-react/tests/start-card-runtime.test.ts | 414 ++++++++++++++++++ 15 files changed, 784 insertions(+), 78 deletions(-) create mode 100644 .changeset/3698-start-card.md create mode 100644 packages/ui-react/src/components/voice/start-card.tsx create mode 100644 packages/ui-react/tests/fixtures/start-card-client.tsx create mode 100644 packages/ui-react/tests/start-card-runtime.test.ts 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..7b75a88bba --- /dev/null +++ b/packages/ui-react/tests/start-card-runtime.test.ts @@ -0,0 +1,414 @@ +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"], "ithaca-steward", null); + const page = await open(width, height); + const before = counts(); + await enter(page, 2); + // 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); +}); From 1e79c94bc019f299c7f4f62c2547fa190c605945 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 02:36:58 +0000 Subject: [PATCH 10/11] test: inventory the Start card runtime proof (#3698) Co-Authored-By: Claude Opus 5.5 --- scripts/runtime-test-builds.ts | 2 +- tests/runtime-build-selection.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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"); From e0783626ec26a7020661c03d145197153bdf34bd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 05:41:12 +0000 Subject: [PATCH 11/11] test(ui-react): pin the edited-persona refusal to the card's own pick (#3698) A Start without a card pick sends the saved persona; if the host's fresh live_persona frame arrives before Start, the edit is already disclosed and Start opens it. Picking the persona on the card pins the old revision, so the refusal path is the one exercised. Co-Authored-By: Claude Opus 5.5 --- packages/ui-react/tests/start-card-runtime.test.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/ui-react/tests/start-card-runtime.test.ts b/packages/ui-react/tests/start-card-runtime.test.ts index 7b75a88bba..ac80541976 100644 --- a/packages/ui-react/tests/start-card-runtime.test.ts +++ b/packages/ui-react/tests/start-card-runtime.test.ts @@ -389,10 +389,15 @@ describe.skipIf(!executablePath)("the Start card against mounted routes and two 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"], "ithaca-steward", null); + await brainWith(["ithaca-steward"], "standard", null); const page = await open(width, height); const before = counts(); - await enter(page, 2); + 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`);