diff --git a/apps/sandbox/templates/moq-publisher/fake-media.ts b/apps/sandbox/templates/moq-publisher/fake-media.ts index a21f7bc417..324c18aa04 100644 --- a/apps/sandbox/templates/moq-publisher/fake-media.ts +++ b/apps/sandbox/templates/moq-publisher/fake-media.ts @@ -32,6 +32,8 @@ const FAKE_AUDIO_BITRATE = 1.28e5; * `internal/design/spf/features/publisher-multi-source-capture.md`). That * extra independence isn't this fake's job to demonstrate; it only needs to * satisfy the additive capability contract for the sandbox's `?fake` mode. + * `micActive` runs a third, audio-only pipeline for the explicit mic seam, + * so a mic-only publish is drivable here too. */ export class FakePublishMedia extends HTMLVideoElementHost @@ -48,15 +50,22 @@ export class FakePublishMedia #cameraActive = false; #screenShareActive = false; + #micActive = false; #cameraState: MediaCaptureState = 'idle'; #screenShareState: MediaCaptureState = 'idle'; #cameraStream: MediaStream | null = null; #screenShareStream: MediaStream | null = null; + /** Owned by the explicit mic pipeline; never exposed or previewed. */ + #micStream: MediaStream | null = null; /** Bumped per kind to cancel in-flight acquisitions when it's re-toggled. */ #cameraAcquireToken = 0; #screenAcquireToken = 0; + #micAcquireToken = 0; /** Owned: losing the merged audio track doesn't end its stream, so `micState` has nothing live to read 'ended' off. */ #micEnded = false; + /** Owned: the explicit pipeline's in-flight/denied phases have no stream to derive from either. */ + #micAcquiring = false; + #micDenied = false; #captureDevices: MediaCaptureDeviceInfo[] = []; #videoInputDeviceId = ''; @@ -101,12 +110,14 @@ export class FakePublishMedia this.#disposed.abort(); this.#cameraAcquireToken++; this.#screenAcquireToken++; + this.#micAcquireToken++; this.#clearPublishTimer(); this.#stopStats(); this.#pendingPublish?.reject(new Error('The media host was destroyed.')); this.#pendingPublish = null; this.#releaseStream('camera'); this.#releaseStream('screen'); + this.#releaseMicStream(); super.destroy(); } @@ -127,9 +138,7 @@ export class FakePublishMedia this.#cameraAcquireToken++; this.#releaseStream('camera'); this.#setCaptureState('camera', 'idle'); - if (!this.#screenShareActive && (this.#publishState === 'connecting' || this.#publishState === 'live')) { - this.unpublish(); - } + this.#unpublishWithoutSources(); } } @@ -148,9 +157,30 @@ export class FakePublishMedia this.#screenAcquireToken++; this.#releaseStream('screen'); this.#setCaptureState('screen', 'idle'); - if (!this.#cameraActive && (this.#publishState === 'connecting' || this.#publishState === 'live')) { - this.unpublish(); - } + this.#unpublishWithoutSources(); + } + } + + get micActive(): boolean { + return this.#micActive; + } + + set micActive(value: boolean) { + if (value === this.#micActive) return; + this.#micActive = value; + this.dispatchEvent(new Event('capturesourcechange')); + + if (value) { + void this.#acquireMic(); + } else { + this.#micAcquireToken++; + this.#updateMicState(() => { + this.#releaseMicStream(); + this.#micAcquiring = false; + this.#micDenied = false; + this.#micEnded = false; + }); + this.#unpublishWithoutSources(); } } @@ -163,16 +193,20 @@ export class FakePublishMedia } /** - * Mostly derived: this fake merges mic audio into each capture stream - * (see the header note) instead of running an independent mic pipeline, - * so 'active' reads straight off the live streams. 'ended' needs the - * owned `#micEnded` flag — losing the audio track removes it from its - * stream without ending the stream itself, so there's nothing live to - * derive 'ended' from. + * Mostly derived: this fake merges mic audio into each video capture + * stream (see the header note), and the explicit `micActive` pipeline + * owns `#micStream`, so 'active' reads straight off the live streams. + * The remaining phases need owned flags — losing a merged audio track + * removes it from its stream without ending the stream itself, and the + * explicit pipeline's acquiring/denied phases have no stream at all. */ get micState(): MediaCaptureState { const hasAudio = (stream: MediaStream | null) => (stream?.getAudioTracks().length ?? 0) > 0; - if (hasAudio(this.#cameraStream) || hasAudio(this.#screenShareStream)) return 'active'; + if (hasAudio(this.#micStream) || hasAudio(this.#cameraStream) || hasAudio(this.#screenShareStream)) { + return 'active'; + } + if (this.#micAcquiring) return 'acquiring'; + if (this.#micDenied) return 'denied'; return this.#micEnded ? 'ended' : 'idle'; } @@ -208,6 +242,7 @@ export class FakePublishMedia if (value === this.#audioInputDeviceId) return; this.#audioInputDeviceId = value; this.#reacquireCamera(); + this.#reacquireMic(); } // ── MediaCaptureToggleCapability ──────────────────────────────────────── @@ -232,6 +267,7 @@ export class FakePublishMedia this.#micMuted = value; for (const track of this.#cameraStream?.getAudioTracks() ?? []) track.enabled = !value; for (const track of this.#screenShareStream?.getAudioTracks() ?? []) track.enabled = !value; + for (const track of this.#micStream?.getAudioTracks() ?? []) track.enabled = !value; this.dispatchEvent(new Event('capturetogglechange')); } @@ -253,7 +289,11 @@ export class FakePublishMedia if (this.#publishState === 'connecting' || this.#publishState === 'live' || this.#publishState === 'stopping') { return Promise.reject(new Error(`publish() is not allowed while the session is ${this.#publishState}.`)); } - if (this.#cameraState !== 'active' && this.#screenShareState !== 'active') { + if ( + this.#cameraState !== 'active' && + this.#screenShareState !== 'active' && + !(this.#micActive && this.micState === 'active') + ) { this.#publishError = { code: 0, message: 'publish() requires an active capture source.' }; this.#setPublishState('error'); return Promise.reject(new Error(this.#publishError.message)); @@ -337,22 +377,93 @@ export class FakePublishMedia * click. Sets the backing field directly — the setter's release path * would clobber the terminal state the UI needs. */ - #consumeIntent(kind: MediaCaptureSourceKind): void { + #consumeIntent(kind: MediaCaptureSourceKind | 'mic'): void { if (kind === 'camera') this.#cameraActive = false; - else this.#screenShareActive = false; + else if (kind === 'screen') this.#screenShareActive = false; + else this.#micActive = false; this.dispatchEvent(new Event('capturesourcechange')); // Every involuntary-release caller (acquire failure, track-ended) routes - // through here, so this is the one place that can see "no source left" — - // a live session with nothing capturing must not stay live. - if ( - !this.#cameraActive && - !this.#screenShareActive && - (this.#publishState === 'connecting' || this.#publishState === 'live') - ) { - this.unpublish(); + // through here — a live session with nothing capturing must not stay live. + this.#unpublishWithoutSources(); + } + + /** Shared by intent consumption and the consumer-release setters: no intent left means no session. */ + #unpublishWithoutSources(): void { + if (this.#cameraActive || this.#screenShareActive || this.#micActive) return; + if (this.#publishState === 'connecting' || this.#publishState === 'live') this.unpublish(); + } + + /** The explicit audio-only pipeline behind `micActive`; video capture keeps merging its own mic audio. */ + async #acquireMic(): Promise { + const token = ++this.#micAcquireToken; + this.#updateMicState(() => { + this.#releaseMicStream(); + this.#micAcquiring = true; + this.#micDenied = false; + }); + + try { + const stream = await navigator.mediaDevices.getUserMedia({ + audio: this.#audioInputDeviceId ? { deviceId: this.#audioInputDeviceId } : true, + }); + if (token !== this.#micAcquireToken) { + for (const track of stream.getTracks()) track.stop(); + return; + } + for (const track of stream.getAudioTracks()) track.enabled = !this.#micMuted; + this.#updateMicState(() => { + this.#micAcquiring = false; + this.#micEnded = false; + this.#micStream = stream; + }); + this.#watchMicTracks(stream); + // Device labels stay redacted until a grant, so refresh after acquiring. + void this.#refreshDevices(); + } catch (error) { + if (token !== this.#micAcquireToken) return; + this.#updateMicState(() => { + this.#micAcquiring = false; + this.#micDenied = error instanceof DOMException && error.name === 'NotAllowedError'; + }); + this.#consumeIntent('mic'); } } + /** + * Mirrors `#setCaptureState`'s dedupe for the derived mic lifecycle: + * merged video audio can hold `micState` at 'active' across explicit + * pipeline changes, and an unchanged state must not fire the event. + */ + #updateMicState(mutate: () => void): void { + const before = this.micState; + mutate(); + if (this.micState !== before) this.dispatchEvent(new Event('capturestatechange')); + } + + #watchMicTracks(stream: MediaStream): void { + for (const track of stream.getTracks()) { + track.addEventListener( + 'ended', + () => { + if (this.#micStream !== stream) return; + this.#updateMicState(() => { + this.#releaseMicStream(); + this.#micEnded = true; + }); + this.#consumeIntent('mic'); + }, + { once: true } + ); + } + } + + #releaseMicStream(): void { + const stream = this.#micStream; + if (!stream) return; + this.#micStream = null; + for (const track of stream.getTracks()) track.stop(); + } + async #getCameraStream(): Promise { return navigator.mediaDevices.getUserMedia({ video: this.#videoInputDeviceId ? { deviceId: this.#videoInputDeviceId } : true, @@ -397,7 +508,7 @@ export class FakePublishMedia else this.#screenShareStream = null; for (const track of stream.getTracks()) track.stop(); // The last source is gone — clean slate, back to 'idle' rather than a stale 'ended' outliving the capture that produced it. - if (!this.#cameraStream && !this.#screenShareStream) this.#micEnded = false; + if (!this.#cameraStream && !this.#screenShareStream && !this.#micStream) this.#micEnded = false; this.dispatchEvent(new Event('capturestreamchange')); this.#syncPreview(); } @@ -438,6 +549,12 @@ export class FakePublishMedia void this.#acquire('camera'); } + #reacquireMic(): void { + if (!this.#micActive) return; + if (!this.#micStream && !this.#micAcquiring) return; + void this.#acquireMic(); + } + async #refreshDevices(): Promise { if (!navigator.mediaDevices?.enumerateDevices) return; const devices = await navigator.mediaDevices.enumerateDevices(); @@ -495,13 +612,18 @@ export class FakePublishMedia let droppedFrames = 0; this.#statsTimer = setInterval(() => { - const videoBitrate = FAKE_VIDEO_BITRATE * (0.92 + Math.random() * 0.16); - const audioBitrate = FAKE_AUDIO_BITRATE; - bytesSent += Math.round((videoBitrate + audioBitrate) / 8); - if (Math.random() < 0.1) droppedFrames += 1; + // Source-aware per sample, so a mic-only session reports no video + // traffic (the stats contract uses NaN for absent metrics) and a + // video source joining mid-session starts counting. + const hasVideo = this.cameraStream !== null || this.screenShareStream !== null; + const hasAudio = this.micState === 'active'; + const videoBitrate = hasVideo ? FAKE_VIDEO_BITRATE * (0.92 + Math.random() * 0.16) : Number.NaN; + const audioBitrate = hasAudio ? FAKE_AUDIO_BITRATE : Number.NaN; + bytesSent += Math.round(((hasVideo ? videoBitrate : 0) + (hasAudio ? audioBitrate : 0)) / 8); + if (hasVideo && Math.random() < 0.1) droppedFrames += 1; this.#publishStats = { - encodedFps: Math.round(29 + Math.random() * 2), + encodedFps: hasVideo ? Math.round(29 + Math.random() * 2) : Number.NaN, videoBitrate, audioBitrate, droppedFrames, diff --git a/packages/core/src/core/ui/capture-placeholder/capture-placeholder-core.ts b/packages/core/src/core/ui/capture-placeholder/capture-placeholder-core.ts index dc4577ce71..eb8b495e8a 100644 --- a/packages/core/src/core/ui/capture-placeholder/capture-placeholder-core.ts +++ b/packages/core/src/core/ui/capture-placeholder/capture-placeholder-core.ts @@ -22,7 +22,7 @@ export interface CapturePlaceholderState extends ButtonState { * Core state machine for the placeholder shown over the preview area before * any capture source is active. Its label is an enable-devices CTA while * `idle` or `ended`, a progress hint while `acquiring`, permission guidance - * when `denied`, and empty once either source is `active`. + * when `denied`, and empty once any counted source is `active`. */ export class CapturePlaceholderCore { static readonly defaultProps: NonNullableObject = { @@ -67,7 +67,7 @@ export class CapturePlaceholderCore { getState(): CapturePlaceholderState { const media = this.#media!; - this.state.patch({ captureState: aggregateCaptureState(media.cameraState, media.screenShareState) }); + this.state.patch({ captureState: aggregateCaptureState(media) }); this.state.patch({ label: resolveText(this.getLabel(this.state.current)) }); return this.state.current; diff --git a/packages/core/src/core/ui/capture-placeholder/tests/capture-placeholder-core.test.ts b/packages/core/src/core/ui/capture-placeholder/tests/capture-placeholder-core.test.ts index 18aada3bd9..f61cedbf9e 100644 --- a/packages/core/src/core/ui/capture-placeholder/tests/capture-placeholder-core.test.ts +++ b/packages/core/src/core/ui/capture-placeholder/tests/capture-placeholder-core.test.ts @@ -7,12 +7,15 @@ function createMediaState(overrides: Partial = {}): Med return { cameraActive: false, screenShareActive: false, + micActive: false, + micExplicit: false, cameraState: 'idle', screenShareState: 'idle', micState: 'idle', screenShareAvailability: 'available', toggleCamera: vi.fn(() => true), toggleScreenShare: vi.fn(() => true), + toggleMic: vi.fn(() => true), ...overrides, }; } @@ -44,6 +47,35 @@ describe('CapturePlaceholderCore', () => { expect(core.getState().captureState).toBe('active'); }); + it('clears the placeholder for a mic-only capture', () => { + const core = new CapturePlaceholderCore(); + core.setMedia(createMediaState({ micState: 'active', micActive: true, micExplicit: true })); + + const state = core.getState(); + expect(state.captureState).toBe('active'); + expect(state.label).toBe(''); + }); + + it('keeps the CTA up when only an implied mic is live', () => { + const core = new CapturePlaceholderCore(); + core.setMedia(createMediaState({ micState: 'active', micExplicit: false })); + + const state = core.getState(); + expect(state.captureState).toBe('idle'); + expect(state.label).toBe('Enable camera and microphone'); + }); + + it('shows permission guidance after a mic-only denial consumes the intent', () => { + // The acquire pipeline sets micActive back to false on denial while + // parking micState — the guidance must survive that consumption. + const core = new CapturePlaceholderCore(); + core.setMedia(createMediaState({ micState: 'denied', micExplicit: true })); + + const state = core.getState(); + expect(state.captureState).toBe('denied'); + expect(state.label).toBe('Camera and microphone access is blocked. Update your browser permissions to continue.'); + }); + it('prefers the more in-progress status when the two disagree', () => { const core = new CapturePlaceholderCore(); core.setMedia(createMediaState({ cameraState: 'idle', screenShareState: 'acquiring' })); diff --git a/packages/core/src/core/ui/enable-devices-button/enable-devices-button-core.ts b/packages/core/src/core/ui/enable-devices-button/enable-devices-button-core.ts index a59b6f143b..9b78bfe3a5 100644 --- a/packages/core/src/core/ui/enable-devices-button/enable-devices-button-core.ts +++ b/packages/core/src/core/ui/enable-devices-button/enable-devices-button-core.ts @@ -72,7 +72,7 @@ export class EnableDevicesButtonCore { const media = this.#media!; this.state.patch({ - captureState: aggregateCaptureState(media.cameraState, media.screenShareState), + captureState: aggregateCaptureState(media), // Disabled only while the CAMERA pipeline is mid-acquisition — the // sources are independently acquirable, so an open screen-share // picker must not grey out the camera CTA (matching activate()'s diff --git a/packages/core/src/core/ui/enable-devices-button/tests/enable-devices-button-core.test.ts b/packages/core/src/core/ui/enable-devices-button/tests/enable-devices-button-core.test.ts index f8c7c08670..3c46c7a59f 100644 --- a/packages/core/src/core/ui/enable-devices-button/tests/enable-devices-button-core.test.ts +++ b/packages/core/src/core/ui/enable-devices-button/tests/enable-devices-button-core.test.ts @@ -7,12 +7,15 @@ function createMediaState(overrides: Partial = {}): Med return { cameraActive: false, screenShareActive: false, + micActive: false, + micExplicit: false, cameraState: 'idle', screenShareState: 'idle', micState: 'idle', screenShareAvailability: 'available', toggleCamera: vi.fn(() => true), toggleScreenShare: vi.fn(() => true), + toggleMic: vi.fn(() => true), ...overrides, }; } @@ -50,6 +53,18 @@ describe('EnableDevicesButtonCore', () => { expect(core.getState().disabled).toBe(false); }); + it('reflects a mic-only capture as active', () => { + const core = new EnableDevicesButtonCore(); + core.setMedia(createMediaState({ micState: 'active', micActive: true, micExplicit: true })); + expect(core.getState().captureState).toBe('active'); + }); + + it('ignores an implied mic when reporting the capture state', () => { + const core = new EnableDevicesButtonCore(); + core.setMedia(createMediaState({ micState: 'active', micExplicit: false })); + expect(core.getState().captureState).toBe('idle'); + }); + it('is disabled via props', () => { const core = new EnableDevicesButtonCore({ disabled: true }); core.setMedia(createMediaState()); diff --git a/packages/core/src/core/ui/publish-button/publish-button-core.ts b/packages/core/src/core/ui/publish-button/publish-button-core.ts index 5c675bd925..a88c3b0ed2 100644 --- a/packages/core/src/core/ui/publish-button/publish-button-core.ts +++ b/packages/core/src/core/ui/publish-button/publish-button-core.ts @@ -21,7 +21,7 @@ export interface PublishButtonProps { * store slices. */ export type PublishButtonMediaState = MediaPublishState & - Pick; + Pick; export interface PublishButtonState extends ButtonState { /** Current publish session lifecycle. */ @@ -82,7 +82,7 @@ export class PublishButtonCore { getState(): PublishButtonState { const media = this.#media!; const session = media.publishState; - const captureState = aggregateCaptureState(media.cameraState, media.screenShareState); + const captureState = aggregateCaptureState(media); this.state.patch({ session, @@ -104,7 +104,7 @@ export class PublishButtonCore { } if (session === 'stopping') return; - if (aggregateCaptureState(media.cameraState, media.screenShareState) !== 'active') return; + if (aggregateCaptureState(media) !== 'active') return; try { // idle/error → start (or retry) a session. diff --git a/packages/core/src/core/ui/publish-button/tests/publish-button-core.test.ts b/packages/core/src/core/ui/publish-button/tests/publish-button-core.test.ts index 70487827fa..adb288b738 100644 --- a/packages/core/src/core/ui/publish-button/tests/publish-button-core.test.ts +++ b/packages/core/src/core/ui/publish-button/tests/publish-button-core.test.ts @@ -11,6 +11,8 @@ function createMediaState(overrides: Partial = {}): Pub unpublish: vi.fn(), cameraState: 'active', screenShareState: 'idle', + micState: 'idle', + micExplicit: false, ...overrides, }; } @@ -53,6 +55,24 @@ describe('PublishButtonCore', () => { expect(core.getState().disabled).toBe(false); }); + it('is enabled when the explicit mic is the only active source', () => { + const core = new PublishButtonCore(); + core.setMedia(createMediaState({ cameraState: 'idle', micState: 'active', micExplicit: true })); + expect(core.getState().disabled).toBe(false); + }); + + it('stays disabled on an implied mic — video-driven audio must not justify publish on its own', () => { + const core = new PublishButtonCore(); + core.setMedia(createMediaState({ cameraState: 'idle', micState: 'active', micExplicit: false })); + expect(core.getState().disabled).toBe(true); + }); + + it('stays disabled on mic denial residue after the intent is consumed', () => { + const core = new PublishButtonCore(); + core.setMedia(createMediaState({ cameraState: 'idle', micState: 'denied', micExplicit: true })); + expect(core.getState().disabled).toBe(true); + }); + it('is disabled while connecting', () => { const core = new PublishButtonCore(); core.setMedia(createMediaState({ publishState: 'connecting' })); @@ -198,6 +218,24 @@ describe('PublishButtonCore', () => { expect(media.publish).not.toHaveBeenCalled(); }); + it('publishes from a mic-only capture', async () => { + const core = new PublishButtonCore(); + const media = createMediaState({ cameraState: 'idle', micState: 'active', micExplicit: true }); + + await core.toggle(media); + + expect(media.publish).toHaveBeenCalled(); + }); + + it('does not publish on an implied mic alone', async () => { + const core = new PublishButtonCore(); + const media = createMediaState({ cameraState: 'idle', micState: 'active', micExplicit: false }); + + await core.toggle(media); + + expect(media.publish).not.toHaveBeenCalled(); + }); + it('does nothing when disabled', async () => { const core = new PublishButtonCore({ disabled: true }); const media = createMediaState({ publishState: 'live' }); diff --git a/packages/core/src/core/ui/screen-share-button/tests/screen-share-button-core.test.ts b/packages/core/src/core/ui/screen-share-button/tests/screen-share-button-core.test.ts index c1703b9c72..558bcdd2a7 100644 --- a/packages/core/src/core/ui/screen-share-button/tests/screen-share-button-core.test.ts +++ b/packages/core/src/core/ui/screen-share-button/tests/screen-share-button-core.test.ts @@ -7,12 +7,15 @@ function createMediaState(overrides: Partial = {}): Med return { cameraActive: true, screenShareActive: false, + micActive: false, + micExplicit: false, cameraState: 'active', screenShareState: 'idle', micState: 'idle', screenShareAvailability: 'available', toggleCamera: vi.fn(() => true), toggleScreenShare: vi.fn(() => true), + toggleMic: vi.fn(() => true), ...overrides, }; } diff --git a/packages/core/src/core/ui/utils/aggregate-capture-state.ts b/packages/core/src/core/ui/utils/aggregate-capture-state.ts index 492e7127e3..f2805d9b25 100644 --- a/packages/core/src/core/ui/utils/aggregate-capture-state.ts +++ b/packages/core/src/core/ui/utils/aggregate-capture-state.ts @@ -1,14 +1,38 @@ -import type { MediaCaptureState } from '@videojs/media'; +import type { MediaCaptureSourceState, MediaCaptureState } from '@videojs/media'; /** - * Aggregate the camera and screen-share pipelines' independent lifecycles - * into the one status a capture-gated control reacts to: active if either - * source is, else the more "in-progress" of the two — `acquiring` > - * `denied` > `ended` > `idle` — matching the precedence a single exclusive - * source used to have before capture became additive. + * Precedence for the aggregate status: active if any counted source is, + * else the more "in-progress" of them — `acquiring` > `denied` > `ended` > + * `idle` — matching the precedence a single exclusive source used to have + * before capture became additive. */ const STATUS_PRECEDENCE: readonly MediaCaptureState[] = ['active', 'acquiring', 'denied', 'ended', 'idle']; -export function aggregateCaptureState(camera: MediaCaptureState, screen: MediaCaptureState): MediaCaptureState { - return STATUS_PRECEDENCE.find((status) => status === camera || status === screen) ?? 'idle'; +/** The capture-source fields the aggregation reads. */ +export type AggregatableCaptureSource = Pick< + MediaCaptureSourceState, + 'cameraState' | 'screenShareState' | 'micState' | 'micExplicit' +>; + +/** + * Aggregate the capture pipelines' independent lifecycles into the one + * status a capture-gated control reacts to. The mic counts only while + * `micExplicit` claims its lifecycle for an explicit request — the same + * rule the publish engine applies to its session gate: an implied mic + * (acquired as a side effect of video intent) must not surface capture + * feedback the video pipelines don't justify, whether an `active` that + * would enable publish controls (e.g. a mic outliving a dismissed screen + * picker by a beat) or a `denied` that would blame permissions a + * camera-only page never asked for. Keyed on `micExplicit` rather than + * `micActive` because the intent slot is consumed on terminal outcomes + * while the state stays parked precisely so UIs can say why an explicit + * capture stopped. + */ +export function aggregateCaptureState(source: AggregatableCaptureSource): MediaCaptureState { + const micState = source.micExplicit ? source.micState : 'idle'; + return ( + STATUS_PRECEDENCE.find( + (status) => status === source.cameraState || status === source.screenShareState || status === micState + ) ?? 'idle' + ); } diff --git a/packages/core/src/core/ui/utils/tests/aggregate-capture-state.test.ts b/packages/core/src/core/ui/utils/tests/aggregate-capture-state.test.ts index c3fa0df7bd..dc393d7e17 100644 --- a/packages/core/src/core/ui/utils/tests/aggregate-capture-state.test.ts +++ b/packages/core/src/core/ui/utils/tests/aggregate-capture-state.test.ts @@ -1,37 +1,81 @@ import type { MediaCaptureState } from '@videojs/media'; import { describe, expect, it } from 'vitest'; +import type { AggregatableCaptureSource } from '../aggregate-capture-state'; import { aggregateCaptureState } from '../aggregate-capture-state'; // Highest to lowest rank, mirroring the precedence documented on // aggregateCaptureState: active > acquiring > denied > ended > idle. const PRECEDENCE: readonly MediaCaptureState[] = ['active', 'acquiring', 'denied', 'ended', 'idle']; +function source(overrides: Partial = {}): AggregatableCaptureSource { + return { + cameraState: 'idle', + screenShareState: 'idle', + micState: 'idle', + micExplicit: false, + ...overrides, + }; +} + describe('aggregateCaptureState', () => { - it('picks the higher-ranked state regardless of which side holds it', () => { + it('picks the higher-ranked video state regardless of which side holds it', () => { for (const [i, higher] of PRECEDENCE.entries()) { for (const lower of PRECEDENCE.slice(i + 1)) { - expect(aggregateCaptureState(higher, lower)).toBe(higher); - expect(aggregateCaptureState(lower, higher)).toBe(higher); + expect(aggregateCaptureState(source({ cameraState: higher, screenShareState: lower }))).toBe(higher); + expect(aggregateCaptureState(source({ cameraState: lower, screenShareState: higher }))).toBe(higher); } } }); - it('returns the shared state when both sides match', () => { + it('returns the shared state when both video sides match', () => { for (const status of PRECEDENCE) { - expect(aggregateCaptureState(status, status)).toBe(status); + expect(aggregateCaptureState(source({ cameraState: status, screenShareState: status }))).toBe(status); } }); // Called out explicitly in review: acquiring must win even though it // is the camera's less "bad" state than the screen's denial. it('camera denied + screen acquiring resolves to acquiring', () => { - expect(aggregateCaptureState('denied', 'acquiring')).toBe('acquiring'); - expect(aggregateCaptureState('acquiring', 'denied')).toBe('acquiring'); + expect(aggregateCaptureState(source({ cameraState: 'denied', screenShareState: 'acquiring' }))).toBe('acquiring'); + expect(aggregateCaptureState(source({ cameraState: 'acquiring', screenShareState: 'denied' }))).toBe('acquiring'); }); it('denied outranks ended', () => { - expect(aggregateCaptureState('denied', 'ended')).toBe('denied'); - expect(aggregateCaptureState('ended', 'denied')).toBe('denied'); + expect(aggregateCaptureState(source({ cameraState: 'denied', screenShareState: 'ended' }))).toBe('denied'); + expect(aggregateCaptureState(source({ cameraState: 'ended', screenShareState: 'denied' }))).toBe('denied'); + }); + + it('counts the mic like a video pipeline when its lifecycle is explicitly claimed', () => { + for (const status of PRECEDENCE) { + expect(aggregateCaptureState(source({ micState: status, micExplicit: true }))).toBe(status); + } + }); + + it('mic-only acquiring outranks a denied video pipeline', () => { + expect(aggregateCaptureState(source({ cameraState: 'denied', micState: 'acquiring', micExplicit: true }))).toBe( + 'acquiring' + ); + }); + + // The parked terminal residue of a mic-only attempt — micActive already + // consumed, micExplicit latched by the store feature — must keep + // surfacing so a denied voice-only page can explain itself. + it('counts the explicit mic terminal residue after the intent is consumed', () => { + expect(aggregateCaptureState(source({ micState: 'denied', micExplicit: true }))).toBe('denied'); + expect(aggregateCaptureState(source({ micState: 'ended', micExplicit: true }))).toBe('ended'); + }); + + // The load-bearing rule: an implied mic (acquired as a side effect of + // video intent) must never surface capture feedback on its own — neither + // an 'active' that would enable publish controls (a mic outliving a + // dismissed screen picker by a beat) nor a 'denied' that would blame + // permissions a camera-only page never asked for. + it('ignores an implied mic entirely', () => { + for (const status of PRECEDENCE) { + expect(aggregateCaptureState(source({ micState: status }))).toBe('idle'); + } + expect(aggregateCaptureState(source({ cameraState: 'ended', micState: 'active' }))).toBe('ended'); + expect(aggregateCaptureState(source({ cameraState: 'acquiring', micState: 'denied' }))).toBe('acquiring'); }); }); diff --git a/packages/core/src/dom/store/features/capture-source.ts b/packages/core/src/dom/store/features/capture-source.ts index f454eedb52..a0df9dd120 100644 --- a/packages/core/src/dom/store/features/capture-source.ts +++ b/packages/core/src/dom/store/features/capture-source.ts @@ -9,6 +9,8 @@ export const captureSourceFeature = definePlayerFeature({ state: ({ target }): MediaCaptureSourceState => ({ cameraActive: false, screenShareActive: false, + micActive: false, + micExplicit: false, cameraState: 'idle', screenShareState: 'idle', micState: 'idle', @@ -29,6 +31,18 @@ export const captureSourceFeature = definePlayerFeature({ media.screenShareActive = next; return next; }, + + toggleMic() { + const { media } = target(); + // The contract keeps `micActive` optional because the capability + // predicate admits older hosts without the slot — writing one there + // would create an inert expando that sync() reads back as real + // intent. + if (!isMediaCaptureSourceCapable(media) || !('micActive' in media)) return false; + const next = !media.micActive; + media.micActive = next; + return next; + }, }), attach({ target, signal, set }) { @@ -40,18 +54,35 @@ export const captureSourceFeature = definePlayerFeature({ screenShareAvailability: canScreenShare() ? 'available' : 'unsupported', }); + // Provenance latch behind `micExplicit`: the pipeline consumes + // `micActive` on `denied`/`ended` while parking `micState` there, so + // the explicit claim must survive that consumption — and reset the + // moment a new (implied) lifecycle starts, so a video-driven mic never + // inherits it. Known boundary: an explicit attempt that terminates + // before this feature attaches (persisted denial rejecting before a + // React passive effect runs) reads as implied on the first sync — the + // host would have to persist provenance for the latch to recover it. + let micExplicit = false; + // Defaulted reads: the capability predicate checks presence of the // core fields, not the whole widened contract, so a media host from // an older generation may lack e.g. `micState` — the slice must never // hold `undefined` where UIs expect a lifecycle value. - const sync = () => + const sync = () => { + const micActive = media.micActive ?? false; + const micState = media.micState ?? 'idle'; + if (micActive) micExplicit = true; + else if (micState !== 'denied' && micState !== 'ended') micExplicit = false; set({ cameraActive: media.cameraActive ?? false, screenShareActive: media.screenShareActive ?? false, + micActive, + micExplicit, cameraState: media.cameraState ?? 'idle', screenShareState: media.screenShareState ?? 'idle', - micState: media.micState ?? 'idle', + micState, }); + }; sync(); diff --git a/packages/core/src/dom/store/features/tests/capture-source.test.ts b/packages/core/src/dom/store/features/tests/capture-source.test.ts index ba94cba996..c3401aeaa4 100644 --- a/packages/core/src/dom/store/features/tests/capture-source.test.ts +++ b/packages/core/src/dom/store/features/tests/capture-source.test.ts @@ -8,6 +8,7 @@ import { captureSourceFeature } from '../capture-source'; interface CaptureSourceCapableMedia extends EventTarget { cameraActive: boolean; screenShareActive: boolean; + micActive: boolean; cameraState: MediaCaptureState; screenShareState: MediaCaptureState; micState: MediaCaptureState; @@ -17,6 +18,7 @@ function createCaptureMedia(initial: Partial = {}): C const media = new EventTarget() as CaptureSourceCapableMedia; media.cameraActive = initial.cameraActive ?? false; media.screenShareActive = initial.screenShareActive ?? false; + media.micActive = initial.micActive ?? false; media.cameraState = initial.cameraState ?? 'idle'; media.screenShareState = initial.screenShareState ?? 'idle'; media.micState = initial.micState ?? 'idle'; @@ -56,6 +58,7 @@ describe('captureSourceFeature', () => { expect(store.toggleCamera()).toBe(false); expect(store.toggleScreenShare()).toBe(false); + expect(store.toggleMic()).toBe(false); }); }); @@ -123,16 +126,30 @@ describe('captureSourceFeature', () => { it('defaults widened-contract fields an older media host lacks instead of storing undefined', () => { const media = createCaptureMedia({ cameraActive: true, cameraState: 'active' }); // The capability predicate checks the core fields only — a host - // predating micState still passes it. + // predating micState/micActive still passes it. delete (media as { micState?: unknown }).micState; + delete (media as { micActive?: unknown }).micActive; const store = createStore()(captureSourceFeature); store.attach({ media: media as unknown as PlayerTarget['media'], container: null }); expect(store.state.micState).toBe('idle'); + expect(store.state.micActive).toBe(false); expect(store.state.cameraState).toBe('active'); }); + it('`toggleMic()` refuses a host without a mic intent slot instead of writing an inert one', () => { + const media = createCaptureMedia(); + delete (media as { micActive?: unknown }).micActive; + + const store = createStore()(captureSourceFeature); + store.attach({ media: media as unknown as PlayerTarget['media'], container: null }); + + expect(store.toggleMic()).toBe(false); + // An expando here would sync back as real intent on the next event. + expect('micActive' in media).toBe(false); + }); + it('syncs the mic pipeline lifecycle on `capturestatechange`', () => { const media = createCaptureMedia({ cameraActive: true, micState: 'acquiring' }); @@ -186,5 +203,83 @@ describe('captureSourceFeature', () => { expect(store.toggleScreenShare()).toBe(true); expect(media.screenShareActive).toBe(true); }); + + it('re-reads the mic intent on `capturesourcechange`', () => { + const media = createCaptureMedia(); + + const store = createStore()(captureSourceFeature); + store.attach({ media: media as unknown as PlayerTarget['media'], container: null }); + + media.micActive = true; + media.dispatchEvent(new Event('capturesourcechange')); + + expect(store.state.micActive).toBe(true); + expect(store.state.micExplicit).toBe(true); + }); + + it('latches `micExplicit` across intent consumption on a terminal outcome', () => { + const media = createCaptureMedia({ micActive: true, micState: 'acquiring' }); + + const store = createStore()(captureSourceFeature); + store.attach({ media: media as unknown as PlayerTarget['media'], container: null }); + expect(store.state.micExplicit).toBe(true); + + // The pipeline consumes the intent on denial while parking the state. + media.micActive = false; + media.micState = 'denied'; + media.dispatchEvent(new Event('capturestatechange')); + + expect(store.state.micActive).toBe(false); + expect(store.state.micExplicit).toBe(true); + }); + + it('never claims an implied mic lifecycle as explicit', () => { + const media = createCaptureMedia({ cameraActive: true, micState: 'acquiring' }); + + const store = createStore()(captureSourceFeature); + store.attach({ media: media as unknown as PlayerTarget['media'], container: null }); + expect(store.state.micExplicit).toBe(false); + + media.micState = 'denied'; + media.dispatchEvent(new Event('capturestatechange')); + + expect(store.state.micExplicit).toBe(false); + }); + + it('resets the explicit claim when a new implied lifecycle starts', () => { + const media = createCaptureMedia({ micActive: true, micState: 'acquiring' }); + + const store = createStore()(captureSourceFeature); + store.attach({ media: media as unknown as PlayerTarget['media'], container: null }); + + media.micActive = false; + media.micState = 'denied'; + media.dispatchEvent(new Event('capturestatechange')); + expect(store.state.micExplicit).toBe(true); + + // Video intent re-fires the mic pipeline over the parked denial — + // the fresh attempt is implied, so the explicit claim must not leak + // onto it. + media.cameraActive = true; + media.micState = 'acquiring'; + media.dispatchEvent(new Event('capturestatechange')); + + expect(store.state.micExplicit).toBe(false); + }); + + it('`toggleMic()` flips the media mic intent without touching the video intents', () => { + const media = createCaptureMedia({ cameraActive: true }); + + const store = createStore()(captureSourceFeature); + store.attach({ media: media as unknown as PlayerTarget['media'], container: null }); + + expect(store.toggleMic()).toBe(true); + expect(media.micActive).toBe(true); + expect(media.cameraActive).toBe(true); + + expect(store.toggleMic()).toBe(false); + expect(media.micActive).toBe(false); + expect(media.cameraActive).toBe(true); + }); }); }); diff --git a/packages/core/src/dom/store/selectors.ts b/packages/core/src/dom/store/selectors.ts index cf6cf4baca..4f3b79c9b8 100644 --- a/packages/core/src/dom/store/selectors.ts +++ b/packages/core/src/dom/store/selectors.ts @@ -29,7 +29,7 @@ export const selectAudioTrack = createSelector(audioTrackFeature); export const selectBuffer = createSelector(bufferFeature); /** Select the capture devices state (cameras, microphones, selections). */ export const selectCaptureDevices = createSelector(captureDevicesFeature); -/** Select the capture source state (camera/screen active, camera/screen state, screen share availability, toggle actions). */ +/** Select the capture source state (camera/screen/mic intents, pipeline states, screen share availability, toggle actions). */ export const selectCaptureSource = createSelector(captureSourceFeature); /** Select the capture tracks state (cameraMuted, micMuted, set/toggle actions). */ export const selectCaptureTracks = createSelector(captureTracksFeature); diff --git a/packages/html/src/ui/capture-placeholder/tests/capture-placeholder-element.test.ts b/packages/html/src/ui/capture-placeholder/tests/capture-placeholder-element.test.ts index 28f1fece6d..1c2305a4e4 100644 --- a/packages/html/src/ui/capture-placeholder/tests/capture-placeholder-element.test.ts +++ b/packages/html/src/ui/capture-placeholder/tests/capture-placeholder-element.test.ts @@ -39,12 +39,15 @@ function createCaptureSourceStore(initial: Partial = {} state: () => ({ cameraActive: false, screenShareActive: false, + micActive: false, + micExplicit: false, cameraState: 'idle', screenShareState: 'idle', micState: 'idle', screenShareAvailability: 'available', toggleCamera: vi.fn(() => true), toggleScreenShare: vi.fn(() => true), + toggleMic: vi.fn(() => true), ...initial, }), attach: (context) => { @@ -128,4 +131,38 @@ describe('CapturePlaceholderElement', () => { expect(placeholder.hasAttribute('aria-label')).toBe(false); expect(placeholder.getAttribute('data-capture-state')).toBe('denied'); }); + + it('reports a mic-only capture as active and clears the guidance', async () => { + const { placeholder, setState } = setup(); + + await placeholder.updateComplete; + + setState({ micState: 'active', micActive: true, micExplicit: true }); + await placeholder.updateComplete; + + expect(placeholder.getAttribute('data-capture-state')).toBe('active'); + expect(placeholder.textContent).toBe(''); + + // An implied mic (video intent gone, mic lingering) must not keep the + // placeholder cleared on its own. + setState({ micActive: false, micExplicit: false }); + await placeholder.updateComplete; + + expect(placeholder.getAttribute('data-capture-state')).toBe('idle'); + expect(placeholder.textContent).toBe('Enable camera and microphone'); + }); + + it('keeps permission guidance after a mic-only denial consumes the intent', async () => { + const { placeholder, setState } = setup(); + + await placeholder.updateComplete; + + setState({ micState: 'denied', micActive: false, micExplicit: true }); + await placeholder.updateComplete; + + expect(placeholder.getAttribute('data-capture-state')).toBe('denied'); + expect(placeholder.textContent).toBe( + 'Camera and microphone access is blocked. Update your browser permissions to continue.' + ); + }); }); diff --git a/packages/html/src/ui/publish-button/publish-button-element.ts b/packages/html/src/ui/publish-button/publish-button-element.ts index f70f7219d3..3a0d31bb3b 100644 --- a/packages/html/src/ui/publish-button/publish-button-element.ts +++ b/packages/html/src/ui/publish-button/publish-button-element.ts @@ -139,6 +139,8 @@ export class PublishButtonElement extends MediaElement { unpublish: publish.unpublish, cameraState: captureSource.cameraState, screenShareState: captureSource.screenShareState, + micState: captureSource.micState, + micExplicit: captureSource.micExplicit, }; } } diff --git a/packages/html/src/ui/publish-button/tests/publish-button-element.test.ts b/packages/html/src/ui/publish-button/tests/publish-button-element.test.ts index 336aba4021..41f65af386 100644 --- a/packages/html/src/ui/publish-button/tests/publish-button-element.test.ts +++ b/packages/html/src/ui/publish-button/tests/publish-button-element.test.ts @@ -32,11 +32,17 @@ type PublisherSliceState = MediaPublishState & MediaCaptureSourceState; function createPublisherStore({ publishState = 'idle', cameraState = 'active', + micState = 'idle', + micActive = false, + micExplicit = false, publish = vi.fn(() => Promise.resolve()), unpublish = vi.fn(), }: { publishState?: MediaPublishState['publishState'] | undefined; cameraState?: MediaCaptureSourceState['cameraState'] | undefined; + micState?: MediaCaptureSourceState['micState'] | undefined; + micActive?: MediaCaptureSourceState['micActive'] | undefined; + micExplicit?: MediaCaptureSourceState['micExplicit'] | undefined; publish?: MediaPublishState['publish'] | undefined; unpublish?: MediaPublishState['unpublish'] | undefined; } = {}): AnyPlayerStore { @@ -48,14 +54,17 @@ function createPublisherStore({ publishError: null, publish, unpublish, - cameraActive: true, + cameraActive: cameraState === 'active', screenShareActive: false, + micActive, + micExplicit, cameraState, screenShareState: 'idle', - micState: 'idle', + micState, screenShareAvailability: 'unavailable', toggleCamera: vi.fn(() => false), toggleScreenShare: vi.fn(() => false), + toggleMic: vi.fn(() => false), }), }) as unknown as AnyPlayerStore; } @@ -149,4 +158,37 @@ describe('PublishButtonElement', () => { expect(publish).not.toHaveBeenCalled(); }); + + it('enables and starts a session from a mic-only capture', async () => { + const publish = vi.fn(() => Promise.resolve()); + const { button } = setup({ cameraState: 'idle', micState: 'active', micActive: true, micExplicit: true, publish }); + + await button.updateComplete; + + expect(button.hasAttribute('aria-disabled')).toBe(false); + expect(button.hasAttribute('data-disabled')).toBe(false); + + click(button); + + expect(publish).toHaveBeenCalledTimes(1); + }); + + it('stays disabled on an implied mic without explicit intent', async () => { + const publish = vi.fn(() => Promise.resolve()); + const { button } = setup({ + cameraState: 'idle', + micState: 'active', + micActive: false, + micExplicit: false, + publish, + }); + + await button.updateComplete; + + expect(button.getAttribute('aria-disabled')).toBe('true'); + + click(button); + + expect(publish).not.toHaveBeenCalled(); + }); }); diff --git a/packages/media/src/core/state.ts b/packages/media/src/core/state.ts index 3acf225e53..a7d21c6115 100644 --- a/packages/media/src/core/state.ts +++ b/packages/media/src/core/state.ts @@ -393,11 +393,20 @@ export interface MediaCaptureSourceState { cameraActive: boolean; /** Whether screen share is an active capture source. */ screenShareActive: boolean; + /** Whether the mic is an explicit capture source (audio-only; video intent still implies the mic). */ + micActive: boolean; + /** + * Whether the lifecycle in `micState` — including a terminal + * `denied`/`ended` parked after the pipeline consumed `micActive` — + * belongs to an explicitly requested mic. Stays `false` for a mic + * acquired only as a side effect of video intent. + */ + micExplicit: boolean; /** Camera pipeline lifecycle. */ cameraState: MediaCaptureState; /** Screen-share pipeline lifecycle. */ screenShareState: MediaCaptureState; - /** Microphone pipeline lifecycle (read-only; the mic has no intent slot). */ + /** Microphone pipeline lifecycle. */ micState: MediaCaptureState; /** Whether screen capture can be requested on this platform. */ screenShareAvailability: MediaFeatureAvailability; @@ -405,6 +414,8 @@ export interface MediaCaptureSourceState { toggleCamera(): boolean; /** Toggle screen share on or off. Returns `true` when sharing. */ toggleScreenShare(): boolean; + /** Toggle the explicit mic intent (prompting for permission as needed). Returns `true` when acquiring. */ + toggleMic(): boolean; } export interface MediaCaptureDevicesState { diff --git a/packages/media/src/core/tests/predicate.test.ts b/packages/media/src/core/tests/predicate.test.ts index 71b6609cbd..03814e30e1 100644 --- a/packages/media/src/core/tests/predicate.test.ts +++ b/packages/media/src/core/tests/predicate.test.ts @@ -82,6 +82,21 @@ describe('isMediaCaptureSourceCapable', () => { it('rejects media without a cameraState', () => { expect(isMediaCaptureSourceCapable({ cameraActive: true, screenShareState: 'idle' })).toBe(false); }); + + // A host from the generation that reports the mic lifecycle but predates + // the audio-only intent slot stays capture-capable — which is why the + // contract keeps `micActive` optional: writers must check presence, not + // trust this narrowing. + it('admits hosts with a mic lifecycle but no mic intent slot', () => { + expect( + isMediaCaptureSourceCapable({ + cameraActive: true, + cameraState: 'active', + screenShareState: 'idle', + micState: 'denied', + }) + ).toBe(true); + }); }); describe('isMediaCaptureDevicesCapable', () => { diff --git a/packages/media/src/core/types.ts b/packages/media/src/core/types.ts index a492d8daf8..d27a64abc8 100644 --- a/packages/media/src/core/types.ts +++ b/packages/media/src/core/types.ts @@ -625,12 +625,13 @@ export interface MediaCaptureSourceEvents { } /** - * Camera and screen-share acquisition — additive, not exclusive: starting - * a share never releases the camera, and either can be toggled - * independently. The microphone has no intent slot of its own: it is - * acquired while either video source is active (keyed for re-acquisition - * on {@link MediaCaptureDevicesCapability.audioInputDeviceId}), and only - * its lifecycle is readable here. + * Camera, screen-share, and microphone acquisition — additive, not + * exclusive: activating any source never releases another, and each can be + * toggled independently. The microphone is also implied by video intent: + * it is acquired while either video source is active (keyed for + * re-acquisition on + * {@link MediaCaptureDevicesCapability.audioInputDeviceId}), so + * {@link micActive} only needs to be written for an audio-only capture. * * The intent slots are consumed by the pipeline on terminal outcomes: * after a permission denial or an out-of-band end (device unplugged, @@ -643,6 +644,17 @@ export interface MediaCaptureSourceCapability { cameraActive: boolean; /** Screen-share acquisition; `true` opens the OS picker, `false` stops sharing. Fires `capturesourcechange`. */ screenShareActive: boolean; + /** + * Microphone acquisition without a video source — the audio-only capture + * seam. Either video source active still implies the mic; this is + * acquisition intent, not a mute. Fires `capturesourcechange`. + * + * Optional because {@link isMediaCaptureSourceCapable} deliberately + * admits hosts from before this generation, which lack the slot — check + * presence before writing; an assignment to a host without it is an + * inert expando, not an acquisition. + */ + micActive?: boolean; /** Camera pipeline lifecycle. Fires `capturestatechange`. */ readonly cameraState: MediaCaptureState; /** Screen-share pipeline lifecycle. Fires `capturestatechange`. */ diff --git a/packages/react/src/ui/capture-placeholder/tests/capture-placeholder.test.tsx b/packages/react/src/ui/capture-placeholder/tests/capture-placeholder.test.tsx index 018736b8e7..63087fedf7 100644 --- a/packages/react/src/ui/capture-placeholder/tests/capture-placeholder.test.tsx +++ b/packages/react/src/ui/capture-placeholder/tests/capture-placeholder.test.tsx @@ -9,16 +9,24 @@ afterEach(() => { cleanup(); }); -function createWrapper({ captureState = 'idle' as MediaCaptureState } = {}) { +function createWrapper({ + captureState = 'idle' as MediaCaptureState, + micState = 'idle' as MediaCaptureState, + micActive = false, + micExplicit = false, +} = {}) { return createPlayerWrapper({ cameraActive: false, screenShareActive: false, + micActive, + micExplicit, cameraState: captureState, screenShareState: 'idle', - micState: 'idle', + micState, screenShareAvailability: 'available', toggleCamera: vi.fn(() => true), toggleScreenShare: vi.fn(() => true), + toggleMic: vi.fn(() => true), }).Wrapper; } @@ -48,4 +56,36 @@ describe('CapturePlaceholder', () => { expect(placeholder.textContent).toBe('Custom content'); expect(placeholder.hasAttribute('aria-label')).toBe(false); }); + + it('reports a mic-only capture as active and clears the guidance', () => { + const Wrapper = createWrapper({ micState: 'active', micActive: true, micExplicit: true }); + + render(, { wrapper: Wrapper }); + + const placeholder = screen.getByTestId('placeholder'); + expect(placeholder.getAttribute('data-capture-state')).toBe('active'); + expect(placeholder.textContent).toBe(''); + }); + + it('keeps the guidance up when only an implied mic is live', () => { + const Wrapper = createWrapper({ micState: 'active', micActive: false, micExplicit: false }); + + render(, { wrapper: Wrapper }); + + const placeholder = screen.getByTestId('placeholder'); + expect(placeholder.getAttribute('data-capture-state')).toBe('idle'); + expect(placeholder.textContent).toBe('Enable camera and microphone'); + }); + + it('keeps permission guidance after a mic-only denial consumes the intent', () => { + const Wrapper = createWrapper({ micState: 'denied', micActive: false, micExplicit: true }); + + render(, { wrapper: Wrapper }); + + const placeholder = screen.getByTestId('placeholder'); + expect(placeholder.getAttribute('data-capture-state')).toBe('denied'); + expect(placeholder.textContent).toBe( + 'Camera and microphone access is blocked. Update your browser permissions to continue.' + ); + }); }); diff --git a/packages/react/src/ui/publish-button/publish-button.tsx b/packages/react/src/ui/publish-button/publish-button.tsx index c8e0346fd4..ebb0b91590 100644 --- a/packages/react/src/ui/publish-button/publish-button.tsx +++ b/packages/react/src/ui/publish-button/publish-button.tsx @@ -53,6 +53,8 @@ export const PublishButton = forwardRef( unpublish: publish.unpublish, cameraState: captureSource.cameraState, screenShareState: captureSource.screenShareState, + micState: captureSource.micState, + micExplicit: captureSource.micExplicit, } : null; diff --git a/packages/react/src/ui/publish-button/tests/publish-button.test.tsx b/packages/react/src/ui/publish-button/tests/publish-button.test.tsx index d0cc3a3c33..f57d1e48b4 100644 --- a/packages/react/src/ui/publish-button/tests/publish-button.test.tsx +++ b/packages/react/src/ui/publish-button/tests/publish-button.test.tsx @@ -10,6 +10,9 @@ afterEach(cleanup); function createWrapper({ publishState = 'idle' as MediaPublishSessionState, captureState = 'active' as MediaCaptureState, + micState = 'idle' as MediaCaptureState, + micActive = false, + micExplicit = false, publish = vi.fn(() => Promise.resolve()), unpublish = vi.fn(), } = {}) { @@ -22,12 +25,15 @@ function createWrapper({ // `captureSource` feature slice cameraActive: captureState === 'active', screenShareActive: false, + micActive, + micExplicit, cameraState: captureState, screenShareState: 'idle', - micState: 'idle', + micState, screenShareAvailability: 'available', toggleCamera: vi.fn(), toggleScreenShare: vi.fn(), + toggleMic: vi.fn(), }); return { Wrapper, publish, unpublish }; @@ -58,6 +64,41 @@ describe('PublishButton', () => { expect(publish).not.toHaveBeenCalled(); }); + it('enables and starts a session from a mic-only capture', () => { + const { Wrapper, publish } = createWrapper({ + captureState: 'idle', + micState: 'active', + micActive: true, + micExplicit: true, + }); + + render(, { wrapper: Wrapper }); + + const button = screen.getByTestId('publish'); + expect(button.hasAttribute('aria-disabled')).toBe(false); + expect(button.hasAttribute('data-disabled')).toBe(false); + + fireEvent.click(button); + expect(publish).toHaveBeenCalledTimes(1); + }); + + it('stays disabled on an implied mic without explicit intent', () => { + const { Wrapper, publish } = createWrapper({ + captureState: 'idle', + micState: 'active', + micActive: false, + micExplicit: false, + }); + + render(, { wrapper: Wrapper }); + + const button = screen.getByTestId('publish'); + expect(button.getAttribute('aria-disabled')).toBe('true'); + + fireEvent.click(button); + expect(publish).not.toHaveBeenCalled(); + }); + it('starts a session when activated while idle with active capture', () => { const { Wrapper, publish, unpublish } = createWrapper();