From 58480890b1d8ca2cfdedbec6a2003b4684240ce1 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 00:47:11 +0000 Subject: [PATCH 01/51] Show call controls in the call window only The main window's call bar now shows the phone icon, the room, the phase and a "Call window" button. The mute, deafen, camera, screen and leave buttons, the volume slider, the level meter, the participants and the video tiles show only in the call window. When the call window cannot open for a call, the bar shows all of them again, so the call can still be muted or left. Co-Authored-By: Claude Opus 5.5 --- ...60-show-calls-in-a-separate-call-window.md | 13 +++++++-- frontend/src/App.svelte | 28 +++++++++++++++---- frontend/src/CallBar.svelte | 23 +++++++++++---- frontend/src/bridge/index.ts | 3 +- frontend/tests/render.test.mjs | 25 +++++++++++++++-- frontend/tests/video.test.mjs | 4 +++ 6 files changed, 81 insertions(+), 15 deletions(-) diff --git a/docs/adr/0060-show-calls-in-a-separate-call-window.md b/docs/adr/0060-show-calls-in-a-separate-call-window.md index 2b7d59d0..1001d425 100644 --- a/docs/adr/0060-show-calls-in-a-separate-call-window.md +++ b/docs/adr/0060-show-calls-in-a-separate-call-window.md @@ -24,8 +24,9 @@ than a call needs? * Keep the web view keyless (ADR-0004), with explicit commands per window. * Keep the main window's navigation, new-window and capture rules for the new window. -* Keep the call bar in the main window, so the call can be controlled when - the call window is closed. +* Keep a call bar in the main window, so the call window can be opened again + when it is closed, and the call can be controlled when the call window + cannot open. ## Considered Options @@ -52,6 +53,14 @@ commands. join, once for each call. The call bar has a "Call window" button that opens it again. It closes itself four seconds after the call ends. When the main window goes, the host closes it. +* On 25 November 2026 the owner asked to show the call's controls, video, + volume, level meter and participants in the call window only. While the + call window opens, the main window's call bar shows only the phone icon, + the room, the phase and the "Call window" button. When the call window + cannot open for the call, the call bar shows all of its controls and the + video tiles, so the call can still be muted or left. A later open that + works makes the bar short again. An ended call still shows its reason and + "Dismiss". * The host keeps each window's session, sound level and level channels under the window's label. Room subscriptions belong to the main window only. A call window that closes or reloads drops only its own channels. diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte index f68b77cc..80381d5a 100644 --- a/frontend/src/App.svelte +++ b/frontend/src/App.svelte @@ -775,11 +775,27 @@ // once per call: closing it during the call keeps it closed until the call // bar's "Call window" button. let callWindowFor = false; + // The call window could not open for this call. The main window then shows + // the call's controls and video itself; otherwise only the call window + // does. A later open that works hides them again. + let callWindowFailed = $state(false); + function showCallWindow() { + openCallWindow().then( + () => (callWindowFailed = false), + () => { + // A window that cannot open leaves the call here; say so, so no + // window is missed without a reason. + callWindowFailed = true; + error = CALL_WINDOW_UNAVAILABLE_TEXT; + } + ); + } $effect(() => { const joined = inCall(callState); - // A window that cannot open leaves the call here; say so, so no window - // is missed without a reason. - if (joined && !callWindowFor) void openCallWindow().catch(() => (error = CALL_WINDOW_UNAVAILABLE_TEXT)); + if (joined && !callWindowFor) { + callWindowFailed = false; + showCallWindow(); + } callWindowFor = joined; }); let callJoinText = $state(null); @@ -1204,6 +1220,7 @@ screenText = null; screenRequest += 1; callDismissed = false; + callWindowFailed = false; callNames = new Map(); callNamesFor = null; callRefresher.request(); @@ -3177,6 +3194,7 @@ void openCallWindow().catch(() => (error = CALL_WINDOW_UNAVAILABLE_TEXT))} + onwindow={showCallWindow} /> {#if cameraText} {/if} - {#if hasVideo(callState)} + {#if callWindowFailed && hasVideo(callState)} {/if} {#if selectedRoom} diff --git a/frontend/src/CallBar.svelte b/frontend/src/CallBar.svelte index 3df17364..e7715256 100644 --- a/frontend/src/CallBar.svelte +++ b/frontend/src/CallBar.svelte @@ -34,9 +34,15 @@ // core's codes show as fixed texts from calls.ts. The live region stays in // the page so that a change in it is announced. Speaking changes are not // announced: each participant's mark is read in place only. + // + // The call window holds the call's controls (ADR-0060). While it can open, + // the bar shows only the room, the phase and a "Call window" button. When + // it could not open (`full`), the bar shows every control, so the call can + // still be muted or left here. let { status, dismissed, + full, roomName, names, busy, @@ -55,6 +61,8 @@ }: { status: CallStatus; dismissed: boolean; + // The call window could not open: show the controls here. + full: boolean; roomName: string; // Display names from the call room's members, by user ID. names: ReadonlyMap; @@ -101,6 +109,11 @@ {#if ended} + {:else if !full} + {:else} + +{/snippet} + + selfClose.shown()} onkeydown={onKeydown} />
@@ -218,41 +318,30 @@ {rosterOpen ? `Hide ${ROSTER_LABEL.toLowerCase()}` : `Show ${ROSTER_LABEL.toLowerCase()}`} + {#if joined && view.large} + + {/if}
{#if joined} -
- {#each grid as cell (cell.key)} - {@const shape = cell.tile === null ? undefined : shapes[cell.tile]} - {@const layout = shape && cell.tile !== null ? tileLayout(shape.width, shape.height, shape.rotation, cell.own) : null} -
-
- {#if cell.tile !== null} - - {/if} - {#if layout === null} - - {/if} -
-
- {#if cell.own} - {OWN_TILE_LABEL} - {:else if cell.userId !== null} - - {/if} - {#if cell.screen}{SCREEN_TILE_LABEL}{/if} - {#if cell.muted}{/if} -
-
- {/each} +
+ {#if view.large} +
{@render feed(view.large, true)}
+
+ {#each view.rest as cell (cell.key)} + {@render feed(cell, false)} + {/each} +
+ {:else} +
+ {#each view.rest as cell (cell.key)} + {@render feed(cell, false)} + {/each} +
+ {/if}
{:else}
@@ -310,6 +399,9 @@
{#if joined} + {#if devicesOpen} + + {/if}
{#if CAMERA_TEXT[status.camera] !== ''} @@ -349,7 +453,7 @@ {#if SCREEN_TEXT[status.screen] !== ''}

{SCREEN_TEXT[status.screen]}

{/if} - {#if status.deviceChange} + {#if status.deviceChange && !devicesOpen}

{DEVICE_CHANGE_TEXT[status.deviceChange]}

{/if} {/if} diff --git a/frontend/src/CallWindowDevices.svelte b/frontend/src/CallWindowDevices.svelte new file mode 100644 index 00000000..d129fd9a --- /dev/null +++ b/frontend/src/CallWindowDevices.svelte @@ -0,0 +1,114 @@ + + +
+

{DEVICES_PANEL_LABEL}

+ {#if devices && !devices.supported} +

{devicesNote(devices)}

+ {:else} + + + + + + + + {/if} + {#if result !== ''} +

{result}

+ {/if} + {#if failure} + + {/if} +
diff --git a/frontend/src/callView.ts b/frontend/src/callView.ts new file mode 100644 index 00000000..7b4f3909 --- /dev/null +++ b/frontend/src/callView.ts @@ -0,0 +1,75 @@ +// Which video feed the call window shows large (ADR-0065), as plain data. A +// feed is a cell of the call grid, named by its key (callWindow.ts). The +// viewer's pick is one of three things: no pick (the window decides), the +// grid (the viewer asked for it) or one feed. The window shows the grid +// unless a feed is large. Nothing here asks the core for another picture +// size: the pictures stay at the sizes the worker sends, and CSS scales them. + +/** The key of the shared screen feed in `callGrid`. */ +export const SCREEN_KEY = 'screen'; + +export type ViewPick = + // The viewer chose nothing: a shared screen shows large, else the grid. + | { kind: 'auto' } + // The viewer chose the grid, also while a screen is shared. + | { kind: 'grid' } + | { kind: 'feed'; key: string }; + +export const AUTO_PICK: ViewPick = { kind: 'auto' }; +export const GRID_PICK: ViewPick = { kind: 'grid' }; + +/** + * The pick after the feeds changed. A feed that went away (the person left, + * the camera went off, the share ended) drops its pick, so the window goes + * back to the grid, or to the screen share by the automatic rule. A choice + * of the grid lasts as long as a screen is shared; the next share is shown + * large again. + */ +export function keepPick(pick: ViewPick, keys: readonly string[]): ViewPick { + if (pick.kind === 'feed' && !keys.includes(pick.key)) return AUTO_PICK; + if (pick.kind === 'grid' && !keys.includes(SCREEN_KEY)) return AUTO_PICK; + return pick; +} + +/** + * The key of the feed to show large, or null for the grid. A pick of a feed + * that is in the call always wins. Without a pick, a shared screen is large. + */ +export function largeKey(pick: ViewPick, keys: readonly string[]): string | null { + const kept = keepPick(pick, keys); + if (kept.kind === 'feed') return kept.key; + if (kept.kind === 'auto' && keys.includes(SCREEN_KEY)) return SCREEN_KEY; + return null; +} + +/** + * The pick after the viewer selects feed `key`. The feed that is large goes + * back to the grid; any other feed becomes large, and the one that was large + * joins the row again. A key that is not in the call changes nothing. + */ +export function selectFeed(pick: ViewPick, key: string, keys: readonly string[]): ViewPick { + if (!keys.includes(key)) return keepPick(pick, keys); + return largeKey(pick, keys) === key ? GRID_PICK : { kind: 'feed', key }; +} + +/** The "Show all" pick: the grid. */ +export function showAll(): ViewPick { + return GRID_PICK; +} + +export type Layout = { + // The feed that shows large, or null for the grid. + large: T | null; + // The other feeds in grid order: the cells of the grid, or the row of small + // tiles along the bottom. + rest: T[]; +}; + +/** Splits the cells into the large feed and the others, keeping their order. */ +export function splitFeeds(cells: readonly T[], large: string | null): Layout { + const chosen = large === null ? undefined : cells.find((cell) => cell.key === large); + return { + large: chosen ?? null, + rest: cells.filter((cell) => cell !== chosen) + }; +} diff --git a/frontend/src/calls.ts b/frontend/src/calls.ts index 0c99b547..43b7b9a0 100644 --- a/frontend/src/calls.ts +++ b/frontend/src/calls.ts @@ -749,6 +749,41 @@ export const DEVICE_CHANGE_TEXT: Record = { failed: 'The microphone or speaker could not be changed, and the sound may have stopped. Choose a device again, or leave and rejoin the call.' }; +/** What the core's device commands answer, as text for the device menus. */ +export const DEVICE_FAILURE_TEXT: Record = { + locked: 'The profile is locked.', + limit_exceeded: 'Persephone is busy. Try again in a moment.', + core_unavailable: 'The call devices could not be listed.', + invalid_argument: 'That device cannot be saved.' +}; + +/** + * What the device panel of the call window says about a change during a + * call (ADR-0065). A failure is the call status's `deviceChange` (ADR-0059). + * The status has no mark for a change that worked, so `null` after a save + * reads as switched. A speaker that is lost needs a rejoin (`failed`). + */ +export const DEVICE_SWITCH_TEXT: Record = { + not_found: 'The chosen microphone or speaker is not connected. The call keeps the one it had.', + unsupported: 'This system cannot switch the microphone or speaker during a call (Linux today). Your choice applies from the next call.', + kept: 'The chosen microphone could not be opened. The call keeps the one it had.', + failed: 'The microphone or speaker could not be changed, and the sound may have stopped. A lost speaker needs a rejoin: leave the call and join it again.' +}; +export const DEVICE_SWITCHED_TEXT = 'Switched. A camera change applies the next time you turn the camera on.'; +export const DEVICE_SWITCHING_TEXT = 'Switching…'; +export const DEVICES_BUTTON_LABEL = 'Device settings'; +export const DEVICES_PANEL_LABEL = 'Call devices'; + +/** + * The line under the device menus after a save: nothing before a save, + * "switching" while it runs, the failure the status shows, or "switched". + */ +export function deviceSwitchText(saved: boolean, saving: boolean, change: CallDeviceChange | null): string { + if (saving) return DEVICE_SWITCHING_TEXT; + if (!saved) return ''; + return change === null ? DEVICE_SWITCHED_TEXT : DEVICE_SWITCH_TEXT[change]; +} + /** The buttons that start each device test. */ export const DEVICE_TEST_LABEL: Record = { microphone: 'Test microphone', diff --git a/frontend/src/style.css b/frontend/src/style.css index 82a9ba2e..dc36c7ae 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -3871,6 +3871,99 @@ mark { gap: 12px; } +/* Choose the large video (ADR-0065). Each feed is one button. A large feed + fills the stage and keeps its aspect ratio; the others make one row of + small tiles along the bottom that scrolls sideways. The pictures are + scaled by CSS only. */ +.call-stage { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + min-height: 0; +} + +.call-stage > .call-grid { + flex: 1; +} + +.call-feed { + display: flex; + flex-direction: column; + gap: 4px; + width: 100%; + min-width: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: inherit; + text-align: left; +} + +.call-feed .video-name { + display: flex; + align-items: center; + gap: 6px; +} + +.call-feed[aria-pressed='true'] .video-frame { + outline: 2px solid var(--accent); +} + +.call-large { + display: flex; + flex: 1; + align-items: center; + justify-content: center; + min-height: 0; + padding: 12px; + container-type: size; +} + +/* The widest tile that fits the stage: its width, or its height (less the + name line) times the picture's ratio. */ +.call-large .call-cell { + width: min(100cqw, calc((100cqh - 28px) * var(--ratio, 1.7778))); +} + +.call-strip { + display: flex; + flex: none; + gap: 8px; + padding: 8px 12px; + overflow-x: auto; + border-top: 1px solid var(--line); + background: var(--panel); +} + +.call-strip .call-cell { + flex: none; + width: 160px; +} + +.call-window-devices { + display: flex; + flex: none; + flex-direction: column; + align-items: flex-start; + gap: 6px; + max-height: 40vh; + padding: 8px 16px; + overflow: auto; + border-top: 1px solid var(--line); + background: var(--panel); +} + +.call-window-devices h2 { + margin: 0; + font-size: 15px; +} + +.call-window-devices .field { + max-width: 100%; +} + .call-cell.speaking .video-frame { outline: 2px solid var(--presence); } diff --git a/frontend/tests/call-view.test.mjs b/frontend/tests/call-view.test.mjs new file mode 100644 index 00000000..b9de4034 --- /dev/null +++ b/frontend/tests/call-view.test.mjs @@ -0,0 +1,98 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + AUTO_PICK, + GRID_PICK, + keepPick, + largeKey, + selectFeed, + showAll, + splitFeeds +} from '../src/callView.ts'; +import { DEVICE_SWITCH_TEXT, DEVICE_SWITCHED_TEXT, DEVICE_SWITCHING_TEXT, deviceSwitchText } from '../src/calls.ts'; + +const cameras = ['own', 'a', 'b']; +const withScreen = [...cameras, 'screen']; +const feed = (key) => ({ kind: 'feed', key }); + +test('GIVEN no pick and no screen share WHEN the large feed is read THEN the grid shows', () => { + assert.equal(largeKey(AUTO_PICK, cameras), null); +}); + +test('GIVEN no pick WHEN a screen share starts THEN the screen is large', () => { + assert.equal(largeKey(AUTO_PICK, withScreen), 'screen'); +}); + +test('GIVEN a picked camera WHEN a screen share starts THEN the pick stays large', () => { + assert.equal(largeKey(feed('a'), withScreen), 'a'); +}); + +test('GIVEN the grid in view WHEN a camera is selected THEN it is large', () => { + assert.deepEqual(selectFeed(AUTO_PICK, 'a', cameras), feed('a')); +}); + +test('GIVEN a large camera WHEN another feed is selected THEN that feed is large', () => { + const next = selectFeed(feed('a'), 'b', cameras); + assert.equal(largeKey(next, cameras), 'b'); + const { large, rest } = splitFeeds(cameras.map((key) => ({ key })), largeKey(next, cameras)); + assert.equal(large.key, 'b'); + assert.deepEqual(rest.map((cell) => cell.key), ['own', 'a']); +}); + +test('GIVEN a large camera WHEN it is selected again THEN the grid shows', () => { + assert.equal(largeKey(selectFeed(feed('a'), 'a', cameras), cameras), null); +}); + +test('GIVEN the automatic large screen WHEN it is selected THEN the grid shows, also with the share on', () => { + const next = selectFeed(AUTO_PICK, 'screen', withScreen); + assert.deepEqual(next, GRID_PICK); + assert.equal(largeKey(next, withScreen), null); +}); + +test('GIVEN a large feed WHEN Show all is chosen THEN the grid shows', () => { + assert.equal(largeKey(showAll(), cameras), null); + assert.equal(largeKey(showAll(), withScreen), null); +}); + +test('GIVEN a grid choice WHEN the screen share ends and another starts THEN the new share is large', () => { + const after = keepPick(GRID_PICK, cameras); + assert.deepEqual(after, AUTO_PICK); + assert.equal(largeKey(after, withScreen), 'screen'); +}); + +test('GIVEN a large feed WHEN it goes away THEN the grid shows', () => { + assert.deepEqual(keepPick(feed('b'), ['own', 'a']), AUTO_PICK); + assert.equal(largeKey(feed('b'), ['own', 'a']), null); +}); + +test('GIVEN a large camera that went away WHEN a screen share runs THEN the screen is large', () => { + assert.equal(largeKey(feed('b'), ['own', 'a', 'screen']), 'screen'); +}); + +test('GIVEN the large feed is the screen WHEN the share ends THEN the grid shows', () => { + assert.equal(largeKey(feed('screen'), cameras), null); +}); + +test('GIVEN a key that is not in the call WHEN it is selected THEN nothing changes', () => { + assert.equal(largeKey(selectFeed(feed('a'), 'zzz', cameras), cameras), 'a'); + assert.equal(largeKey(selectFeed(AUTO_PICK, 'zzz', cameras), cameras), null); +}); + +test('GIVEN no large feed WHEN the cells are split THEN all stay in order', () => { + const cells = cameras.map((key) => ({ key })); + const split = splitFeeds(cells, null); + assert.equal(split.large, null); + assert.deepEqual(split.rest, cells); +}); + +test('GIVEN the device panel WHEN a change is read THEN each result has its own text', () => { + assert.equal(deviceSwitchText(false, false, null), ''); + assert.equal(deviceSwitchText(true, true, null), DEVICE_SWITCHING_TEXT); + assert.equal(deviceSwitchText(true, false, null), DEVICE_SWITCHED_TEXT); + for (const change of ['not_found', 'unsupported', 'kept', 'failed']) { + assert.equal(deviceSwitchText(true, false, change), DEVICE_SWITCH_TEXT[change]); + } + assert.match(DEVICE_SWITCH_TEXT.not_found, /not connected/); + assert.match(DEVICE_SWITCH_TEXT.unsupported, /Linux/); + assert.match(DEVICE_SWITCH_TEXT.failed, /rejoin/); +}); From 8e1dfe81fc04b8982069880c2b1af5fdfe557155 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 01:34:32 +0000 Subject: [PATCH 11/51] Write the newline ID in the call window device test as an escape Co-Authored-By: Claude Opus 5.5 --- src-tauri/tests/ipc.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index da58faf1..a273b4d8 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -1200,8 +1200,7 @@ fn given_the_call_window_then_it_lists_and_changes_call_devices() { for args in [ serde_json::json!({"recording": "", "playout": null}), serde_json::json!({"playout": "s".repeat(513)}), - serde_json::json!({"camera": "cam -1"}), + serde_json::json!({"camera": "cam\n1"}), ] { assert_eq!( invoke("set_call_devices", args).unwrap_err(), From 2670449456935ca224acc8ba93174d2e2a64d52d Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 01:26:26 +0000 Subject: [PATCH 12/51] Add the call statistics messages to the call protocol Wire version 11 adds ToWorker::SetStats and the closed numeric FromWorker::Stats message (ADR-0066), with bounds checked on read. Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/AGENTS.md | 1 + crates/call-protocol/src/lib.rs | 37 +- crates/call-protocol/src/stats.rs | 448 ++++++++++++++++++++++++ crates/call-protocol/src/stats/tests.rs | 296 ++++++++++++++++ 4 files changed, 780 insertions(+), 2 deletions(-) create mode 100644 crates/call-protocol/src/stats.rs create mode 100644 crates/call-protocol/src/stats/tests.rs diff --git a/crates/call-protocol/AGENTS.md b/crates/call-protocol/AGENTS.md index 5926d756..b954c88d 100644 --- a/crates/call-protocol/AGENTS.md +++ b/crates/call-protocol/AGENTS.md @@ -15,6 +15,7 @@ This crate defines the bounded binary messages between the key-holding core and - Sound level meter (ADR-0055 amendment of 2026-11-23): wire version 9 added `FromWorker::SoundLevel { level }`, 0 to `MAX_SOUND_LEVEL` (100). `Reader::sound_level` refuses a larger value. - Devices and levels (ADR-0059): wire version 10 added `ToWorker::TestDevice { test, device }` (a first message only, like `ListDevices`; `DeviceTest` is a closed set), `ToWorker::SetDevices { recording, playout, camera }` (the camera choice applies from the next camera start; `DevicesSet` answers for the microphone and speaker only), `FromWorker::ParticipantLevel { connection, identity, level }`, `FromWorker::ParticipantMuted { connection, identity, muted }` and `FromWorker::DevicesSet { failure }` (0 for none, else a `FailureCode`). `SoundLevel` is now the own microphone's level. - Microphone settings (ADR-0062): wire version 11 added `ToWorker::SetMicrophone { auto_level, mic_gain }` (tag 16, no answer), and `Join` ends with `auto_level` and `mic_gain` (two bytes). `Reader::mic_gain` refuses a gain over `MAX_MIC_GAIN_PERCENT` (400) or off the step of `MIC_GAIN_STEP_PERCENT` (5); use `valid_mic_gain` wherever a gain is used. +- Call statistics (ADR-0066): wire version 11 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer leaves out entries past the limits. - Coordinate wire changes with `crates/core` and `crates/call-worker` (planned), and bump the version byte. ## Checks diff --git a/crates/call-protocol/src/lib.rs b/crates/call-protocol/src/lib.rs index f430ad79..428c9703 100644 --- a/crates/call-protocol/src/lib.rs +++ b/crates/call-protocol/src/lib.rs @@ -12,6 +12,13 @@ use persephone_media_protocol::{ }; use zeroize::Zeroizing; +mod stats; +pub use stats::{ + AudioReceiveStats, AudioSendStats, CallStats, ConnectionStats, MAX_STATS_CONNECTIONS, + MAX_STATS_FPS, MAX_STATS_KBPS, MAX_STATS_MS, MAX_STATS_SIDE, QualityLimit, RemoteStats, + VideoReceiveStats, VideoSendStats, +}; + pub const VERSION: u8 = 11; pub const MAX_MESSAGE_BYTES: usize = 64 * 1024; /// Longest diagnostic record target (ADR-0058). @@ -369,6 +376,11 @@ pub enum ToWorker { playout: Option, camera: Option, }, + /// Start or stop sending [`FromWorker::Stats`], at most one a second + /// (ADR-0066). Off when the worker starts. No answer. + SetStats { + on: bool, + }, } /// The device that [`ToWorker::TestDevice`] tests. A closed set. @@ -489,6 +501,7 @@ impl std::fmt::Debug for ToWorker { .field("recording", recording) .field("playout", playout) .finish(), + Self::SetStats { on } => f.debug_struct("SetStats").field("on", on).finish(), } } } @@ -735,6 +748,9 @@ pub enum FromWorker { target: String, message: String, }, + /// The call's statistics, as numbers with units (ADR-0066). Sent at + /// most once a second, and only while [`ToWorker::SetStats`] is on. + Stats(CallStats), } // Tags of core to worker messages. @@ -754,6 +770,7 @@ const TO_SET_DIAGNOSTICS: u8 = 13; const TO_TEST_DEVICE: u8 = 14; const TO_SET_DEVICES: u8 = 15; const TO_SET_MICROPHONE: u8 = 16; +const TO_SET_STATS: u8 = 17; // Tags of worker to core messages. const FROM_READY: u8 = 1; @@ -778,6 +795,7 @@ const FROM_SOUND_LEVEL: u8 = 19; const FROM_PARTICIPANT_LEVEL: u8 = 20; const FROM_PARTICIPANT_MUTED: u8 = 21; const FROM_DEVICES_SET: u8 = 22; +const FROM_STATS: u8 = 23; #[derive(Clone, Copy)] enum CharRule { @@ -1148,6 +1166,10 @@ impl ToWorker { put_str(&mut out, playout.as_deref().unwrap_or("")); put_str(&mut out, camera.as_deref().unwrap_or("")); } + Self::SetStats { on } => { + out.push(TO_SET_STATS); + out.push(u8::from(*on)); + } } out } @@ -1273,6 +1295,7 @@ impl ToWorker { playout: reader.device_choice()?, camera: reader.device_choice()?, }, + TO_SET_STATS => Self::SetStats { on: reader.bool()? }, _ => return Err(DecodeError::UnknownTag), }; reader.finish()?; @@ -1446,6 +1469,10 @@ impl FromWorker { put_str(&mut out, target); put_str(&mut out, message); } + Self::Stats(stats) => { + out.push(FROM_STATS); + stats::put_stats(&mut out, stats); + } Self::VideoStopped { tile } => { out.push(FROM_VIDEO_STOPPED); out.push(*tile); @@ -1560,6 +1587,7 @@ impl FromWorker { } Self::VideoFrame { tile, rotation } } + FROM_STATS => Self::Stats(stats::read_stats(&mut reader)?), _ => return Err(DecodeError::UnknownTag), }; reader.finish()?; @@ -1777,6 +1805,7 @@ pub fn write_video_frame( #[cfg(test)] mod tests { + use super::stats::tests::full_stats; use super::*; use std::io::Cursor; @@ -1950,6 +1979,8 @@ mod tests { }, ToWorker::SetDiagnostics { on: true }, ToWorker::SetDiagnostics { on: false }, + ToWorker::SetStats { on: true }, + ToWorker::SetStats { on: false }, ToWorker::TestDevice { test: DeviceTest::Microphone, device: None, @@ -2119,6 +2150,8 @@ mod tests { target: "t".to_owned(), message: String::new(), }, + FromWorker::Stats(CallStats::default()), + FromWorker::Stats(full_stats()), FromWorker::VideoStopped { tile: 0 }, FromWorker::VideoStopped { tile: 4 }, FromWorker::VideoStopped { tile: SCREEN_TILE }, @@ -2342,7 +2375,7 @@ mod tests { Err(DecodeError::UnknownTag) ); assert_eq!( - FromWorker::decode(&[VERSION, 23]), + FromWorker::decode(&[VERSION, 24]), Err(DecodeError::UnknownTag) ); assert_eq!(FromWorker::decode(&[]), Err(DecodeError::Truncated)); @@ -3332,7 +3365,7 @@ mod tests { ); } - /// GIVEN a message of the previous wire versions (6 to 9) + /// GIVEN a message of the previous wire versions (6 to 10) /// WHEN it is decoded in either direction /// THEN the version is refused. #[test] diff --git a/crates/call-protocol/src/stats.rs b/crates/call-protocol/src/stats.rs new file mode 100644 index 00000000..255e512a --- /dev/null +++ b/crates/call-protocol/src/stats.rs @@ -0,0 +1,448 @@ +//! The call statistics message (ADR-0066): closed numeric values only. +//! +//! Every field is an integer with a unit and an upper bound that the reader +//! checks. There is no text except the participants' identities, which the +//! worker has already validated for other messages. There is no address, +//! port, candidate type, SSRC or codec name. + +use super::{DecodeError, MAX_OTHER_CONNECTIONS, MAX_PARTICIPANTS, Reader, put_str}; + +/// The highest bitrate or bandwidth a statistic holds, in kbit/s (1 Gbit/s). +pub const MAX_STATS_KBPS: u32 = 1_000_000; +/// The longest time a statistic holds, in milliseconds (one minute). +pub const MAX_STATS_MS: u16 = 60_000; +/// The highest frame rate a statistic holds, in frames per second. +pub const MAX_STATS_FPS: u8 = 120; +/// The longest picture side a statistic holds, in pixels. +pub const MAX_STATS_SIDE: u16 = 16_384; +/// The most connections one message describes: the own SFU and the other +/// SFUs of ADR-0054. +pub const MAX_STATS_CONNECTIONS: usize = 1 + MAX_OTHER_CONNECTIONS as usize; + +/// Why a sent video track runs below what was asked, as WebRTC reports it. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum QualityLimit { + None = 0, + Cpu = 1, + Bandwidth = 2, + Other = 3, +} + +impl TryFrom for QualityLimit { + type Error = DecodeError; + + fn try_from(value: u8) -> Result { + Ok(match value { + 0 => Self::None, + 1 => Self::Cpu, + 2 => Self::Bandwidth, + 3 => Self::Other, + _ => return Err(DecodeError::InvalidValue), + }) + } +} + +/// The own microphone track. `None` fields are not known yet: a rate needs +/// two samples, and the far end reports loss, jitter and round-trip time +/// only after its first report. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct AudioSendStats { + /// 0 to `MAX_SOUND_LEVEL` (100), as the meter shows it. + pub level: u8, + /// Kbit/s, at most [`MAX_STATS_KBPS`]. + pub bitrate_kbps: Option, + /// Packets sent since the track began (saturates at `u32::MAX`). + pub packets_sent: u32, + /// Packets the far end reports lost. + pub packets_lost: Option, + /// Milliseconds, at most [`MAX_STATS_MS`]. + pub jitter_ms: Option, + /// Milliseconds, at most [`MAX_STATS_MS`]. + pub rtt_ms: Option, +} + +/// The own camera or screen share track. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct VideoSendStats { + /// At most [`MAX_STATS_FPS`]. + pub fps: u8, + /// At most [`MAX_STATS_SIDE`] each. + pub width: u16, + pub height: u16, + /// Kbit/s, at most [`MAX_STATS_KBPS`]. + pub bitrate_kbps: Option, + pub limit: QualityLimit, + /// Packets the far end reports lost. + pub packets_lost: Option, +} + +/// The audio of one remote participant. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct AudioReceiveStats { + /// 0 to `MAX_SOUND_LEVEL` (100). + pub level: u8, + pub bitrate_kbps: Option, + pub packets_received: u32, + pub packets_lost: u32, + /// Milliseconds, at most [`MAX_STATS_MS`]. + pub jitter_ms: u16, + /// Share of the samples of the last second that WebRTC made up, 0 to + /// 100. + pub concealed_percent: Option, +} + +/// The video of one remote participant. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct VideoReceiveStats { + pub fps: u8, + pub width: u16, + pub height: u16, + pub bitrate_kbps: Option, + /// Frames dropped since the track began. + pub frames_dropped: u32, + pub packets_lost: u32, +} + +/// One remote participant, named by the identity and connection that the +/// worker already validated for its other messages. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RemoteStats { + pub connection: u8, + pub identity: String, + pub audio: Option, + pub video: Option, +} + +/// One connection to an SFU: 0 is the own one. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ConnectionStats { + pub connection: u8, + /// The bandwidth that WebRTC estimates for sending, kbit/s. + pub outgoing_kbps: Option, + /// Everything sent and everything received on the connection, kbit/s. + pub send_kbps: Option, + pub receive_kbps: Option, + pub rtt_ms: Option, +} + +/// One reading of the call's statistics. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CallStats { + pub microphone: Option, + pub camera: Option, + pub screen: Option, + /// At most [`MAX_PARTICIPANTS`], at most one for each participant. + pub remotes: Vec, + /// At most [`MAX_STATS_CONNECTIONS`], at most one for each connection. + pub connections: Vec, +} + +// Writing. The caller keeps every value inside its bound; the reader refuses +// anything else. + +fn put_flag(out: &mut Vec, present: bool) { + out.push(u8::from(present)); +} + +fn put_u32(out: &mut Vec, value: Option) { + put_flag(out, value.is_some()); + if let Some(value) = value { + out.extend_from_slice(&value.to_be_bytes()); + } +} + +fn put_u16(out: &mut Vec, value: Option) { + put_flag(out, value.is_some()); + if let Some(value) = value { + out.extend_from_slice(&value.to_be_bytes()); + } +} + +fn put_u8(out: &mut Vec, value: Option) { + put_flag(out, value.is_some()); + if let Some(value) = value { + out.push(value); + } +} + +fn put_audio_send(out: &mut Vec, audio: &AudioSendStats) { + out.push(audio.level); + put_u32(out, audio.bitrate_kbps); + out.extend_from_slice(&audio.packets_sent.to_be_bytes()); + put_u32(out, audio.packets_lost); + put_u16(out, audio.jitter_ms); + put_u16(out, audio.rtt_ms); +} + +fn put_video_send(out: &mut Vec, video: &VideoSendStats) { + out.push(video.fps); + out.extend_from_slice(&video.width.to_be_bytes()); + out.extend_from_slice(&video.height.to_be_bytes()); + put_u32(out, video.bitrate_kbps); + out.push(video.limit as u8); + put_u32(out, video.packets_lost); +} + +fn put_audio_receive(out: &mut Vec, audio: &AudioReceiveStats) { + out.push(audio.level); + put_u32(out, audio.bitrate_kbps); + out.extend_from_slice(&audio.packets_received.to_be_bytes()); + out.extend_from_slice(&audio.packets_lost.to_be_bytes()); + out.extend_from_slice(&audio.jitter_ms.to_be_bytes()); + put_u8(out, audio.concealed_percent); +} + +fn put_video_receive(out: &mut Vec, video: &VideoReceiveStats) { + out.push(video.fps); + out.extend_from_slice(&video.width.to_be_bytes()); + out.extend_from_slice(&video.height.to_be_bytes()); + put_u32(out, video.bitrate_kbps); + out.extend_from_slice(&video.frames_dropped.to_be_bytes()); + out.extend_from_slice(&video.packets_lost.to_be_bytes()); +} + +/// Writes `stats` after the message tag. Entries past the limits are left +/// out, so the message always fits. +pub(super) fn put_stats(out: &mut Vec, stats: &CallStats) { + let present = u8::from(stats.microphone.is_some()) + | u8::from(stats.camera.is_some()) << 1 + | u8::from(stats.screen.is_some()) << 2; + out.push(present); + if let Some(audio) = &stats.microphone { + put_audio_send(out, audio); + } + for video in [&stats.camera, &stats.screen].into_iter().flatten() { + put_video_send(out, video); + } + let remotes = &stats.remotes[..stats.remotes.len().min(MAX_PARTICIPANTS)]; + out.push(remotes.len() as u8); + for remote in remotes { + out.push(remote.connection); + put_str(out, &remote.identity); + out.push(u8::from(remote.audio.is_some()) | u8::from(remote.video.is_some()) << 1); + if let Some(audio) = &remote.audio { + put_audio_receive(out, audio); + } + if let Some(video) = &remote.video { + put_video_receive(out, video); + } + } + let connections = &stats.connections[..stats.connections.len().min(MAX_STATS_CONNECTIONS)]; + out.push(connections.len() as u8); + for connection in connections { + out.push(connection.connection); + put_u32(out, connection.outgoing_kbps); + put_u32(out, connection.send_kbps); + put_u32(out, connection.receive_kbps); + put_u16(out, connection.rtt_ms); + } +} + +// Reading. + +impl Reader<'_> { + fn flag(&mut self) -> Result { + self.bool() + } + + fn kbps(&mut self) -> Result, DecodeError> { + if !self.flag()? { + return Ok(None); + } + let value = self.u32()?; + if value > MAX_STATS_KBPS { + return Err(DecodeError::InvalidValue); + } + Ok(Some(value)) + } + + fn u16(&mut self) -> Result { + let bytes = self.take(2)?; + Ok(u16::from_be_bytes([bytes[0], bytes[1]])) + } + + fn millis(&mut self) -> Result { + let value = self.u16()?; + if value > MAX_STATS_MS { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn optional_millis(&mut self) -> Result, DecodeError> { + if self.flag()? { + Ok(Some(self.millis()?)) + } else { + Ok(None) + } + } + + fn optional_count(&mut self) -> Result, DecodeError> { + if self.flag()? { + Ok(Some(self.u32()?)) + } else { + Ok(None) + } + } + + fn fps(&mut self) -> Result { + let value = self.u8()?; + if value > MAX_STATS_FPS { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn side(&mut self) -> Result { + let value = self.u16()?; + if value > MAX_STATS_SIDE { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn percent(&mut self) -> Result { + let value = self.u8()?; + if value > 100 { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn audio_send(&mut self) -> Result { + Ok(AudioSendStats { + level: self.sound_level()?, + bitrate_kbps: self.kbps()?, + packets_sent: self.u32()?, + packets_lost: self.optional_count()?, + jitter_ms: self.optional_millis()?, + rtt_ms: self.optional_millis()?, + }) + } + + fn video_send(&mut self) -> Result { + Ok(VideoSendStats { + fps: self.fps()?, + width: self.side()?, + height: self.side()?, + bitrate_kbps: self.kbps()?, + limit: QualityLimit::try_from(self.u8()?)?, + packets_lost: self.optional_count()?, + }) + } + + fn audio_receive(&mut self) -> Result { + Ok(AudioReceiveStats { + level: self.sound_level()?, + bitrate_kbps: self.kbps()?, + packets_received: self.u32()?, + packets_lost: self.u32()?, + jitter_ms: self.millis()?, + concealed_percent: if self.flag()? { + Some(self.percent()?) + } else { + None + }, + }) + } + + fn video_receive(&mut self) -> Result { + Ok(VideoReceiveStats { + fps: self.fps()?, + width: self.side()?, + height: self.side()?, + bitrate_kbps: self.kbps()?, + frames_dropped: self.u32()?, + packets_lost: self.u32()?, + }) + } +} + +/// Reads the statistics after the message tag. The counts are checked +/// before anything is allocated, and a participant or a connection that +/// appears twice is refused. +pub(super) fn read_stats(reader: &mut Reader<'_>) -> Result { + let present = reader.u8()?; + if present > 0b111 { + return Err(DecodeError::InvalidValue); + } + let microphone = if present & 1 != 0 { + Some(reader.audio_send()?) + } else { + None + }; + let camera = if present & 2 != 0 { + Some(reader.video_send()?) + } else { + None + }; + let screen = if present & 4 != 0 { + Some(reader.video_send()?) + } else { + None + }; + let count = usize::from(reader.u8()?); + if count > MAX_PARTICIPANTS { + return Err(DecodeError::TooLarge); + } + let mut remotes: Vec = Vec::with_capacity(count); + for _ in 0..count { + let connection = reader.connection()?; + let identity = reader.identity()?; + if remotes + .iter() + .any(|seen| seen.connection == connection && seen.identity == identity) + { + return Err(DecodeError::InvalidValue); + } + let kinds = reader.u8()?; + if kinds > 0b11 { + return Err(DecodeError::InvalidValue); + } + let audio = if kinds & 1 != 0 { + Some(reader.audio_receive()?) + } else { + None + }; + let video = if kinds & 2 != 0 { + Some(reader.video_receive()?) + } else { + None + }; + remotes.push(RemoteStats { + connection, + identity, + audio, + video, + }); + } + let count = usize::from(reader.u8()?); + if count > MAX_STATS_CONNECTIONS { + return Err(DecodeError::TooLarge); + } + let mut connections: Vec = Vec::with_capacity(count); + for _ in 0..count { + let connection = reader.connection()?; + if connections.iter().any(|seen| seen.connection == connection) { + return Err(DecodeError::InvalidValue); + } + connections.push(ConnectionStats { + connection, + outgoing_kbps: reader.kbps()?, + send_kbps: reader.kbps()?, + receive_kbps: reader.kbps()?, + rtt_ms: reader.optional_millis()?, + }); + } + Ok(CallStats { + microphone, + camera, + screen, + remotes, + connections, + }) +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/call-protocol/src/stats/tests.rs b/crates/call-protocol/src/stats/tests.rs new file mode 100644 index 00000000..b9ae5628 --- /dev/null +++ b/crates/call-protocol/src/stats/tests.rs @@ -0,0 +1,296 @@ +use super::*; +use crate::{FROM_STATS, FromWorker, MAX_IDENTITY_BYTES, MAX_MESSAGE_BYTES, ToWorker, VERSION}; + +pub(crate) fn full_stats() -> CallStats { + let audio = AudioReceiveStats { + level: 100, + bitrate_kbps: Some(MAX_STATS_KBPS), + packets_received: u32::MAX, + packets_lost: 7, + jitter_ms: MAX_STATS_MS, + concealed_percent: Some(100), + }; + let video = VideoReceiveStats { + fps: MAX_STATS_FPS, + width: MAX_STATS_SIDE, + height: 1, + bitrate_kbps: None, + frames_dropped: 3, + packets_lost: u32::MAX, + }; + let sent = VideoSendStats { + fps: 30, + width: 1280, + height: 720, + bitrate_kbps: Some(1500), + limit: QualityLimit::Bandwidth, + packets_lost: Some(2), + }; + CallStats { + microphone: Some(AudioSendStats { + level: 42, + bitrate_kbps: Some(32), + packets_sent: 1000, + packets_lost: Some(1), + jitter_ms: Some(3), + rtt_ms: Some(40), + }), + camera: Some(sent), + screen: Some(VideoSendStats { + limit: QualityLimit::None, + packets_lost: None, + ..sent + }), + remotes: vec![ + RemoteStats { + connection: 0, + identity: "@bob:example.org:D".to_owned(), + audio: Some(audio), + video: Some(video), + }, + RemoteStats { + connection: 2, + identity: "@bob:example.org:D".to_owned(), + audio: None, + video: Some(video), + }, + ], + connections: vec![ + ConnectionStats { + connection: 0, + outgoing_kbps: Some(2500), + send_kbps: Some(40), + receive_kbps: None, + rtt_ms: Some(20), + }, + ConnectionStats { + connection: 3, + outgoing_kbps: None, + send_kbps: None, + receive_kbps: Some(MAX_STATS_KBPS), + rtt_ms: None, + }, + ], + } +} + +/// A message body with the version, the tag and `fields`. +fn body(fields: &[u8]) -> Vec { + let mut out = vec![VERSION, FROM_STATS]; + out.extend_from_slice(fields); + out +} + +fn decode(fields: &[u8]) -> Result { + FromWorker::decode(&body(fields)) +} + +/// The fields of a message with an own microphone record and nothing else. +fn audio_send_fields(level: u8) -> Vec { + // present: microphone; level; no bitrate; 4 bytes of packets; no loss, + // jitter or round-trip time; then no remotes and no connections. + vec![0b001, level, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] +} + +/// GIVEN every kind of statistic WHEN encoded and decoded THEN it is the +/// same. +#[test] +fn given_full_stats_when_round_tripped_then_unchanged() { + for stats in [CallStats::default(), full_stats()] { + let message = FromWorker::Stats(stats); + assert_eq!(FromWorker::decode(&message.encode()), Ok(message)); + } +} + +/// GIVEN statistics for every participant, with the longest identities WHEN +/// encoded THEN the message fits `MAX_MESSAGE_BYTES`. +#[test] +fn given_the_most_participants_with_long_identities_then_the_message_fits() { + let mut stats = full_stats(); + let audio = stats.remotes[0].audio; + let video = stats.remotes[0].video; + stats.remotes = (0..MAX_PARTICIPANTS) + .map(|index| RemoteStats { + connection: 0, + identity: format!("{index:0>width$}", width = MAX_IDENTITY_BYTES), + audio, + video, + }) + .collect(); + let wire = FromWorker::Stats(stats.clone()).encode(); + assert!(wire.len() < MAX_MESSAGE_BYTES, "{}", wire.len()); + assert_eq!(FromWorker::decode(&wire), Ok(FromWorker::Stats(stats))); +} + +/// GIVEN more entries than the limits WHEN encoded THEN the extra entries +/// are left out and the message decodes. +#[test] +fn given_too_many_entries_when_encoded_then_the_extras_are_left_out() { + let stats = CallStats { + remotes: (0..MAX_PARTICIPANTS + 5) + .map(|index| RemoteStats { + connection: 0, + identity: format!("id{index}"), + audio: None, + video: None, + }) + .collect(), + connections: (0..8) + .map(|connection| ConnectionStats { + connection, + outgoing_kbps: None, + send_kbps: None, + receive_kbps: None, + rtt_ms: None, + }) + .collect(), + ..CallStats::default() + }; + let Ok(FromWorker::Stats(read)) = FromWorker::decode(&FromWorker::Stats(stats).encode()) else { + panic!("the message must decode"); + }; + assert_eq!(read.remotes.len(), MAX_PARTICIPANTS); + assert_eq!(read.connections.len(), MAX_STATS_CONNECTIONS); +} + +/// GIVEN a count of participants or connections over its limit WHEN decoded +/// THEN it is refused before any entry is read. +#[test] +fn given_counts_over_the_limits_when_decoded_then_they_are_refused() { + assert_eq!( + decode(&[0, (MAX_PARTICIPANTS + 1) as u8]), + Err(DecodeError::TooLarge) + ); + assert_eq!( + decode(&[0, 0, (MAX_STATS_CONNECTIONS + 1) as u8]), + Err(DecodeError::TooLarge) + ); + assert_eq!( + decode(&[0, 0, 0]), + Ok(FromWorker::Stats(CallStats::default())) + ); +} + +/// GIVEN a field over its bound WHEN decoded THEN it is refused, and the +/// bound itself is accepted. +#[test] +fn given_a_value_over_its_bound_when_decoded_then_it_is_refused() { + assert_eq!( + decode(&audio_send_fields(101)), + Err(DecodeError::InvalidValue) + ); + assert!(decode(&audio_send_fields(100)).is_ok()); + // A bitrate over 1 Gbit/s. + for (kbps, ok) in [(MAX_STATS_KBPS, true), (MAX_STATS_KBPS + 1, false)] { + let mut fields = vec![0b001, 0, 1]; + fields.extend_from_slice(&kbps.to_be_bytes()); + fields.extend_from_slice(&[0; 9]); + assert_eq!(decode(&fields).is_ok(), ok, "{kbps}"); + } + // A round-trip time over a minute. + for (millis, ok) in [(MAX_STATS_MS, true), (MAX_STATS_MS + 1, false)] { + let mut fields = vec![0b001, 0, 0, 0, 0, 0, 0, 0, 0, 1]; + fields.extend_from_slice(&millis.to_be_bytes()); + fields.extend_from_slice(&[0, 0]); + assert_eq!(decode(&fields).is_ok(), ok, "{millis}"); + } + // A frame rate, a side and a limit code of a camera. + for (fps, side, limit, ok) in [ + (MAX_STATS_FPS, MAX_STATS_SIDE, 3u8, true), + (MAX_STATS_FPS + 1, 1u16, 0u8, false), + (1, MAX_STATS_SIDE + 1, 0, false), + (1, 1, 4, false), + ] { + let mut fields = vec![0b010, fps]; + fields.extend_from_slice(&side.to_be_bytes()); + fields.extend_from_slice(&1u16.to_be_bytes()); + fields.extend_from_slice(&[0, limit, 0, 0, 0]); + assert_eq!(decode(&fields).is_ok(), ok, "{fps} {side} {limit}"); + } +} + +/// GIVEN flag bytes that are not 0 or 1, or unknown presence bits WHEN +/// decoded THEN they are refused. +#[test] +fn given_bad_flags_when_decoded_then_they_are_refused() { + assert_eq!(decode(&[0b1000]), Err(DecodeError::InvalidValue)); + let mut fields = audio_send_fields(1); + fields[2] = 2; + assert_eq!(decode(&fields), Err(DecodeError::InvalidValue)); + // A remote with unknown kind bits. + assert_eq!( + decode(&[0, 1, 0, 0, 1, b'a', 0b100]), + Err(DecodeError::InvalidValue) + ); +} + +/// GIVEN a participant or a connection listed twice, an unknown connection +/// number, or a bad identity WHEN decoded THEN it is refused. +#[test] +fn given_duplicate_or_bad_entries_when_decoded_then_they_are_refused() { + let remote = [0u8, 0, 1, b'a', 0]; + let mut twice = vec![0, 2]; + twice.extend_from_slice(&remote); + twice.extend_from_slice(&remote); + twice.push(0); + assert_eq!(decode(&twice), Err(DecodeError::InvalidValue)); + // The same identity on two connections is two participants. + let mut other = remote; + other[0] = 1; + let mut two = vec![0, 2]; + two.extend_from_slice(&remote); + two.extend_from_slice(&other); + two.push(0); + assert!(decode(&two).is_ok()); + // Connection 4 does not exist. + assert_eq!( + decode(&[0, 1, 4, 0, 1, b'a', 0, 0]), + Err(DecodeError::InvalidValue) + ); + // An empty identity and a control character. + assert_eq!(decode(&[0, 1, 0, 0, 0, 0]), Err(DecodeError::TooShort)); + assert_eq!( + decode(&[0, 1, 0, 0, 1, 0x07, 0, 0]), + Err(DecodeError::InvalidCharacter) + ); + // A connection twice. + let connection = [0u8, 0, 0, 0, 0]; + let mut dup = vec![0, 0, 2]; + dup.extend_from_slice(&connection); + dup.extend_from_slice(&connection); + assert_eq!(decode(&dup), Err(DecodeError::InvalidValue)); +} + +/// GIVEN a message cut at every byte, with a trailing byte, or over the +/// message limit WHEN decoded THEN it is refused. +#[test] +fn given_truncated_trailing_or_oversize_stats_when_decoded_then_refused() { + let wire = FromWorker::Stats(full_stats()).encode(); + for length in 0..wire.len() { + assert!(FromWorker::decode(&wire[..length]).is_err(), "{length}"); + } + let mut longer = wire.clone(); + longer.push(0); + assert_eq!(FromWorker::decode(&longer), Err(DecodeError::TrailingBytes)); + let mut huge = wire; + huge.resize(MAX_MESSAGE_BYTES + 1, 0); + assert_eq!(FromWorker::decode(&huge), Err(DecodeError::TooLarge)); +} + +/// GIVEN the core's switch WHEN it is anything but 0 or 1 THEN it is +/// refused. +#[test] +fn given_the_stats_switch_when_decoded_then_only_a_bool_is_accepted() { + for on in [true, false] { + let message = ToWorker::SetStats { on }; + assert_eq!(ToWorker::decode(&message.encode()), Ok(message)); + } + assert_eq!( + ToWorker::decode(&[VERSION, 16, 2]), + Err(DecodeError::InvalidValue) + ); + assert_eq!( + ToWorker::decode(&[VERSION, 16]), + Err(DecodeError::Truncated) + ); +} From ee66d9af07dc66d2a5f1dba5be69f330027675cc Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 01:37:27 +0000 Subject: [PATCH 13/51] Read call statistics in the worker only while the core asks StatsProbe reads get_stats once a second on its own task with a deadline. A pure StatsBook makes rates from counter changes. The newest reading waits in its own output slot and never uses the control queue. Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/src/stats.rs | 13 +- crates/call-protocol/src/stats/tests.rs | 2 +- crates/call-worker/AGENTS.md | 1 + crates/call-worker/src/mapping.rs | 2 + crates/call-worker/src/mapping/stats.rs | 440 +++++++++++++ crates/call-worker/src/mapping/stats/tests.rs | 353 ++++++++++ crates/call-worker/src/output.rs | 115 +++- crates/call-worker/src/session.rs | 100 ++- crates/call-worker/src/session/stats_probe.rs | 607 ++++++++++++++++++ 9 files changed, 1622 insertions(+), 11 deletions(-) create mode 100644 crates/call-worker/src/mapping/stats.rs create mode 100644 crates/call-worker/src/mapping/stats/tests.rs create mode 100644 crates/call-worker/src/session/stats_probe.rs diff --git a/crates/call-protocol/src/stats.rs b/crates/call-protocol/src/stats.rs index 255e512a..c6acfdff 100644 --- a/crates/call-protocol/src/stats.rs +++ b/crates/call-protocol/src/stats.rs @@ -99,8 +99,9 @@ pub struct VideoReceiveStats { pub width: u16, pub height: u16, pub bitrate_kbps: Option, - /// Frames dropped since the track began. - pub frames_dropped: u32, + /// Frames dropped each second, over the last interval, at most + /// [`MAX_STATS_FPS`]. Not known until the second sample. + pub dropped_fps: Option, pub packets_lost: u32, } @@ -198,7 +199,7 @@ fn put_video_receive(out: &mut Vec, video: &VideoReceiveStats) { out.extend_from_slice(&video.width.to_be_bytes()); out.extend_from_slice(&video.height.to_be_bytes()); put_u32(out, video.bitrate_kbps); - out.extend_from_slice(&video.frames_dropped.to_be_bytes()); + put_u8(out, video.dropped_fps); out.extend_from_slice(&video.packets_lost.to_be_bytes()); } @@ -353,7 +354,11 @@ impl Reader<'_> { width: self.side()?, height: self.side()?, bitrate_kbps: self.kbps()?, - frames_dropped: self.u32()?, + dropped_fps: if self.flag()? { + Some(self.fps()?) + } else { + None + }, packets_lost: self.u32()?, }) } diff --git a/crates/call-protocol/src/stats/tests.rs b/crates/call-protocol/src/stats/tests.rs index b9ae5628..079dd0dc 100644 --- a/crates/call-protocol/src/stats/tests.rs +++ b/crates/call-protocol/src/stats/tests.rs @@ -15,7 +15,7 @@ pub(crate) fn full_stats() -> CallStats { width: MAX_STATS_SIDE, height: 1, bitrate_kbps: None, - frames_dropped: 3, + dropped_fps: Some(3), packets_lost: u32::MAX, }; let sent = VideoSendStats { diff --git a/crates/call-worker/AGENTS.md b/crates/call-worker/AGENTS.md index 44f3e913..f3afecd9 100644 --- a/crates/call-worker/AGENTS.md +++ b/crates/call-worker/AGENTS.md @@ -30,6 +30,7 @@ The contained process that runs one call (ADR-0043). It joins one LiveKit room w - Device tests (ADR-0059): `TestDevice` is a first message, like `ListDevices`; it connects to no server. `session::test_device` opens a sound test's device first (`sound_test::open`, off the runtime threads), then applies stage 2, then runs it (`Opened::run`, on its own thread). `sound_test.rs` listens (15 s, own level) or plays a 440 Hz tone (1.5 s). Windows: WASAPI in shared mode; `E_ACCESSDENIED` is `DeviceDenied`. Linux: one PulseAudio stream through the `libpulse.so.0` handle of `pulse.rs`, the default stream with no device name and `PA_STREAM_DONT_MOVE`; a `pulse:` choice is checked with `sound_paths` as for a `Join` and reaches the stream through `PULSE_SOURCE` or `PULSE_SINK`; any other chosen ID is `DeviceNotFound`; it must open before stage 2 (new socket); `PA_ERR_ACCESS` is `DeviceDenied`. macOS: a Core Audio HAL I/O procedure (32-bit float only) on the default device or the chosen UID; the device is found before the microphone permission is checked, so a missing device never prompts; a refused permission is `DeviceDenied`. Never request a permission in a default-run test on macOS: outside an app bundle it ends the process. The camera test takes the portal remote that the core sends before `TestDevice` (`Grant::take`), opens the camera as a call does and sends pictures on tile 0 for at most 30 s. `Leave` ends any test, which ends with `Left` or `Failed`. - Microphone settings (ADR-0062): `Join` carries `auto_level` and `mic_gain`, and `SetMicrophone` changes them in a running call. `mapping::Microphone::new` is the worker's own check (a gain over 400 percent or off the step of 5 is `Protocol`; the protocol reader refuses it first). The gain goes to the voice engine's audio processing module through `native::capture_processing::set_capture_gain_percent` (a process-wide value that every live factory applies); the automatic level goes to the published microphone track through `RtcAudioTrack::set_auto_gain_control`. Both apply at once, and `apply_microphone` applies both again after each `SetDevices`. The device tests (`sound_test.rs`) do not use them. A refusal is noted, never fatal. - Audio notes (ADR-0058 amendment of 2026-11-25): `note_audio` in `session.rs` writes `Note` records of the target `persephone::call_worker::audio` while the log is on: the devices at the join (counts and how each was chosen, never an ID or name), the microphone settings with what the audio processing module reports, and every 5 seconds the own level, the playout state and each remote audio track's packets, samples and level (`measure_levels`). Keep them to counts, flags and levels. Never add an identity, a device ID or name, a key or a token. +- Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since the reading before (a reset, a missing earlier value or a zero interval gives no rate, never a wrong one) and clamps every number to the protocol bound. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue. - Pictures never use the control queue. `output.rs` keeps at most one waiting picture per tile (newest wins), and control messages always go out first. Pictures are RGBA in byte order R, G, B, A, at most 640x360 and 15 per second per camera tile, and at most 1280x720 and 5 per second on the screen tile (5), checked by tile index before allocation. ## Build diff --git a/crates/call-worker/src/mapping.rs b/crates/call-worker/src/mapping.rs index bf9add86..4911fbee 100644 --- a/crates/call-worker/src/mapping.rs +++ b/crates/call-worker/src/mapping.rs @@ -1,5 +1,7 @@ //! The pure parts of the worker: no LiveKit types, no I/O, no clock reads. +pub mod stats; + use std::collections::{BTreeSet, HashMap, VecDeque}; use std::time::{Duration, Instant}; diff --git a/crates/call-worker/src/mapping/stats.rs b/crates/call-worker/src/mapping/stats.rs new file mode 100644 index 00000000..95b71674 --- /dev/null +++ b/crates/call-worker/src/mapping/stats.rs @@ -0,0 +1,440 @@ +//! Turns raw WebRTC counters into the call statistics message (ADR-0066). +//! +//! Pure: no LiveKit types, no I/O and no clock. The caller gives each +//! reading a time in milliseconds, and the book makes rates from the change +//! of a counter since the reading before. + +use std::collections::HashMap; + +use persephone_call_protocol::{ + AudioReceiveStats, AudioSendStats, CallStats, ConnectionStats, MAX_OTHER_CONNECTIONS, + MAX_PARTICIPANTS, MAX_STATS_CONNECTIONS, MAX_STATS_FPS, MAX_STATS_KBPS, MAX_STATS_MS, + MAX_STATS_SIDE, QualityLimit, RemoteStats, VideoReceiveStats, VideoSendStats, +}; + +use super::{sound_level, valid_identity}; + +/// How many bits a counter has in WebRTC. A 32-bit counter that falls from +/// near its top to near zero has wrapped. Any other fall is a reset. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Width { + Bits32, + Bits64, +} + +/// How much `current` is above `previous`, or `None` when there is no +/// previous value or the counter was reset. +pub fn counter_delta(previous: Option, current: u64, width: Width) -> Option { + let previous = previous?; + if current >= previous { + return Some(current - previous); + } + let top = u64::from(u32::MAX); + // A 32-bit counter wraps from near its top to near zero. A fall by less + // than half the range is a reset or a counter that went back. + if width == Width::Bits32 && previous <= top && current <= top && previous - current > top / 2 { + return Some(current + (top - previous) + 1); + } + None +} + +/// `delta` each second over `interval_ms`. `None` for no interval. +pub fn per_second(delta: u64, interval_ms: u64) -> Option { + if interval_ms == 0 { + return None; + } + u64::try_from(u128::from(delta) * 1000 / u128::from(interval_ms)).ok() +} + +/// The bitrate in kbit/s of `delta` bytes over `interval_ms`, at most +/// [`MAX_STATS_KBPS`]. `None` for no interval. +pub fn kbps(delta_bytes: u64, interval_ms: u64) -> Option { + if interval_ms == 0 { + return None; + } + // Bits per millisecond are kbit/s. + let rate = u128::from(delta_bytes) * 8 / u128::from(interval_ms); + Some(u32::try_from(rate.min(u128::from(MAX_STATS_KBPS))).unwrap_or(MAX_STATS_KBPS)) +} + +/// Seconds as WebRTC reports them to milliseconds, at most +/// [`MAX_STATS_MS`]. A value that is not a number or is negative is `None`. +pub fn millis(seconds: f64) -> Option { + if !seconds.is_finite() || seconds < 0.0 { + return None; + } + // Clamped first, so the cast cannot truncate. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let millis = (seconds * 1000.0).round().min(f64::from(MAX_STATS_MS)) as u16; + Some(millis) +} + +/// A count that WebRTC reports signed (lost packets can fall below zero when +/// duplicates arrive): never below 0 and at most `u32::MAX`. +pub fn count(value: i64) -> u32 { + u32::try_from(value.max(0)).unwrap_or(u32::MAX) +} + +fn unsigned(value: u64) -> u32 { + u32::try_from(value).unwrap_or(u32::MAX) +} + +fn frames_per_second(value: f64) -> u8 { + if !value.is_finite() || value <= 0.0 { + return 0; + } + // Clamped first, so the cast cannot truncate. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let fps = value.round().min(f64::from(MAX_STATS_FPS)) as u8; + fps +} + +fn side(value: u32) -> u16 { + u16::try_from(value.min(u32::from(MAX_STATS_SIDE))).unwrap_or(MAX_STATS_SIDE) +} + +fn kbps_from_bits(bits_per_second: f64) -> Option { + if !bits_per_second.is_finite() || bits_per_second < 0.0 { + return None; + } + // Clamped first, so the cast cannot truncate. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let rate = (bits_per_second / 1000.0) + .round() + .min(f64::from(MAX_STATS_KBPS)) as u32; + Some(rate) +} + +// The raw readings: plain numbers in the units of WebRTC's statistics +// (seconds, bytes, 0.0 to 1.0 levels). + +/// The own microphone track. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawOwnAudio { + /// Linear, 0.0 to 1.0. + pub level: f64, + pub bytes_sent: u64, + pub packets_sent: u64, + /// What the far end reports; `None` before its first report. + pub packets_lost: Option, + pub jitter_seconds: Option, + pub rtt_seconds: Option, +} + +/// The own camera or screen share track. A track with several layers gives +/// the sum of their bytes and the largest layer's size and frame rate. +#[derive(Clone, Debug, PartialEq)] +pub struct RawOwnVideo { + pub fps: f64, + pub width: u32, + pub height: u32, + pub bytes_sent: u64, + pub limit: QualityLimit, + pub packets_lost: Option, +} + +/// The audio of one remote participant, summed over its audio tracks. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawRemoteAudio { + /// Linear, 0.0 to 1.0; the loudest track. + pub level: f64, + pub bytes_received: u64, + pub packets_received: u64, + pub packets_lost: i64, + pub jitter_seconds: f64, + pub total_samples: u64, + pub concealed_samples: u64, +} + +/// The video of one remote participant. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawRemoteVideo { + pub fps: f64, + pub width: u32, + pub height: u32, + pub bytes_received: u64, + pub frames_dropped: u64, + pub packets_lost: i64, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawRemote { + pub connection: u8, + pub identity: String, + pub audio: Option, + pub video: Option, +} + +/// One connection to an SFU. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawConnection { + pub connection: u8, + /// WebRTC's estimate of the bandwidth for sending, in bit/s. + pub outgoing_bits_per_second: Option, + /// The bytes sent and received on the connection's transports. + pub bytes_sent: Option, + pub bytes_received: Option, + pub rtt_seconds: Option, +} + +/// One reading of everything. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawStats { + /// Milliseconds on a clock that only goes forward. + pub at_ms: u64, + pub microphone: Option, + pub camera: Option, + pub screen: Option, + pub remotes: Vec, + pub connections: Vec, +} + +/// What a counter belongs to. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +enum Source { + Microphone, + Camera, + Screen, + Remote(u8, String), + Connection(u8), +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +enum Counter { + BytesSent, + BytesReceived, + AudioBytes, + VideoBytes, + FramesDropped, + TotalSamples, + ConcealedSamples, +} + +type Key = (Source, Counter); + +/// Remembers the last counters, so a reading gives rates. +#[derive(Debug, Default)] +pub struct StatsBook { + at_ms: Option, + counters: HashMap, +} + +/// The counters of one reading while it is made. +struct Reading<'a> { + /// The time since the reading before, or `None` for the first reading + /// and for one at the same time or earlier. + interval_ms: Option, + before: &'a HashMap, + now: HashMap, +} + +impl Reading<'_> { + /// The change of a counter since the reading before. The counter is kept + /// for the next reading in any case. + fn delta( + &mut self, + source: &Source, + counter: Counter, + value: u64, + width: Width, + ) -> Option { + let key = (source.clone(), counter); + let delta = self + .interval_ms + .and_then(|_| counter_delta(self.before.get(&key).copied(), value, width)); + self.now.insert(key, value); + delta + } + + fn kbps(&mut self, source: &Source, counter: Counter, bytes: u64) -> Option { + let delta = self.delta(source, counter, bytes, Width::Bits64); + kbps(delta?, self.interval_ms?) + } +} + +impl StatsBook { + /// Forgets every counter, so the next reading has no rates. Call it when + /// the statistics are turned on, so a pause is not a long interval. + pub fn reset(&mut self) { + self.at_ms = None; + self.counters.clear(); + } + + /// The statistics message for `raw`. Rates are `None` for the first + /// reading, for a reading at the time of the one before, and for a + /// counter that was not there before or was reset. A reading at the + /// time of the one before changes nothing, so the next reading still + /// has a rate. Entries past the limits and entries the protocol would + /// refuse are left out. + pub fn next(&mut self, raw: &RawStats) -> CallStats { + // The same time twice is a zero interval: no rates, and no change + // of what the next reading compares with. + let same_time = self.at_ms == Some(raw.at_ms); + let interval_ms = if same_time { + None + } else { + self.at_ms + .and_then(|before| raw.at_ms.checked_sub(before)) + .filter(|interval| *interval > 0) + }; + let before = std::mem::take(&mut self.counters); + let mut reading = Reading { + interval_ms, + before: &before, + now: HashMap::new(), + }; + let stats = CallStats { + microphone: raw + .microphone + .as_ref() + .map(|audio| own_audio(&mut reading, audio)), + camera: raw + .camera + .as_ref() + .map(|video| own_video(&mut reading, &Source::Camera, video)), + screen: raw + .screen + .as_ref() + .map(|video| own_video(&mut reading, &Source::Screen, video)), + remotes: remotes(&mut reading, &raw.remotes), + connections: connections(&mut reading, &raw.connections), + }; + let now = reading.now; + if same_time { + self.counters = before; + } else { + self.counters = now; + self.at_ms = Some(raw.at_ms); + } + stats + } +} + +fn own_audio(reading: &mut Reading<'_>, audio: &RawOwnAudio) -> AudioSendStats { + AudioSendStats { + level: sound_level(audio.level), + bitrate_kbps: reading.kbps(&Source::Microphone, Counter::BytesSent, audio.bytes_sent), + packets_sent: unsigned(audio.packets_sent), + packets_lost: audio.packets_lost.map(count), + jitter_ms: audio.jitter_seconds.and_then(millis), + rtt_ms: audio.rtt_seconds.and_then(millis), + } +} + +fn own_video(reading: &mut Reading<'_>, source: &Source, video: &RawOwnVideo) -> VideoSendStats { + VideoSendStats { + fps: frames_per_second(video.fps), + width: side(video.width), + height: side(video.height), + bitrate_kbps: reading.kbps(source, Counter::BytesSent, video.bytes_sent), + limit: video.limit, + packets_lost: video.packets_lost.map(count), + } +} + +fn remotes(reading: &mut Reading<'_>, raw: &[RawRemote]) -> Vec { + let mut out: Vec = Vec::new(); + for remote in raw { + if out.len() >= MAX_PARTICIPANTS { + break; + } + if !valid_identity(&remote.identity) + || remote.connection > MAX_OTHER_CONNECTIONS + || out.iter().any(|seen| { + seen.connection == remote.connection && seen.identity == remote.identity + }) + { + continue; + } + let source = Source::Remote(remote.connection, remote.identity.clone()); + let audio = remote.audio.as_ref().map(|audio| { + let total = reading.delta( + &source, + Counter::TotalSamples, + audio.total_samples, + Width::Bits64, + ); + let concealed = reading.delta( + &source, + Counter::ConcealedSamples, + audio.concealed_samples, + Width::Bits64, + ); + AudioReceiveStats { + level: sound_level(audio.level), + bitrate_kbps: reading.kbps(&source, Counter::AudioBytes, audio.bytes_received), + packets_received: unsigned(audio.packets_received), + packets_lost: count(audio.packets_lost), + jitter_ms: millis(audio.jitter_seconds).unwrap_or(0), + concealed_percent: concealed_percent(total, concealed), + } + }); + let video = remote.video.as_ref().map(|video| { + let dropped = reading.delta( + &source, + Counter::FramesDropped, + video.frames_dropped, + Width::Bits32, + ); + VideoReceiveStats { + fps: frames_per_second(video.fps), + width: side(video.width), + height: side(video.height), + bitrate_kbps: reading.kbps(&source, Counter::VideoBytes, video.bytes_received), + dropped_fps: dropped + .zip(reading.interval_ms) + .and_then(|(delta, interval)| per_second(delta, interval)) + .map(|rate| u8::try_from(rate.min(u64::from(MAX_STATS_FPS))).unwrap_or(0)), + packets_lost: count(video.packets_lost), + } + }); + out.push(RemoteStats { + connection: remote.connection, + identity: remote.identity.clone(), + audio, + video, + }); + } + out +} + +/// The share of the samples of one interval that WebRTC made up. `None` +/// when there was no interval or no sample. +fn concealed_percent(total: Option, concealed: Option) -> Option { + let (total, concealed) = (total?, concealed?); + if total == 0 { + return None; + } + let percent = (u128::from(concealed) * 100 / u128::from(total)).min(100); + u8::try_from(percent).ok() +} + +fn connections(reading: &mut Reading<'_>, raw: &[RawConnection]) -> Vec { + let mut out: Vec = Vec::new(); + for connection in raw { + if out.len() >= MAX_STATS_CONNECTIONS + || connection.connection > MAX_OTHER_CONNECTIONS + || out + .iter() + .any(|seen| seen.connection == connection.connection) + { + continue; + } + let source = Source::Connection(connection.connection); + out.push(ConnectionStats { + connection: connection.connection, + outgoing_kbps: connection.outgoing_bits_per_second.and_then(kbps_from_bits), + send_kbps: connection + .bytes_sent + .and_then(|bytes| reading.kbps(&source, Counter::BytesSent, bytes)), + receive_kbps: connection + .bytes_received + .and_then(|bytes| reading.kbps(&source, Counter::BytesReceived, bytes)), + rtt_ms: connection.rtt_seconds.and_then(millis), + }); + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/call-worker/src/mapping/stats/tests.rs b/crates/call-worker/src/mapping/stats/tests.rs new file mode 100644 index 00000000..c0b7237f --- /dev/null +++ b/crates/call-worker/src/mapping/stats/tests.rs @@ -0,0 +1,353 @@ +use super::*; +use persephone_call_protocol::MAX_IDENTITY_BYTES; + +fn audio_in(bytes: u64) -> RawRemoteAudio { + RawRemoteAudio { + level: 0.5, + bytes_received: bytes, + packets_received: 100, + packets_lost: 2, + jitter_seconds: 0.012, + total_samples: 0, + concealed_samples: 0, + } +} + +fn remote(identity: &str, audio: Option) -> RawRemote { + RawRemote { + connection: 0, + identity: identity.to_owned(), + audio, + video: None, + } +} + +fn mic(bytes: u64) -> RawOwnAudio { + RawOwnAudio { + level: 1.0, + bytes_sent: bytes, + packets_sent: 5, + packets_lost: Some(-3), + jitter_seconds: Some(0.0004), + rtt_seconds: Some(0.0415), + } +} + +fn reading(at_ms: u64, bytes: u64) -> RawStats { + RawStats { + at_ms, + microphone: Some(mic(bytes)), + ..RawStats::default() + } +} + +fn bitrate(stats: &CallStats) -> Option { + stats + .microphone + .as_ref() + .and_then(|audio| audio.bitrate_kbps) +} + +/// GIVEN a counter that grows WHEN the delta is taken THEN it is the +/// growth; GIVEN no previous value THEN there is none. +#[test] +fn given_a_growing_counter_when_the_delta_is_taken_then_it_is_the_growth() { + assert_eq!(counter_delta(Some(10), 25, Width::Bits64), Some(15)); + assert_eq!(counter_delta(Some(10), 10, Width::Bits64), Some(0)); + assert_eq!(counter_delta(None, 25, Width::Bits64), None); +} + +/// GIVEN a counter that falls WHEN the delta is taken THEN it is a reset +/// and has no delta. +#[test] +fn given_a_counter_that_falls_when_the_delta_is_taken_then_it_is_a_reset() { + assert_eq!(counter_delta(Some(1000), 5, Width::Bits64), None); + // A small fall of a 32-bit counter is no wrap. + assert_eq!(counter_delta(Some(1000), 5, Width::Bits32), None); + // A fall from a 64-bit value beyond 32 bits is never a wrap. + assert_eq!(counter_delta(Some(1 << 40), 5, Width::Bits32), None); +} + +/// GIVEN a 32-bit counter near its top that comes back near zero WHEN the +/// delta is taken THEN it is the growth across the wrap, but a 64-bit +/// counter is not wrapped. +#[test] +fn given_a_32_bit_counter_wraps_when_the_delta_is_taken_then_it_counts_across() { + let top = u64::from(u32::MAX); + assert_eq!(counter_delta(Some(top - 4), 5, Width::Bits32), Some(10)); + assert_eq!(counter_delta(Some(top), 0, Width::Bits32), Some(1)); + assert_eq!(counter_delta(Some(top - 4), 5, Width::Bits64), None); +} + +/// GIVEN a zero interval WHEN a rate is made THEN there is none. +#[test] +fn given_a_zero_interval_when_a_rate_is_made_then_there_is_none() { + assert_eq!(per_second(10, 0), None); + assert_eq!(kbps(10, 0), None); + assert_eq!(per_second(10, 500), Some(20)); +} + +/// GIVEN bytes over an interval WHEN the bitrate is made THEN it is in +/// kbit/s, and a huge value stops at the bound. +#[test] +fn given_bytes_over_an_interval_when_the_bitrate_is_made_then_it_is_in_kbps() { + // 125 000 bytes in a second are 1000 kbit/s. + assert_eq!(kbps(125_000, 1000), Some(1000)); + assert_eq!(kbps(125_000, 2000), Some(500)); + assert_eq!(kbps(u64::MAX, 1), Some(MAX_STATS_KBPS)); +} + +/// GIVEN odd WebRTC numbers WHEN they are converted THEN each stays inside +/// its bound and a number that is not a number is unknown. +#[test] +fn given_odd_numbers_when_converted_then_they_stay_inside_their_bounds() { + assert_eq!(millis(0.0415), Some(42)); + assert_eq!(millis(1e9), Some(MAX_STATS_MS)); + assert_eq!(millis(-1.0), None); + assert_eq!(millis(f64::NAN), None); + assert_eq!(millis(f64::INFINITY), None); + assert_eq!(count(-5), 0); + assert_eq!(count(i64::MAX), u32::MAX); + assert_eq!(frames_per_second(29.6), 30); + assert_eq!(frames_per_second(1e9), MAX_STATS_FPS); + assert_eq!(frames_per_second(f64::NAN), 0); + assert_eq!(side(u32::MAX), MAX_STATS_SIDE); + assert_eq!(kbps_from_bits(2_500_000.0), Some(2500)); + assert_eq!(kbps_from_bits(1e300), Some(MAX_STATS_KBPS)); + assert_eq!(kbps_from_bits(f64::NAN), None); +} + +/// GIVEN the first reading WHEN it is made THEN no rate is known; GIVEN the +/// second a second later THEN the rate follows from the change. +#[test] +fn given_two_readings_when_made_then_the_second_has_the_rate() { + let mut book = StatsBook::default(); + let first = book.next(&reading(1000, 10_000)); + assert_eq!(bitrate(&first), None); + // Own values that need no earlier reading are there at once. + let audio = first.microphone.unwrap(); + assert_eq!(audio.level, 100); + assert_eq!(audio.packets_lost, Some(0), "a negative loss counts as 0"); + assert_eq!(audio.jitter_ms, Some(0)); + assert_eq!(audio.rtt_ms, Some(42)); + let second = book.next(&reading(2000, 10_000 + 4000)); + assert_eq!(bitrate(&second), Some(32)); + // Half a second later with the same growth doubles the rate. + let third = book.next(&reading(2500, 10_000 + 8000)); + assert_eq!(bitrate(&third), Some(64)); +} + +/// GIVEN a counter that was reset WHEN the next reading is made THEN that +/// reading has no rate and the one after has it again. +#[test] +fn given_a_reset_counter_when_read_then_one_reading_has_no_rate() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 50_000)); + let after_reset = book.next(&reading(2000, 100)); + assert_eq!(bitrate(&after_reset), None); + let next = book.next(&reading(3000, 100 + 12_500)); + assert_eq!(bitrate(&next), Some(100)); +} + +/// GIVEN two readings at the same time WHEN the second is made THEN it has +/// no rate and the third still compares with the first. +#[test] +fn given_a_zero_interval_when_read_then_no_rate_and_the_baseline_stays() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 0)); + let same = book.next(&reading(1000, 5000)); + assert_eq!(bitrate(&same), None); + let later = book.next(&reading(2000, 12_500)); + assert_eq!(bitrate(&later), Some(100)); +} + +/// GIVEN a reading with an earlier time WHEN it is made THEN it has no rate +/// and becomes the new baseline. +#[test] +fn given_time_going_back_when_read_then_no_rate_and_a_new_baseline() { + let mut book = StatsBook::default(); + book.next(&reading(5000, 1_000_000)); + let back = book.next(&reading(1000, 0)); + assert_eq!(bitrate(&back), None); + let next = book.next(&reading(2000, 12_500)); + assert_eq!(bitrate(&next), Some(100)); +} + +/// GIVEN the statistics were turned off and on WHEN the book is reset THEN +/// the first reading has no rate, however long the pause. +#[test] +fn given_a_reset_book_when_read_then_the_first_reading_has_no_rate() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 0)); + book.reset(); + assert_eq!(bitrate(&book.next(&reading(60_000, 1_000_000))), None); +} + +/// GIVEN a track that stops and starts WHEN readings are made THEN the new +/// track has no rate until its second reading. +#[test] +fn given_a_track_that_goes_and_returns_when_read_then_its_rate_starts_again() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 0)); + book.next(&RawStats { + at_ms: 2000, + ..RawStats::default() + }); + assert_eq!(bitrate(&book.next(&reading(3000, 99_000))), None); + assert_eq!( + bitrate(&book.next(&reading(4000, 99_000 + 125_000))), + Some(1000) + ); +} + +/// GIVEN remote audio that conceals samples WHEN read twice THEN the share +/// is of the samples of the last interval only. +#[test] +fn given_concealed_samples_when_read_then_the_share_is_of_the_last_interval() { + let mut book = StatsBook::default(); + let with = |at_ms, total, concealed| RawStats { + at_ms, + remotes: vec![remote( + "@a:example.org:D", + Some(RawRemoteAudio { + total_samples: total, + concealed_samples: concealed, + ..audio_in(0) + }), + )], + ..RawStats::default() + }; + let share = |stats: &CallStats| stats.remotes[0].audio.unwrap().concealed_percent; + assert_eq!(share(&book.next(&with(1000, 48_000, 40_000))), None); + assert_eq!(share(&book.next(&with(2000, 96_000, 40_000))), Some(0)); + assert_eq!(share(&book.next(&with(3000, 144_000, 52_000))), Some(25)); + // No samples in the interval: no share. + assert_eq!(share(&book.next(&with(4000, 144_000, 52_000))), None); + // More concealed than total is stopped at 100. + assert_eq!(share(&book.next(&with(5000, 144_100, 99_000))), Some(100)); +} + +/// GIVEN remote video that drops frames WHEN read twice THEN the drop rate +/// is per second. +#[test] +fn given_dropped_frames_when_read_then_the_rate_is_per_second() { + let mut book = StatsBook::default(); + let with = |at_ms, dropped| RawStats { + at_ms, + remotes: vec![RawRemote { + video: Some(RawRemoteVideo { + fps: 29.97, + width: 1280, + height: 720, + frames_dropped: dropped, + ..RawRemoteVideo::default() + }), + ..remote("@a:example.org:D", None) + }], + ..RawStats::default() + }; + let rate = |stats: &CallStats| stats.remotes[0].video.unwrap().dropped_fps; + assert_eq!(rate(&book.next(&with(1000, 7))), None); + assert_eq!(rate(&book.next(&with(3000, 17))), Some(5)); + let last = book.next(&with(4000, 1_000_000)); + assert_eq!(rate(&last), Some(MAX_STATS_FPS)); + assert_eq!(last.remotes[0].video.unwrap().fps, 30); +} + +/// GIVEN too many, repeated and invalid participants WHEN read THEN the +/// message holds only valid ones, each once, and at most the limit. +#[test] +fn given_bad_participants_when_read_then_only_valid_distinct_ones_stay() { + let mut raw = RawStats { + at_ms: 1000, + ..RawStats::default() + }; + raw.remotes.push(remote("", None)); + raw.remotes.push(remote("bad\nname", None)); + raw.remotes + .push(remote(&"x".repeat(MAX_IDENTITY_BYTES + 1), None)); + raw.remotes.push(RawRemote { + connection: MAX_OTHER_CONNECTIONS + 1, + ..remote("@far:example.org:D", None) + }); + raw.remotes.push(remote("@a:example.org:D", None)); + raw.remotes + .push(remote("@a:example.org:D", Some(audio_in(1)))); + raw.remotes.push(RawRemote { + connection: 2, + ..remote("@a:example.org:D", None) + }); + raw.remotes + .extend((0..MAX_PARTICIPANTS * 2).map(|i| remote(&format!("@u{i}:example.org:D"), None))); + let stats = StatsBook::default().next(&raw); + assert_eq!(stats.remotes.len(), MAX_PARTICIPANTS); + assert_eq!(stats.remotes[0].identity, "@a:example.org:D"); + assert!(stats.remotes[0].audio.is_none(), "the first entry wins"); + assert_eq!(stats.remotes[1].connection, 2); + // The message encodes and decodes: nothing the protocol refuses is left. + let message = persephone_call_protocol::FromWorker::Stats(stats); + assert_eq!( + persephone_call_protocol::FromWorker::decode(&message.encode()), + Ok(message) + ); +} + +/// GIVEN connections that repeat or do not exist WHEN read THEN each real +/// one is there once and the rates follow the transport bytes. +#[test] +fn given_connections_when_read_then_rates_follow_the_transport_bytes() { + let link = |connection, sent, received| RawConnection { + connection, + outgoing_bits_per_second: Some(3_000_000.0), + bytes_sent: Some(sent), + bytes_received: Some(received), + rtt_seconds: Some(0.02), + }; + let raw = |at_ms, sent, received| RawStats { + at_ms, + connections: vec![ + link(0, sent, received), + link(0, 0, 0), + link(1, sent, received), + link(MAX_OTHER_CONNECTIONS + 1, 0, 0), + ], + ..RawStats::default() + }; + let mut book = StatsBook::default(); + let first = book.next(&raw(1000, 0, 0)); + assert_eq!(first.connections.len(), 2); + assert_eq!(first.connections[0].send_kbps, None); + assert_eq!(first.connections[0].outgoing_kbps, Some(3000)); + assert_eq!(first.connections[0].rtt_ms, Some(20)); + let second = book.next(&raw(2000, 250_000, 125_000)); + assert_eq!(second.connections[0].send_kbps, Some(2000)); + assert_eq!(second.connections[0].receive_kbps, Some(1000)); + assert_eq!(second.connections[1].connection, 1); +} + +/// GIVEN a participant that left WHEN readings go on THEN its counters are +/// forgotten, so the book holds no more than the reading shows. +#[test] +fn given_a_participant_that_left_when_read_then_its_counters_are_forgotten() { + let mut book = StatsBook::default(); + let both = RawStats { + at_ms: 1000, + remotes: vec![ + remote("@a:example.org:D", Some(audio_in(1))), + remote("@b:example.org:D", Some(audio_in(1))), + ], + ..RawStats::default() + }; + book.next(&both); + let held = book.counters.len(); + book.next(&RawStats { + at_ms: 2000, + remotes: vec![remote("@a:example.org:D", Some(audio_in(1)))], + ..RawStats::default() + }); + assert!(book.counters.len() < held); + assert!(book.counters.keys().all(|(source, _)| matches!( + source, + Source::Remote(0, identity) if identity == "@a:example.org:D" + ))); +} diff --git a/crates/call-worker/src/output.rs b/crates/call-worker/src/output.rs index 4f761339..535ef96e 100644 --- a/crates/call-worker/src/output.rs +++ b/crates/call-worker/src/output.rs @@ -6,8 +6,13 @@ //! that still waits, so at most one picture per tile is held, and a picture //! never waits in front of a control message. The slot write never blocks. //! +//! - The call statistics (ADR-0066) go into one slot, apart from both. A +//! newer reading replaces the one that still waits. The writer writes it +//! after the control messages and a waiting picture of its round, so it +//! never delays them, and the slot write never blocks. +//! //! A small wake item in the control queue tells the writer that a picture -//! waits. If the queue is full, the writer is busy and looks at the slots +//! or a reading waits. If the queue is full, the writer is busy and looks at the slots //! anyway before it sleeps. use std::io::{self, Write}; @@ -15,7 +20,9 @@ use std::sync::{Arc, Mutex, PoisonError}; #[cfg(test)] use persephone_call_protocol::SCREEN_TILE; -use persephone_call_protocol::{FromWorker, VIDEO_TILES, write_message, write_video_frame}; +use persephone_call_protocol::{ + CallStats, FromWorker, VIDEO_TILES, write_message, write_video_frame, +}; use tokio::sync::mpsc::{self, WeakSender, error::TryRecvError}; use crate::video::rgba_len; @@ -84,10 +91,12 @@ impl Default for Slots { /// The own camera's tile. const OWN_TILE: u8 = 0; -/// The newest waiting picture of each tile. +/// The newest waiting picture of each tile, and the newest waiting +/// statistics reading. #[derive(Default)] pub struct VideoSlots { slots: Mutex, + stats: Mutex>, } impl VideoSlots { @@ -112,6 +121,19 @@ impl VideoSlots { valid } + /// Stores a statistics reading and replaces the one that waits. + fn put_stats(&self, stats: CallStats) { + *self.stats.lock().unwrap_or_else(PoisonError::into_inner) = Some(stats); + } + + /// Takes the waiting statistics reading. + fn take_stats(&self) -> Option { + self.stats + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + } + /// Drops the picture that waits for a tile. A remote tile stays closed /// until the writer writes a `VideoStarted` queued after this clear. pub fn clear(&self, tile: u8) { @@ -219,6 +241,15 @@ impl Output { } } + /// Offers a statistics reading (ADR-0066). It never waits, and it + /// replaces a reading that has not gone out, so at most one waits and + /// no control message is held up by it. + pub fn offer_stats(&self, stats: CallStats) { + self.slots.put_stats(stats); + // A full queue means the writer is busy and will look at the slot. + let _ = self.queue.try_send(Item::Wake); + } + /// Drops the picture that waits for a tile. Call it after the tile's /// producer has stopped and before `VideoStopped`. pub fn clear_picture(&self, tile: u8) { @@ -294,6 +325,13 @@ fn write_loop_with( } wrote_picture = true; } + // The newest statistics reading, after the control messages and the + // picture of this round. + if let Some(stats) = input.slots.take_stats() + && write_message(&mut out, &FromWorker::Stats(stats)).is_err() + { + return false; + } // Diagnostic records only after every waiting control message and // picture, a few at a time, so neither waits long behind them, and // a steady stream of pictures does not stop them (ADR-0058). @@ -578,6 +616,77 @@ mod tests { )); } + fn stats_with_level(level: u8) -> CallStats { + CallStats { + microphone: Some(persephone_call_protocol::AudioSendStats { + level, + bitrate_kbps: None, + packets_sent: 0, + packets_lost: None, + jitter_ms: None, + rtt_ms: None, + }), + ..CallStats::default() + } + } + + /// GIVEN several statistics readings before the writer runs WHEN it runs + /// THEN only the newest goes out, after the control messages and the + /// waiting picture. + #[test] + fn given_stats_pile_up_when_written_then_only_the_newest_goes_after_the_rest() { + let (output, receiver) = Output::new(); + let sink = output.pictures(); + for level in 1..=5 { + output.offer_stats(stats_with_level(level)); + } + sink.put(0, 0, 1, 1, picture(1, 1, 3)); + output + .queue + .try_send(output.slots.queued(FromWorker::Left)) + .unwrap(); + drop(sink); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + let items = read_all(wire); + assert_eq!(items.len(), 3); + assert_eq!(items[0], WorkerItem::Message(FromWorker::Left)); + assert!(matches!(items[1], WorkerItem::Video { tile: 0, .. })); + assert_eq!( + items[2], + WorkerItem::Message(FromWorker::Stats(stats_with_level(5))) + ); + } + + /// GIVEN a full control queue WHEN a reading is offered THEN the offer + /// does not block and takes no place in the queue, and the reading goes + /// out after the queue drains. + #[test] + fn given_full_queue_when_stats_offered_then_it_does_not_block_or_queue() { + let (output, receiver) = Output::new(); + for _ in 0..OUTPUT_CAPACITY { + output + .queue + .try_send(output.slots.queued(FromWorker::Left)) + .unwrap(); + } + output.offer_stats(stats_with_level(9)); + assert_eq!( + output.queue.max_capacity() - output.queue.capacity(), + OUTPUT_CAPACITY + ); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + let items = read_all(wire); + assert_eq!(items.len(), OUTPUT_CAPACITY + 1); + assert_eq!( + items.last(), + Some(&WorkerItem::Message(FromWorker::Stats(stats_with_level(9)))) + ); + } + /// GIVEN pictures for several tiles WHEN the writer runs THEN the tiles take /// turns, starting after the one served last. #[test] diff --git a/crates/call-worker/src/session.rs b/crates/call-worker/src/session.rs index 320327dd..191a91db 100644 --- a/crates/call-worker/src/session.rs +++ b/crates/call-worker/src/session.rs @@ -20,8 +20,8 @@ use livekit::{ prelude::{ AudioProcessingOptions, LocalAudioTrack, LocalTrack, LocalTrackPublication, LocalVideoTrack, Participant, PlatformAudio, PlayoutDeviceId, RecordingDeviceId, - RemoteAudioTrack, RemoteParticipant, RemoteTrack, RemoteTrackPublication, TrackKind, - TrackSid, TrackSource, + RemoteAudioTrack, RemoteParticipant, RemoteTrack, RemoteTrackPublication, RemoteVideoTrack, + TrackKind, TrackSid, TrackSource, }, rtc_engine::EngineError, webrtc::{ @@ -49,6 +49,8 @@ use tokio::time::{Instant, MissedTickBehavior, interval}; use tokio_stream::StreamExt; use zeroize::Zeroizing; +mod stats_probe; + use crate::camera::{self, CapturedFrame, Format}; use crate::containment; use crate::mapping::{ @@ -67,6 +69,7 @@ use crate::video::{ fit_within_box, quarter_turns, rgba_len, }; use crate::{EXIT_DONE, EXIT_FAILED, Input}; +use stats_probe::{Sources, StatsProbe}; /// Element Call's key ring size (livekit-client keyringSize). const KEY_RING_SIZE: i32 = 256; @@ -259,6 +262,8 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) let (connect_tx, connect_done) = mpsc::channel::(usize::from(MAX_OTHER_CONNECTIONS)); // At most one sound level measurement runs, so one result can wait. let (sound_tx, mut sound_done) = mpsc::channel::>(1); + // The same for the statistics read (ADR-0066). + let (stats_tx, mut stats_done) = mpsc::channel(1); let mut others_inbox = OtherInbox { events: OtherEvents::default(), connected: connect_done, @@ -295,6 +300,7 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) playout: Playout::new(volume), microphone, sound: SoundProbe::new(sound_tx), + stats: StatsProbe::new(stats_tx), }; // Tracks subscribed during the connect get the volume now; later ones // when their subscription is handled. @@ -320,6 +326,7 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) &mut others_inbox, &mut tracker, &mut sound_done, + &mut stats_done, ) .await } @@ -1066,6 +1073,8 @@ struct Call<'a> { /// The level meters' measurement of the own and received sound /// (ADR-0055, ADR-0059). sound: SoundProbe, + /// The statistics read while the core asks for them (ADR-0066). + stats: StatsProbe, } /// Measures the own and the received sound for the level meters (ADR-0055, @@ -2012,6 +2021,7 @@ impl Call<'_> { if let Some(task) = self.sound.task.take() { task.abort(); } + self.stats.shutdown(); open_done.close(); while let Ok(done) = open_done.try_recv() { if let Ok(opened) = done.result { @@ -2587,6 +2597,75 @@ impl Call<'_> { ); } + /// Starts a read of the statistics when they are on and one is due. + fn measure_stats(&mut self) { + let Self { + stats, + room, + others, + publication, + .. + } = self; + stats.tick(Instant::now(), || { + let mut sources = Sources { + microphone: match publication.track() { + Some(LocalTrack::Audio(track)) => Some(track), + _ => None, + }, + ..Sources::default() + }; + for local in room.local_participant().track_publications().values() { + let Some(LocalTrack::Video(track)) = local.track() else { + continue; + }; + match local.source() { + TrackSource::Camera => sources.camera = Some(track), + TrackSource::Screenshare => sources.screen = Some(track), + _ => {} + } + } + let rooms = std::iter::once((0, &**room)).chain(others.open_indexed()); + let mut participants = 0; + for (connection, remote_room) in rooms { + for (identity, participant) in remote_room.remote_participants() { + if participants >= MAX_PARTICIPANTS { + return sources; + } + let identity = identity.to_string(); + if !valid_identity(&identity) { + continue; + } + participants += 1; + // The microphone, and the camera before a screen share. + let mut video: Option<(bool, RemoteVideoTrack)> = None; + for publication in participant.track_publications().values() { + match (publication.track(), publication.source()) { + (Some(RemoteTrack::Audio(track)), TrackSource::Microphone) => { + sources + .remote_audio + .push((connection, identity.clone(), track)); + } + (Some(RemoteTrack::Video(track)), source) => { + let camera = source == TrackSource::Camera; + if video + .as_ref() + .is_none_or(|(have_camera, _)| camera && !have_camera) + { + video = Some((camera, track)); + } + } + _ => {} + } + } + if let Some((_, track)) = video { + sources.remote_video.push((connection, identity, track)); + } + } + } + sources + }); + } + /// Tells the core whether a remote participant's microphone is muted. async fn send_muted( &self, @@ -2845,6 +2924,10 @@ impl Call<'_> { crate::diagnostics::global().set_on(on); Ok(Vec::new()) } + ToWorker::SetStats { on } => { + self.stats.set(on); + Ok(Vec::new()) + } ToWorker::SetCamera { on: true, remote } => { // The remote that came with this command, taken now so it // cannot go to another one: the camera channel gives them @@ -3124,6 +3207,7 @@ async fn event_loop( others: &mut OtherInbox, tracker: &mut SpeakingTracker, sound_done: &mut Receiver>, + stats_done: &mut Receiver<(u64, Option)>, ) -> End { let mut tick = interval(SPEAKING_TICK); tick.set_missed_tick_behavior(MissedTickBehavior::Delay); @@ -3208,7 +3292,17 @@ async fn event_loop( Some(levels) = sound_done.recv() => { outgoing.extend(call.sound.end(levels)); } - _ = tick.tick() => call.measure_sound(), + Some((generation, raw)) = stats_done.recv() => { + // Never queued: the newest reading waits in a slot, and the + // control messages go out before it. + if let Some(FromWorker::Stats(stats)) = call.stats.end(generation, raw) { + output.offer_stats(stats); + } + } + _ = tick.tick() => { + call.measure_sound(); + call.measure_stats(); + } } outgoing.extend(tracker.poll(Instant::now().into_std())); let disconnected = outgoing.iter().any(|message| { diff --git a/crates/call-worker/src/session/stats_probe.rs b/crates/call-worker/src/session/stats_probe.rs new file mode 100644 index 00000000..555ecd96 --- /dev/null +++ b/crates/call-worker/src/session/stats_probe.rs @@ -0,0 +1,607 @@ +//! Reads the call's WebRTC statistics for the "technical details" panel +//! (ADR-0066). +//! +//! Like [`super::SoundProbe`] it runs one read at a time, on its own task and +//! under a deadline, so the event loop never waits for it. It reads only +//! while the core has turned the statistics on, and at most once a second. +//! The task gives back plain numbers (`RawStats`); `mapping::stats` makes +//! the message from them. Nothing here keeps a track, an address or a name: +//! only the numbers that the message carries leave the parse functions. + +use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; +use std::time::Duration; + +use livekit::{ + prelude::{LocalAudioTrack, LocalVideoTrack, RemoteAudioTrack, RemoteVideoTrack}, + webrtc::stats::{QualityLimitationReason, RtcStats}, +}; +use persephone_call_protocol::{FromWorker, MAX_OTHER_CONNECTIONS, QualityLimit}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tokio::time::Instant; + +use super::read_all; +use crate::mapping::stats::{ + RawConnection, RawOwnAudio, RawOwnVideo, RawRemote, RawRemoteAudio, RawRemoteVideo, RawStats, + StatsBook, +}; + +/// The shortest time between two reads. +pub const STATS_INTERVAL: Duration = Duration::from_secs(1); +/// The time one read has for all its statistics. It is shorter than +/// [`STATS_TIMEOUT`], so the task reports what it has. +const STATS_READ_BUDGET: Duration = Duration::from_millis(700); +/// The longest one read may take altogether. +const STATS_TIMEOUT: Duration = Duration::from_millis(900); +const _: () = assert!(STATS_READ_BUDGET.as_millis() < STATS_TIMEOUT.as_millis()); +const _: () = assert!(STATS_TIMEOUT.as_millis() < STATS_INTERVAL.as_millis()); + +/// What one read looks at. The tracks are cheap handles; at most one audio +/// and one video track of each remote participant, so at most +/// `2 * MAX_PARTICIPANTS` remote reads and three own ones. +#[derive(Default)] +pub struct Sources { + pub microphone: Option, + pub camera: Option, + pub screen: Option, + pub remote_audio: Vec<(u8, String, RemoteAudioTrack)>, + pub remote_video: Vec<(u8, String, RemoteVideoTrack)>, +} + +/// The reading of one track: its statistics, or none when they could not be +/// read. +enum Read { + Microphone(Vec), + Camera(Vec), + Screen(Vec), + RemoteAudio(u8, String, Vec), + RemoteVideo(u8, String, Vec), +} + +type Job = Pin + Send>>; + +/// One read's report. Dropping it sends the numbers, or `None`, so the task +/// reports once however it ends. Only one read runs and the slot is freed +/// only by its report, so the channel has room. +struct Report { + done: mpsc::Sender<(u64, Option)>, + generation: u64, + stats: Option, +} + +impl Drop for Report { + fn drop(&mut self) { + let _ = self.done.try_send((self.generation, self.stats.take())); + } +} + +/// Reads the statistics while they are on. +pub struct StatsProbe { + done: mpsc::Sender<(u64, Option)>, + on: bool, + /// Numbers the reads, so the report of a read that was stopped never + /// frees the slot of a newer one. + generation: u64, + task: Option>, + started: Option, + /// The clock of the readings: they count from here. + base: std::time::Instant, + book: StatsBook, +} + +impl StatsProbe { + pub fn new(done: mpsc::Sender<(u64, Option)>) -> Self { + Self { + done, + on: false, + generation: 0, + task: None, + started: None, + base: std::time::Instant::now(), + book: StatsBook::default(), + } + } + + /// Turns the reads on or off (`SetStats`). Turning them on starts a new + /// series: the first reading has no rates. + pub fn set(&mut self, on: bool) { + if on == self.on { + return; + } + self.on = on; + self.generation += 1; + self.started = None; + self.book.reset(); + // A read that runs ends by its deadline and reports; its report is + // dropped by its number. The slot is freed only by that report. + } + + /// Stops a read that runs, for the end of the call. + pub fn shutdown(&mut self) { + self.on = false; + self.generation += 1; + if let Some(task) = self.task.take() { + task.abort(); + } + } + + /// Starts a read when they are on, none runs and a second has gone since + /// the last start. `sources` is only called then. + pub fn tick(&mut self, now: Instant, sources: impl FnOnce() -> Sources) { + if !self.on || self.task.is_some() { + return; + } + if self + .started + .is_some_and(|at| now.saturating_duration_since(at) < STATS_INTERVAL) + { + return; + } + self.started = Some(now); + let done = self.done.clone(); + let generation = self.generation; + let base = self.base; + let sources = sources(); + self.task = Some(tokio::spawn(async move { + let mut report = Report { + done, + generation, + stats: None, + }; + report.stats = tokio::time::timeout(STATS_TIMEOUT, read(sources, base)) + .await + .ok(); + })); + } + + /// A read reported, so the slot is free. The message to send, when the + /// read belongs to the current series and finished. + pub fn end(&mut self, generation: u64, stats: Option) -> Option { + self.task = None; + if generation != self.generation { + return None; + } + stats.map(|raw| FromWorker::Stats(self.book.next(&raw))) + } +} + +/// Reads every track at once, each under one deadline. +async fn read(sources: Sources, base: std::time::Instant) -> RawStats { + let deadline = Instant::now() + STATS_READ_BUDGET; + let mut jobs: Vec = Vec::new(); + if let Some(track) = sources.microphone { + jobs.push(Box::pin(async move { + Read::Microphone(track.get_stats().await.unwrap_or_default()) + })); + } + if let Some(track) = sources.camera { + jobs.push(Box::pin(async move { + Read::Camera(track.get_stats().await.unwrap_or_default()) + })); + } + if let Some(track) = sources.screen { + jobs.push(Box::pin(async move { + Read::Screen(track.get_stats().await.unwrap_or_default()) + })); + } + for (connection, identity, track) in sources.remote_audio { + jobs.push(Box::pin(async move { + Read::RemoteAudio( + connection, + identity, + track.get_stats().await.unwrap_or_default(), + ) + })); + } + for (connection, identity, track) in sources.remote_video { + jobs.push(Box::pin(async move { + Read::RemoteVideo( + connection, + identity, + track.get_stats().await.unwrap_or_default(), + ) + })); + } + let reads = read_all(deadline, jobs).await.into_iter().flatten(); + let at_ms = u64::try_from(base.elapsed().as_millis()).unwrap_or(u64::MAX); + assemble(at_ms, reads) +} + +/// Makes the raw reading from what the reads gave. A track whose read did +/// not finish is left out. +fn assemble(at_ms: u64, reads: impl Iterator) -> RawStats { + let mut raw = RawStats { + at_ms, + ..RawStats::default() + }; + // The first transport of the own tracks (the publisher) and of the + // remote tracks of each connection (the subscriber). + let mut publisher: Option = None; + let mut subscribers: HashMap = HashMap::new(); + let mut remotes: HashMap<(u8, String), RawRemote> = HashMap::new(); + for read in reads { + match read { + Read::Microphone(stats) => { + raw.microphone = own_audio(&stats); + publisher = publisher.or_else(|| link(&stats)); + } + Read::Camera(stats) => { + raw.camera = own_video(&stats); + publisher = publisher.or_else(|| link(&stats)); + } + Read::Screen(stats) => { + raw.screen = own_video(&stats); + publisher = publisher.or_else(|| link(&stats)); + } + Read::RemoteAudio(connection, identity, stats) => { + if let Some(link) = link(&stats) { + subscribers.entry(connection).or_insert(link); + } + remote(&mut remotes, connection, identity).audio = remote_audio(&stats); + } + Read::RemoteVideo(connection, identity, stats) => { + if let Some(link) = link(&stats) { + subscribers.entry(connection).or_insert(link); + } + remote(&mut remotes, connection, identity).video = remote_video(&stats); + } + } + } + raw.remotes = remotes.into_values().collect(); + raw.remotes + .sort_by(|a, b| (a.connection, &a.identity).cmp(&(b.connection, &b.identity))); + raw.connections = (0..=MAX_OTHER_CONNECTIONS) + .filter_map(|connection| { + let own = if connection == 0 { + publisher.as_ref() + } else { + None + }; + connection_stats(connection, own, subscribers.get(&connection)) + }) + .collect(); + raw +} + +fn remote( + remotes: &mut HashMap<(u8, String), RawRemote>, + connection: u8, + identity: String, +) -> &mut RawRemote { + remotes + .entry((connection, identity.clone())) + .or_insert_with(|| RawRemote { + connection, + identity, + audio: None, + video: None, + }) +} + +/// The numbers of one peer connection's transport and its selected pair of +/// addresses. The addresses themselves are never read. +#[derive(Clone, Debug, Default, PartialEq)] +struct Link { + bytes_sent: u64, + bytes_received: u64, + outgoing_bits_per_second: Option, + rtt_seconds: Option, +} + +fn link(stats: &[RtcStats]) -> Option { + let mut transports = stats.iter().filter_map(|stat| match stat { + RtcStats::Transport(transport) => Some(transport), + _ => None, + }); + let transport = transports.next()?; + let selected = stats.iter().find_map(|stat| match stat { + RtcStats::CandidatePair(pair) + if pair.rtc.id == transport.transport.selected_candidate_pair_id => + { + Some(&pair.candidate_pair) + } + _ => None, + }); + Some(Link { + bytes_sent: transport.transport.bytes_sent, + bytes_received: transport.transport.bytes_received, + outgoing_bits_per_second: selected + .map(|pair| pair.available_outgoing_bitrate) + .filter(|rate| *rate > 0.0), + rtt_seconds: selected + .map(|pair| pair.current_round_trip_time) + .filter(|rtt| *rtt > 0.0), + }) +} + +/// The connection's numbers: what is sent and received in total on its +/// transports, the estimate of the outgoing bandwidth, and the round-trip +/// time. `None` when no transport was read. +fn connection_stats( + connection: u8, + publisher: Option<&Link>, + subscriber: Option<&Link>, +) -> Option { + let links: Vec<&Link> = publisher.into_iter().chain(subscriber).collect(); + if links.is_empty() { + return None; + } + Some(RawConnection { + connection, + outgoing_bits_per_second: links.iter().find_map(|link| link.outgoing_bits_per_second), + bytes_sent: Some(links.iter().map(|link| link.bytes_sent).sum()), + bytes_received: Some(links.iter().map(|link| link.bytes_received).sum()), + rtt_seconds: links.iter().find_map(|link| link.rtt_seconds), + }) +} + +fn own_audio(stats: &[RtcStats]) -> Option { + let mut audio: Option = None; + for stat in stats { + if let RtcStats::OutboundRtp(outbound) = stat + && outbound.stream.kind == "audio" + { + let audio = audio.get_or_insert_with(RawOwnAudio::default); + audio.bytes_sent = audio.bytes_sent.saturating_add(outbound.sent.bytes_sent); + audio.packets_sent = audio + .packets_sent + .saturating_add(outbound.sent.packets_sent); + } + } + let audio = audio.as_mut()?; + for stat in stats { + match stat { + RtcStats::MediaSource(source) if source.source.kind == "audio" => { + audio.level = audio.level.max(source.audio.audio_level); + } + // What the far end reports of our stream. + RtcStats::RemoteInboundRtp(far) if far.stream.kind == "audio" => { + audio.packets_lost = Some(far.received.packets_lost); + audio.jitter_seconds = Some(far.received.jitter); + audio.rtt_seconds = Some(far.remote_inbound.round_trip_time); + } + _ => {} + } + } + Some(audio.clone()) +} + +fn limit(reason: QualityLimitationReason) -> QualityLimit { + match reason { + QualityLimitationReason::None => QualityLimit::None, + QualityLimitationReason::Cpu => QualityLimit::Cpu, + QualityLimitationReason::Bandwidth => QualityLimit::Bandwidth, + QualityLimitationReason::Other => QualityLimit::Other, + } +} + +/// The own video track: the bytes of every layer, and the size, frame rate +/// and limit of the largest one. +fn own_video(stats: &[RtcStats]) -> Option { + let mut video: Option = None; + let mut largest = 0_u64; + for stat in stats { + let RtcStats::OutboundRtp(outbound) = stat else { + continue; + }; + if outbound.stream.kind != "video" { + continue; + } + let size = + u64::from(outbound.outbound.frame_width) * u64::from(outbound.outbound.frame_height); + match video.as_mut() { + None => { + largest = size; + video = Some(RawOwnVideo { + fps: outbound.outbound.frames_per_second, + width: outbound.outbound.frame_width, + height: outbound.outbound.frame_height, + bytes_sent: outbound.sent.bytes_sent, + limit: limit(outbound.outbound.quality_limitation_reason), + packets_lost: None, + }); + } + Some(video) => { + video.bytes_sent = video.bytes_sent.saturating_add(outbound.sent.bytes_sent); + if size > largest { + largest = size; + video.fps = outbound.outbound.frames_per_second; + video.width = outbound.outbound.frame_width; + video.height = outbound.outbound.frame_height; + video.limit = limit(outbound.outbound.quality_limitation_reason); + } + } + } + } + let video = video.as_mut()?; + for stat in stats { + if let RtcStats::RemoteInboundRtp(far) = stat + && far.stream.kind == "video" + { + video.packets_lost = Some( + video + .packets_lost + .unwrap_or(0) + .saturating_add(far.received.packets_lost.max(0)), + ); + } + } + Some(video.clone()) +} + +fn remote_audio(stats: &[RtcStats]) -> Option { + let mut audio: Option = None; + for stat in stats { + let RtcStats::InboundRtp(inbound) = stat else { + continue; + }; + if inbound.stream.kind != "audio" { + continue; + } + let audio = audio.get_or_insert_with(RawRemoteAudio::default); + audio.level = audio.level.max(inbound.inbound.audio_level); + audio.bytes_received = audio + .bytes_received + .saturating_add(inbound.inbound.bytes_received); + audio.packets_received = audio + .packets_received + .saturating_add(inbound.received.packets_received); + audio.packets_lost = audio + .packets_lost + .saturating_add(inbound.received.packets_lost); + audio.jitter_seconds = audio.jitter_seconds.max(inbound.received.jitter); + audio.total_samples = audio + .total_samples + .saturating_add(inbound.inbound.total_samples_received); + audio.concealed_samples = audio + .concealed_samples + .saturating_add(inbound.inbound.concealed_samples); + } + audio +} + +fn remote_video(stats: &[RtcStats]) -> Option { + let mut video: Option = None; + for stat in stats { + let RtcStats::InboundRtp(inbound) = stat else { + continue; + }; + if inbound.stream.kind != "video" { + continue; + } + let video = video.get_or_insert_with(RawRemoteVideo::default); + video.fps = video.fps.max(inbound.inbound.frames_per_second); + video.width = video.width.max(inbound.inbound.frame_width); + video.height = video.height.max(inbound.inbound.frame_height); + video.bytes_received = video + .bytes_received + .saturating_add(inbound.inbound.bytes_received); + video.frames_dropped = video + .frames_dropped + .saturating_add(u64::from(inbound.inbound.frames_dropped)); + video.packets_lost = video + .packets_lost + .saturating_add(inbound.received.packets_lost); + } + video +} + +#[cfg(test)] +mod tests { + use super::*; + + fn probe() -> (StatsProbe, mpsc::Receiver<(u64, Option)>) { + let (tx, rx) = mpsc::channel(1); + (StatsProbe::new(tx), rx) + } + + /// Starts a read at `now` and counts the calls of the source builder. + fn tick(probe: &mut StatsProbe, now: Instant) -> usize { + let mut built = 0; + probe.tick(now, || { + built += 1; + Sources::default() + }); + built + } + + /// GIVEN the statistics are off WHEN a tick comes THEN nothing is built + /// or read. + #[tokio::test] + async fn given_statistics_off_when_ticked_then_nothing_is_read() { + let (mut probe, mut reports) = probe(); + assert_eq!(tick(&mut probe, Instant::now()), 0); + assert!(reports.try_recv().is_err()); + } + + /// GIVEN the statistics are on WHEN ticks come THEN one read starts, no + /// other starts while it runs or within a second, and the report frees + /// the slot and gives one message. + #[tokio::test] + async fn given_statistics_on_when_ticked_then_one_read_runs_at_most_once_a_second() { + let (mut probe, mut reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + assert_eq!(tick(&mut probe, start), 0, "one read at a time"); + let (generation, raw) = reports.recv().await.unwrap(); + let message = probe.end(generation, raw); + assert!(matches!(message, Some(FromWorker::Stats(_)))); + assert_eq!( + tick(&mut probe, start + Duration::from_millis(900)), + 0, + "less than a second since the last start" + ); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1); + probe.shutdown(); + } + + /// GIVEN a read that runs WHEN the statistics go off and on again THEN + /// the old read's report gives no message and the slot stays taken until + /// it reports, so two reads never run together. + #[tokio::test] + async fn given_a_switch_during_a_read_when_it_reports_then_the_old_report_is_dropped() { + let (mut probe, mut reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + probe.set(false); + probe.set(true); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 0, "still reading"); + let (generation, raw) = reports.recv().await.unwrap(); + assert!(probe.end(generation, raw).is_none(), "an old series"); + assert_eq!( + tick(&mut probe, start + STATS_INTERVAL), + 1, + "a new one starts" + ); + probe.shutdown(); + } + + /// GIVEN a read that did not finish WHEN it reports nothing THEN no + /// message goes and the next read can start. + #[tokio::test] + async fn given_a_read_that_did_not_finish_then_no_message_and_the_slot_is_free() { + let (mut probe, _reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + assert!(probe.end(probe.generation, None).is_none()); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1); + probe.shutdown(); + } + + /// GIVEN the call ends WHEN the probe shuts down THEN no read starts + /// again, even when a tick comes. + #[tokio::test] + async fn given_shutdown_when_ticked_then_no_read_starts() { + let (mut probe, _reports) = probe(); + probe.set(true); + probe.shutdown(); + assert_eq!(tick(&mut probe, Instant::now()), 0); + } + + /// GIVEN reads that hold no statistics WHEN the reading is assembled THEN + /// a track with nothing to show has no entry and no connection is made + /// up. + #[test] + fn given_a_connection_without_transports_when_assembled_then_it_has_no_entry() { + let raw = assemble(5, std::iter::empty()); + assert_eq!(raw.at_ms, 5); + assert!(raw.connections.is_empty() && raw.remotes.is_empty()); + let raw = assemble( + 6, + [ + Read::Microphone(Vec::new()), + Read::RemoteAudio(1, "x".into(), Vec::new()), + ] + .into_iter(), + ); + assert!(raw.microphone.is_none(), "no outbound statistic, no entry"); + assert_eq!(raw.remotes.len(), 1); + assert!(raw.remotes[0].audio.is_none()); + assert!(raw.connections.is_empty()); + } +} From e323a6c8294a6dec1cc086d84dcc5e426de56a92 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 01:37:27 +0000 Subject: [PATCH 14/51] Add the call statistics DTOs Co-Authored-By: Claude Opus 5.5 --- crates/contracts/generated/contracts.ts | 68 ++++++++ crates/contracts/src/lib.rs | 189 +++++++++++++++++++++++ crates/contracts/tests/contracts.rs | 169 ++++++++++++++++++++ crates/contracts/tests/type-contracts.ts | 12 ++ 4 files changed, 438 insertions(+) diff --git a/crates/contracts/generated/contracts.ts b/crates/contracts/generated/contracts.ts index 47569945..8e47d641 100644 --- a/crates/contracts/generated/contracts.ts +++ b/crates/contracts/generated/contracts.ts @@ -117,6 +117,74 @@ muted: boolean, }; export type CallParticipantLevel = { userId: string, deviceId: string, level: number, }; +export type CallStatsLimit = "none" | "cpu" | "bandwidth" | "other"; + +export type CallStatsAudioSent = { +/** + * 0 to [`CALL_SOUND_LEVEL_MAX`]. + */ +level: number, +/** + * Kbit/s, at most [`CALL_STATS_KBPS_MAX`]. + */ +bitrateKbps: number | null, packetsSent: number, +/** + * Packets the far end reports lost. + */ +packetsLost: number | null, +/** + * Milliseconds, at most [`CALL_STATS_MS_MAX`]. + */ +jitterMs: number | null, rttMs: number | null, }; + +export type CallStatsVideoSent = { +/** + * At most [`CALL_STATS_FPS_MAX`]. + */ +fps: number, +/** + * At most [`CALL_STATS_SIDE_MAX`] each. + */ +width: number, height: number, bitrateKbps: number | null, limit: CallStatsLimit, packetsLost: number | null, }; + +export type CallStatsAudioReceived = { +/** + * 0 to [`CALL_SOUND_LEVEL_MAX`]. + */ +level: number, bitrateKbps: number | null, packetsReceived: number, packetsLost: number, jitterMs: number, +/** + * The share of the last second's samples that WebRTC made up, 0 to 100. + */ +concealedPercent: number | null, }; + +export type CallStatsVideoReceived = { fps: number, width: number, height: number, bitrateKbps: number | null, +/** + * Frames dropped each second, at most [`CALL_STATS_FPS_MAX`]. + */ +droppedFps: number | null, packetsLost: number, }; + +export type CallStatsParticipant = { userId: string, deviceId: string, audio: CallStatsAudioReceived | null, video: CallStatsVideoReceived | null, }; + +export type CallStatsConnection = { connection: number, +/** + * The bandwidth that WebRTC estimates for sending, kbit/s. + */ +outgoingKbps: number | null, +/** + * Everything sent and received on the connection, kbit/s. + */ +sendKbps: number | null, receiveKbps: number | null, rttMs: number | null, }; + +export type CallStats = { microphone: CallStatsAudioSent | null, camera: CallStatsVideoSent | null, screen: CallStatsVideoSent | null, +/** + * At most [`CALL_PARTICIPANTS_MAX`], each device once. + */ +participants: Array, +/** + * At most [`CALL_STATS_CONNECTIONS_MAX`], each connection once. + */ +connections: Array, }; + export type CallDeviceTestKind = "microphone" | "speaker" | "camera"; export type CallDeviceTestState = "idle" | "starting" | "running" | "done" | "not_found" | "denied" | "unsupported" | "unavailable" | "in_call" | "failed"; diff --git a/crates/contracts/src/lib.rs b/crates/contracts/src/lib.rs index 3dc54336..a816ecfa 100644 --- a/crates/contracts/src/lib.rs +++ b/crates/contracts/src/lib.rs @@ -2455,6 +2455,187 @@ pub struct CallParticipantLevel { pub level: u8, } +/// The highest bitrate or bandwidth a call statistic shows, in kbit/s. +pub const CALL_STATS_KBPS_MAX: u32 = 1_000_000; +/// The longest time a call statistic shows, in milliseconds. +pub const CALL_STATS_MS_MAX: u16 = 60_000; +/// The highest frame rate a call statistic shows. +pub const CALL_STATS_FPS_MAX: u8 = 120; +/// The longest picture side a call statistic shows, in pixels. +pub const CALL_STATS_SIDE_MAX: u16 = 16_384; +/// The most connections one reading describes: the own call server and the +/// other call servers of ADR-0054. +pub const CALL_STATS_CONNECTIONS_MAX: usize = 4; + +/// Why a sent video runs below what was asked, as WebRTC reports it. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CallStatsLimit { + None, + Cpu, + Bandwidth, + Other, +} + +/// The own microphone. An unknown value is null: a rate needs two readings, +/// and the far end reports loss, jitter and round-trip time later. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsAudioSent { + /// 0 to [`CALL_SOUND_LEVEL_MAX`]. + pub level: u8, + /// Kbit/s, at most [`CALL_STATS_KBPS_MAX`]. + pub bitrate_kbps: Option, + pub packets_sent: u32, + /// Packets the far end reports lost. + pub packets_lost: Option, + /// Milliseconds, at most [`CALL_STATS_MS_MAX`]. + pub jitter_ms: Option, + pub rtt_ms: Option, +} + +/// The own camera or screen share. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsVideoSent { + /// At most [`CALL_STATS_FPS_MAX`]. + pub fps: u8, + /// At most [`CALL_STATS_SIDE_MAX`] each. + pub width: u16, + pub height: u16, + pub bitrate_kbps: Option, + pub limit: CallStatsLimit, + pub packets_lost: Option, +} + +/// The audio of another device in the call. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsAudioReceived { + /// 0 to [`CALL_SOUND_LEVEL_MAX`]. + pub level: u8, + pub bitrate_kbps: Option, + pub packets_received: u32, + pub packets_lost: u32, + pub jitter_ms: u16, + /// The share of the last second's samples that WebRTC made up, 0 to 100. + pub concealed_percent: Option, +} + +/// The video of another device in the call. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsVideoReceived { + pub fps: u8, + pub width: u16, + pub height: u16, + pub bitrate_kbps: Option, + /// Frames dropped each second, at most [`CALL_STATS_FPS_MAX`]. + pub dropped_fps: Option, + pub packets_lost: u32, +} + +/// One other device in the call, by the IDs of the call status. The IDs are +/// validated Matrix IDs (untrusted, shown as text). +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsParticipant { + pub user_id: String, + pub device_id: String, + pub audio: Option, + pub video: Option, +} + +/// One connection to a call server: 0 is the own one, 1 to 3 are other ones +/// (ADR-0054). +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsConnection { + pub connection: u8, + /// The bandwidth that WebRTC estimates for sending, kbit/s. + pub outgoing_kbps: Option, + /// Everything sent and received on the connection, kbit/s. + pub send_kbps: Option, + pub receive_kbps: Option, + pub rtt_ms: Option, +} + +/// The call's technical details, read about once a second while the call +/// window shows them (ADR-0066). Numbers with units only: no address, port, +/// codec or other text but the IDs of the devices. +#[derive(Clone, Debug, Default, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStats { + pub microphone: Option, + pub camera: Option, + pub screen: Option, + /// At most [`CALL_PARTICIPANTS_MAX`], each device once. + pub participants: Vec, + /// At most [`CALL_STATS_CONNECTIONS_MAX`], each connection once. + pub connections: Vec, +} + +impl CallStats { + /// Whether every number is inside its bound, the lists are inside their + /// limits, no device or connection comes twice and the IDs fit. A reading + /// that fails is dropped whole, never cut. + pub fn within_limits(&self) -> bool { + let kbps = |value: Option| value.is_none_or(|value| value <= CALL_STATS_KBPS_MAX); + let millis = |value: Option| value.is_none_or(|value| value <= CALL_STATS_MS_MAX); + let sent_audio = |audio: &CallStatsAudioSent| { + audio.level <= CALL_SOUND_LEVEL_MAX + && kbps(audio.bitrate_kbps) + && millis(audio.jitter_ms) + && millis(audio.rtt_ms) + }; + let sent_video = |video: &CallStatsVideoSent| { + video.fps <= CALL_STATS_FPS_MAX + && video.width <= CALL_STATS_SIDE_MAX + && video.height <= CALL_STATS_SIDE_MAX + && kbps(video.bitrate_kbps) + }; + let audio = |audio: &CallStatsAudioReceived| { + audio.level <= CALL_SOUND_LEVEL_MAX + && kbps(audio.bitrate_kbps) + && audio.jitter_ms <= CALL_STATS_MS_MAX + && audio.concealed_percent.is_none_or(|percent| percent <= 100) + }; + let video = |video: &CallStatsVideoReceived| { + video.fps <= CALL_STATS_FPS_MAX + && video.width <= CALL_STATS_SIDE_MAX + && video.height <= CALL_STATS_SIDE_MAX + && kbps(video.bitrate_kbps) + && video + .dropped_fps + .is_none_or(|fps| fps <= CALL_STATS_FPS_MAX) + }; + self.microphone.as_ref().is_none_or(sent_audio) + && self.camera.as_ref().is_none_or(sent_video) + && self.screen.as_ref().is_none_or(sent_video) + && self.participants.len() <= CALL_PARTICIPANTS_MAX + && self.participants.iter().enumerate().all(|(index, person)| { + person.user_id.len() <= CALL_USER_ID_BYTES_MAX + && person.device_id.len() <= CALL_DEVICE_ID_BYTES_MAX + && person.audio.as_ref().is_none_or(audio) + && person.video.as_ref().is_none_or(video) + && !self.participants[..index].iter().any(|seen| { + seen.user_id == person.user_id && seen.device_id == person.device_id + }) + }) + && self.connections.len() <= CALL_STATS_CONNECTIONS_MAX + && self.connections.iter().enumerate().all(|(index, link)| { + link.connection < 4 + && kbps(link.outgoing_kbps) + && kbps(link.send_kbps) + && kbps(link.receive_kbps) + && millis(link.rtt_ms) + && !self.connections[..index] + .iter() + .any(|seen| seen.connection == link.connection) + }) + } +} + /// What a device test checks (ADR-0059). #[derive(Clone, Copy, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -2918,6 +3099,14 @@ pub fn generated_typescript() -> String { format!("export {}", CallPhase::decl(&config)), format!("export {}", CallParticipant::decl(&config)), format!("export {}", CallParticipantLevel::decl(&config)), + format!("export {}", CallStatsLimit::decl(&config)), + format!("export {}", CallStatsAudioSent::decl(&config)), + format!("export {}", CallStatsVideoSent::decl(&config)), + format!("export {}", CallStatsAudioReceived::decl(&config)), + format!("export {}", CallStatsVideoReceived::decl(&config)), + format!("export {}", CallStatsParticipant::decl(&config)), + format!("export {}", CallStatsConnection::decl(&config)), + format!("export {}", CallStats::decl(&config)), format!("export {}", CallDeviceTestKind::decl(&config)), format!("export {}", CallDeviceTestState::decl(&config)), format!("export {}", CallDeviceTestStatus::decl(&config)), diff --git a/crates/contracts/tests/contracts.rs b/crates/contracts/tests/contracts.rs index d876b1e4..9bf17d7a 100644 --- a/crates/contracts/tests/contracts.rs +++ b/crates/contracts/tests/contracts.rs @@ -1004,3 +1004,172 @@ fn linux_vault_reasons_are_fixed_store_codes() { } assert!(serde_json::from_value::(serde_json::json!("no_keyring")).is_err()); } + +fn sample_call_stats() -> persephone_contracts::CallStats { + use persephone_contracts::{ + CallStats, CallStatsAudioReceived, CallStatsAudioSent, CallStatsConnection, CallStatsLimit, + CallStatsParticipant, CallStatsVideoReceived, CallStatsVideoSent, + }; + CallStats { + microphone: Some(CallStatsAudioSent { + level: 100, + bitrate_kbps: Some(32), + packets_sent: u32::MAX, + packets_lost: None, + jitter_ms: Some(60_000), + rtt_ms: Some(40), + }), + camera: Some(CallStatsVideoSent { + fps: 120, + width: 16_384, + height: 1, + bitrate_kbps: Some(1_000_000), + limit: CallStatsLimit::Bandwidth, + packets_lost: Some(3), + }), + screen: None, + participants: vec![CallStatsParticipant { + user_id: "@bob:example.invalid".into(), + device_id: "BOBDEV".into(), + audio: Some(CallStatsAudioReceived { + level: 5, + bitrate_kbps: None, + packets_received: 10, + packets_lost: 0, + jitter_ms: 4, + concealed_percent: Some(100), + }), + video: Some(CallStatsVideoReceived { + fps: 30, + width: 1280, + height: 720, + bitrate_kbps: Some(900), + dropped_fps: Some(120), + packets_lost: 1, + }), + }], + connections: vec![CallStatsConnection { + connection: 3, + outgoing_kbps: None, + send_kbps: Some(1), + receive_kbps: None, + rtt_ms: Some(60_000), + }], + } +} + +/// GIVEN a statistics reading at every bound WHEN it crosses the wire THEN +/// it round-trips with camelCase names, unknown fields are refused, and the +/// bound itself passes `within_limits`. +#[test] +fn call_stats_cross_with_camel_case_names_and_refuse_unknown_fields() { + let stats = sample_call_stats(); + assert!(stats.within_limits()); + let json = serde_json::to_value(&stats).unwrap(); + assert_eq!(json["microphone"]["packetsSent"], u32::MAX); + assert_eq!(json["camera"]["limit"], "bandwidth"); + assert_eq!(json["participants"][0]["video"]["droppedFps"], 120); + assert!(json["screen"].is_null()); + assert_eq!( + serde_json::from_value::(json.clone()).unwrap(), + stats + ); + for path in [ + "/microphone", + "/participants/0", + "/participants/0/audio", + "/connections/0", + ] { + let mut extra = json.clone(); + extra.pointer_mut(path).unwrap()["address"] = "10.0.0.1".into(); + assert!( + serde_json::from_value::(extra).is_err(), + "{path}" + ); + } +} + +/// GIVEN a statistics reading with one value over its bound, too many or +/// repeated entries, or an overlong ID WHEN it is checked THEN it is +/// refused whole. +#[test] +fn call_stats_over_their_bounds_are_refused_whole() { + use persephone_contracts::{ + CALL_DEVICE_ID_BYTES_MAX, CALL_PARTICIPANTS_MAX, CALL_STATS_CONNECTIONS_MAX, + CALL_USER_ID_BYTES_MAX, CallStats, + }; + let edits: [(&str, Box); 12] = [ + ( + "level", + Box::new(|s| s.microphone.as_mut().unwrap().level = 101), + ), + ( + "bitrate", + Box::new(|s| s.camera.as_mut().unwrap().bitrate_kbps = Some(1_000_001)), + ), + ("fps", Box::new(|s| s.camera.as_mut().unwrap().fps = 121)), + ( + "side", + Box::new(|s| s.camera.as_mut().unwrap().height = 16_385), + ), + ( + "jitter", + Box::new(|s| s.microphone.as_mut().unwrap().jitter_ms = Some(60_001)), + ), + ( + "concealed", + Box::new(|s| { + s.participants[0].audio.as_mut().unwrap().concealed_percent = Some(101); + }), + ), + ( + "dropped", + Box::new(|s| s.participants[0].video.as_mut().unwrap().dropped_fps = Some(121)), + ), + ("rtt", Box::new(|s| s.connections[0].rtt_ms = Some(60_001))), + ( + "connection number", + Box::new(|s| s.connections[0].connection = 4), + ), + ( + "user id", + Box::new(|s| s.participants[0].user_id = "u".repeat(CALL_USER_ID_BYTES_MAX + 1)), + ), + ( + "device id", + Box::new(|s| s.participants[0].device_id = "d".repeat(CALL_DEVICE_ID_BYTES_MAX + 1)), + ), + ( + "same device twice", + Box::new(|s| { + let again = s.participants[0].clone(); + s.participants.push(again); + }), + ), + ]; + for (name, edit) in edits { + let mut stats = sample_call_stats(); + edit(&mut stats); + assert!(!stats.within_limits(), "{name}"); + } + let mut many = sample_call_stats(); + let one = many.participants[0].clone(); + many.participants = (0..=CALL_PARTICIPANTS_MAX) + .map(|index| persephone_contracts::CallStatsParticipant { + device_id: format!("D{index}"), + ..one.clone() + }) + .collect(); + assert!(!many.within_limits(), "too many devices"); + many.participants.truncate(CALL_PARTICIPANTS_MAX); + assert!(many.within_limits()); + let mut links = sample_call_stats(); + let first = links.connections[0].clone(); + links.connections = (0..=CALL_STATS_CONNECTIONS_MAX) + .map(|index| persephone_contracts::CallStatsConnection { + connection: u8::try_from(index).unwrap(), + ..first.clone() + }) + .collect(); + assert!(!links.within_limits(), "too many connections"); +} diff --git a/crates/contracts/tests/type-contracts.ts b/crates/contracts/tests/type-contracts.ts index 0042832c..a1afc563 100644 --- a/crates/contracts/tests/type-contracts.ts +++ b/crates/contracts/tests/type-contracts.ts @@ -11,6 +11,7 @@ import type { CallReadiness, CallStatus, CallParticipantLevel, + CallStats, CallDeviceTestKind, CallDeviceTestState, CallDeviceTestStatus, @@ -299,6 +300,17 @@ const unknownDeviceChange: CallStatus = { ...idleCall, deviceChange: "unplugged" const levelList: CallParticipantLevel[] = [{ userId: "@a:s", deviceId: "D", level: 40 }]; // @ts-expect-error a level carries the device and a number, nothing else const levelWithName: CallParticipantLevel = { ...levelList[0], name: "x" }; +const detailsTable: CallStats = { + microphone: { level: 40, bitrateKbps: null, packetsSent: 3, packetsLost: null, jitterMs: null, rttMs: null }, + camera: null, + screen: null, + participants: [{ userId: "@a:s", deviceId: "D", audio: null, video: null }], + connections: [{ connection: 0, outgoingKbps: null, sendKbps: 40, receiveKbps: null, rttMs: 20 }], +}; +// @ts-expect-error statistics carry numbers and IDs, never an address or a codec name +const detailsWithAddress: CallStats = { ...detailsTable, connections: [{ ...detailsTable.connections[0], address: "10.0.0.1" }] }; +// @ts-expect-error an unknown value is null, not missing +const detailsMissingValue: CallStats = { ...detailsTable, microphone: { level: 1, packetsSent: 3, packetsLost: null, jitterMs: null, rttMs: null } }; const testStatus: CallDeviceTestStatus = { id: 4, test: "camera", state: "running", stream: 2 }; // @ts-expect-error the test ID is required const noTestId: CallDeviceTestStatus = { test: "camera", state: "running", stream: 2 }; From 315f1d78d4472d1fd4811b74d688a04e7049510e Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 01:45:12 +0000 Subject: [PATCH 15/51] Forward call statistics from the core only while the call window asks Adds the call_stats command and call_stats event. The switch is off at every call start, and turned off when the call ends or the UI connection closes. Only the newest reading waits. Co-Authored-By: Claude Opus 5.5 --- crates/core-protocol/src/lib.rs | 87 +++++++++ crates/core/src/calls/controller.rs | 268 +++++++++++++++++++++++++++- crates/core/src/calls/mod.rs | 1 + crates/core/src/calls/stats.rs | 218 ++++++++++++++++++++++ crates/core/src/lib.rs | 94 ++++++++++ 5 files changed, 665 insertions(+), 3 deletions(-) create mode 100644 crates/core/src/calls/stats.rs diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index c16b439d..edab3bfa 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -768,6 +768,13 @@ pub enum Call { auto_level: bool, gain: u16, }, + /// Start or stop the call statistics (ADR-0066). While on, the core + /// asks the worker to read them and sends [`Event::CallStats`], at most + /// about once a second. Only the call window may send it. Off at every + /// call start, and off again when the call ends. Replies `null`. + CallStats { + on: bool, + }, /// Turn the camera on or off during a call. Replies `CallStatus`, with the /// camera `starting` when turned on; the worker's answer arrives as /// [`Event::CallChanged`]. Refused when no call is connected. @@ -1117,6 +1124,14 @@ pub enum Event { #[serde(deserialize_with = "bounded_levels")] levels: Vec, }, + /// The call's technical details (ADR-0066), sent only while + /// [`Call::CallStats`] is on: numbers with units, and the validated IDs + /// of the devices. Coalesced: only the newest waits. A reading that is + /// out of bounds is refused whole. + CallStats { + #[serde(deserialize_with = "bounded_stats")] + stats: persephone_contracts::CallStats, + }, /// A device test started, changed or ended (ADR-0059): ask for /// `call_device_test_status`. Content-free and coalesced. CallDeviceTestChanged {}, @@ -1161,6 +1176,20 @@ pub fn levels_within_limits(levels: &[persephone_contracts::CallParticipantLevel }) } +/// Reads a statistics reading and refuses one with a number over its bound, +/// too many or repeated entries or an overlong ID. The frame that carries it +/// is already bounded by the transport. +fn bounded_stats<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + let stats = persephone_contracts::CallStats::deserialize(deserializer)?; + if stats.within_limits() { + Ok(stats) + } else { + Err(serde::de::Error::custom("call statistics out of bounds")) + } +} + /// Reads a level list and refuses an entry past [`MAX_CALL_LEVELS`], an /// overlong ID or a level out of range before it keeps it, so a hostile list /// allocates at most the limits. @@ -2349,6 +2378,10 @@ mod tests { Call::CallScreen { on: true }, r#"{"id":1,"call":{"command":"call_screen","on":true}}"#, ), + ( + Call::CallStats { on: true }, + r#"{"id":1,"call":{"command":"call_stats","on":true}}"#, + ), ( Call::CallVideoFrame { tile: 4, @@ -4151,6 +4184,60 @@ mod timeline_events_wire_tests { ); } + /// GIVEN the statistics command WHEN it is decoded THEN it carries only + /// the flag. + #[test] + fn given_the_stats_command_then_it_carries_only_the_flag() { + let decoded = |json: &[u8]| serde_json::from_slice::(json); + assert!(decoded(br#"{"id":1,"call":{"command":"call_stats","on":true}}"#).is_ok()); + assert!(decoded(br#"{"id":1,"call":{"command":"call_stats","on":false}}"#).is_ok()); + for json in [ + &br#"{"id":1,"call":{"command":"call_stats"}}"#[..], + br#"{"id":1,"call":{"command":"call_stats","on":1}}"#, + br#"{"id":1,"call":{"command":"call_stats","on":true,"interval":1}}"#, + ] { + assert!(decoded(json).is_err(), "{}", String::from_utf8_lossy(json)); + } + } + + /// GIVEN statistics events WHEN read THEN a reading inside its bounds + /// is kept, and one with a number over its bound, an overlong ID, a + /// repeated device or an unknown field is refused whole. + #[test] + fn given_call_stats_events_then_only_bounded_readings_are_read() { + let event = |stats: serde_json::Value| { + serde_json::from_value::( + serde_json::json!({"event": {"call_stats": {"stats": stats}}}), + ) + }; + let reading = |fps: u32, user: &str| { + serde_json::json!({ + "microphone": null, + "camera": {"fps": fps, "width": 640, "height": 360, "bitrateKbps": null, + "limit": "none", "packetsLost": null}, + "screen": null, + "participants": [{"userId": user, "deviceId": "D", "audio": null, "video": null}], + "connections": [], + }) + }; + assert!(event(reading(120, "@a:example.org")).is_ok()); + assert!(event(reading(121, "@a:example.org")).is_err()); + assert!(event(reading(1, &"a".repeat(MAX_USER_ID_BYTES + 1))).is_err()); + let mut twice = reading(1, "@a:example.org"); + let again = twice["participants"][0].clone(); + twice["participants"].as_array_mut().unwrap().push(again); + assert!(event(twice).is_err()); + let mut extra = reading(1, "@a:example.org"); + extra["address"] = "10.0.0.1".into(); + assert!(event(extra).is_err()); + let wire = serde_json::to_string(&CoreMessage::Event(Event::CallStats { + stats: persephone_contracts::CallStats::default(), + })) + .unwrap(); + assert!(wire.starts_with(r#"{"event":{"call_stats":{"stats":{"microphone":null"#)); + assert!(serde_json::from_str::(&wire).is_ok()); + } + /// GIVEN call level events WHEN read THEN bounded ones are kept, and a /// level over the top, too many devices or an overlong ID is refused. #[test] diff --git a/crates/core/src/calls/controller.rs b/crates/core/src/calls/controller.rs index 39f47138..ca6a18f4 100644 --- a/crates/core/src/calls/controller.rs +++ b/crates/core/src/calls/controller.rs @@ -29,6 +29,7 @@ use super::readiness::{Discovery, Flow, TurnServers, sfu_transport, turn_servers use super::rings::{self, Plan as RingPlan, Watch}; use super::screen::{ScreenGrant, ScreenRefusal, ScreenSource}; use super::sfu::{self, OpenIdToken, SfuError, SfuGrant}; +use super::stats; use super::status::can_send_member_state; use super::video::{Notifier, Picture, VideoStore}; use super::worker::{ @@ -54,7 +55,8 @@ use persephone_call_protocol::{ }; use persephone_contracts::{ CALL_PARTICIPANTS_MAX, CallCamera, CallDeviceChange, CallDeviceTestKind, CallDeviceTestState, - CallDeviceTestStatus, CallParticipantLevel, CallParticipantRef, CallScreen, CallVideoTile, + CallDeviceTestStatus, CallParticipantLevel, CallParticipantRef, CallScreen, CallStats, + CallVideoTile, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet, VecDeque}, @@ -663,12 +665,14 @@ impl View { fn apply(&mut self, event: &FromWorker) -> Applied { match event { // A record goes to the diagnostic log, never to the view. - // A sound level goes to the level meters, never to the view. + // A sound level goes to the level meters, never to the view; the + // statistics go to their own listener (ADR-0066). FromWorker::Ready { .. } | FromWorker::ParticipantJoined { .. } | FromWorker::Diagnostic { .. } | FromWorker::SoundLevel { .. } - | FromWorker::ParticipantLevel { .. } => Applied::Same, + | FromWorker::ParticipantLevel { .. } + | FromWorker::Stats(_) => Applied::Same, FromWorker::ParticipantMuted { connection, identity, @@ -1175,6 +1179,10 @@ enum Command { type Listener = Arc; /// Takes the call's sound levels (ADR-0055, ADR-0059). pub type SoundListener = Arc; +/// Takes the call's technical details (ADR-0066): the newest reading, or +/// `None` when there is none any more (the statistics went off, or the call +/// ended). It must not block and must not call the controller. +pub type StatsListener = Arc) + Send + Sync>; /// A member as the page names it: user ID and device ID. type CallParticipantLevelKey = (String, String); @@ -1203,6 +1211,13 @@ struct Inner { /// Takes each sound level of the running call; see /// [`CallController::set_sound_listener`]. sound_listener: Mutex>, + /// Whether the page shows the technical details (ADR-0066). Only a + /// running or joining call can have it on, and the end of the call turns + /// it off under the slot lock. + stats_on: watch::Sender, + /// Takes each statistics reading of the running call; see + /// [`CallController::set_stats_listener`]. + stats_listener: Mutex>, /// The picture store of the running worker, from its start to the end of /// the call or join, or of a camera test while no call runs (ADR-0059). video: Mutex>, @@ -1347,6 +1362,12 @@ impl Inner { *slot = Slot::Idle; // Under the slot lock, so a later join cannot meet this close. self.close_video(); + // The details never carry over to another call (ADR-0066). + self.stats_on.send_replace(false); + } + drop(slot); + if mine && let Some(listener) = plain(&self.stats_listener).clone() { + listener(None); } mine } @@ -1408,6 +1429,8 @@ impl CallController { listener: Mutex::new(None), video_listener: Mutex::new(None), sound_listener: Mutex::new(None), + stats_on: watch::channel(false).0, + stats_listener: Mutex::new(None), video: Mutex::new(None), next_id: AtomicU64::new(0), device_test: Mutex::new(DeviceTestSlot::default()), @@ -1442,6 +1465,34 @@ impl CallController { *plain(&self.inner.sound_listener) = Some(listener); } + /// Sets what takes the call's statistics readings (ADR-0066). It is + /// called from the call task with the newest reading while they are on, + /// and with `None` when they stop. + pub fn set_stats_listener(&self, listener: StatsListener) { + *plain(&self.inner.stats_listener) = Some(listener); + } + + /// Turns the call's technical details on or off (ADR-0066): the worker + /// reads its statistics only while they are on. Turning them on needs a + /// running or joining call (`NotInCall` otherwise); off always works. + /// They are off again when the call ends. + pub fn set_stats(&self, on: bool) -> Result<(), CallError> { + let slot = self.inner.slot(); + if on && matches!(&*slot, Slot::Idle) { + return Err(CallError::NotInCall); + } + // Under the slot lock, so the end of a call cannot meet a late `on`. + let was = self.inner.stats_on.send_replace(on); + drop(slot); + if was + && !on + && let Some(listener) = plain(&self.inner.stats_listener).clone() + { + listener(None); + } + Ok(()) + } + /// Calls `listener` after each change of the device test's status, on /// the test's thread. It must not block and must not call the controller. pub fn set_test_listener(&self, listener: Listener) { @@ -3567,6 +3618,19 @@ impl Call { self.participant_level(inner, *connection, identity, *level); return Ok(()); } + // The technical details go to the page only while it asks for them + // (ADR-0066); a reading that comes after they went off is dropped. + if let FromWorker::Stats(stats) = event { + if *inner.stats_on.borrow() + && let Some(listener) = plain(&inner.stats_listener).clone() + && let Some(view) = stats::view(stats, |connection, identity| { + self.view.level_member(connection, identity) + }) + { + listener(Some(view)); + } + return Ok(()); + } // A camera that is not on has no capture left: its remote is used up. // An `On` after a remote went (and no off since) is a capture over it. if let FromWorker::Camera { state } = event { @@ -3878,6 +3942,28 @@ impl Call { Ok(()) } + /// Gives the worker the statistics switch in `pending` (ADR-0066). A + /// value that the worker already has is not sent again. When the queue + /// is full, the switch waits for the next retry instead of ending the + /// call; a newer value replaces a waiting one. + fn apply_stats( + &self, + pending: &mut Option<(Instant, bool)>, + sent: &mut bool, + ) -> Result<(), EndReason> { + if let Some((_, on)) = pending.take() { + if on == *sent { + return Ok(()); + } + if self.queue_worker(ToWorker::SetStats { on })? { + *sent = on; + } else { + *pending = Some((Instant::now() + UNSENT_RETRY, on)); + } + } + Ok(()) + } + /// Sends the pending device choice (ADR-0059). A full queue keeps it for /// a retry, so a busy worker does not end the call; a newer choice /// replaces it. @@ -4066,6 +4152,12 @@ impl Call { let mut diagnostics = crate::diagnostics::global().watch(); diagnostics.mark_changed(); let mut pending_diagnostics: Option<(Instant, bool)> = None; + // The statistics switch (ADR-0066), sent on each change. The worker + // starts with it off, so `stats_sent` starts off too. + let mut stats_switch = inner.stats_on.subscribe(); + stats_switch.mark_changed(); + let mut pending_stats: Option<(Instant, bool)> = None; + let mut stats_sent = false; // The newest device choice while the worker's queue is full. let mut pending_devices: Option<(Instant, DeviceChoice)> = None; self.start_keys(inner).await?; @@ -4079,6 +4171,7 @@ impl Call { let due = pending_own.as_ref().map(|(at, _)| *at); let retry = self.unsent_retry; let diagnostics_due = pending_diagnostics.map(|(at, _)| at); + let stats_due = pending_stats.map(|(at, _)| at); let devices_due = pending_devices.as_ref().map(|(at, _)| *at); tokio::select! { _ = &mut *stop => return Ok(()), @@ -4140,6 +4233,17 @@ impl Call { None => std::future::pending().await, } } => self.apply_diagnostics(&mut pending_diagnostics)?, + Ok(()) = stats_switch.changed() => { + let on = *stats_switch.borrow_and_update(); + pending_stats = Some((Instant::now(), on)); + self.apply_stats(&mut pending_stats, &mut stats_sent)?; + } + () = async { + match stats_due { + Some(at) => time::sleep_until(at.into()).await, + None => std::future::pending().await, + } + } => self.apply_stats(&mut pending_stats, &mut stats_sent)?, remote = portal_done(&mut self.portal) => self.portal_finished(inner, remote)?, (picked, cancelled) = screen_pick_done(&mut self.screen_pick) => { if cancelled { @@ -6734,6 +6838,164 @@ mod tests { assert_eq!(changes.load(Ordering::SeqCst), before); } + /// A slot with a running call, for the statistics switch. + fn run_slot(calls: &CallController, id: u64) { + let (commands, _rx) = mpsc::channel(1); + *calls.inner.slot() = Slot::Running(RunHandle { + id, + room_id: room_id!("!r:example.org").to_owned(), + flags: Arc::new(Flags::default()), + kill: killer().1, + stop: None, + commands, + camera_wanted: Arc::new(AtomicBool::new(false)), + screen_control: Arc::default(), + volume: watch::channel(MAX_VOLUME_PERCENT).0, + devices: watch::channel(None).0, + task: None, + }); + } + + fn stats_reading(identity: &str) -> persephone_call_protocol::CallStats { + persephone_call_protocol::CallStats { + remotes: vec![persephone_call_protocol::RemoteStats { + connection: 0, + identity: identity.to_owned(), + audio: None, + video: None, + }], + ..persephone_call_protocol::CallStats::default() + } + } + + /// GIVEN a call WHEN the worker reports statistics THEN they reach the + /// listener only while the page has them on, named by member, and never + /// change the call state; a reading after they went off is dropped. + #[test] + fn given_statistics_then_only_a_page_that_asked_for_them_gets_them() { + let fixture = test_call( + no_admission(), + Arc::new(Flags::default()), + Arc::new(AtomicBool::new(false)), + ); + let calls = controller(FakeHost::new(true, None)); + let changes = Arc::new(AtomicUsize::new(0)); + let seen = changes.clone(); + calls.set_listener(Arc::new(move || { + seen.fetch_add(1, Ordering::SeqCst); + })); + let heard = Arc::new(Mutex::new(Vec::new())); + let taken = heard.clone(); + calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats))); + let inner = calls.inner.clone(); + let mut call = fixture.call; + call.view = view(); + call.view.set_members(vec![member( + "@a:example.org", + "A", + "https://sfu.example.org", + )]); + let backend = call.view.members[0].backend_identities[0].clone(); + let reading = FromWorker::Stats(stats_reading(&backend)); + let state = call.view.state(); + let before = changes.load(Ordering::SeqCst); + + // Off: nothing leaves. + assert_eq!(call.worker_event(&inner, &reading), Ok(())); + assert!(plain(&heard).is_empty()); + + // On: the reading leaves, named by the member the identity stands for. + inner.stats_on.send_replace(true); + assert_eq!(call.worker_event(&inner, &reading), Ok(())); + let sent = plain(&heard).clone(); + assert_eq!(sent.len(), 1); + let stats = sent[0].as_ref().expect("a reading"); + assert_eq!(stats.participants.len(), 1); + assert_eq!(stats.participants[0].user_id, "@a:example.org"); + assert_eq!(stats.participants[0].device_id, "A"); + + // A participant that is no member is left out; the rest goes. + let stranger = FromWorker::Stats(stats_reading("stranger")); + assert_eq!(call.worker_event(&inner, &stranger), Ok(())); + assert!( + plain(&heard)[1] + .as_ref() + .is_some_and(|stats| stats.participants.is_empty()) + ); + + // Off again: a reading that was already on its way is dropped. + inner.stats_on.send_replace(false); + assert_eq!(call.worker_event(&inner, &reading), Ok(())); + assert_eq!(plain(&heard).len(), 2); + assert_eq!(call.view.state(), state); + assert_eq!(changes.load(Ordering::SeqCst), before); + } + + /// GIVEN no call WHEN the page turns the statistics on THEN it is refused + /// and nothing is on; GIVEN a call WHEN it turns them on and off THEN the + /// switch follows, and turning them off tells the listener once. + #[test] + fn given_no_call_then_statistics_cannot_be_turned_on() { + let calls = controller(FakeHost::new(true, None)); + let heard = Arc::new(Mutex::new(Vec::new())); + let taken = heard.clone(); + calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats))); + assert!(matches!(calls.set_stats(true), Err(CallError::NotInCall))); + assert!(!*calls.inner.stats_on.borrow()); + assert!(calls.set_stats(false).is_ok(), "off always works"); + assert!(plain(&heard).is_empty(), "off while off tells nobody"); + run_slot(&calls, 3); + assert!(calls.set_stats(true).is_ok()); + assert!(*calls.inner.stats_on.borrow()); + assert!(calls.set_stats(false).is_ok()); + assert!(!*calls.inner.stats_on.borrow()); + assert_eq!(*plain(&heard), [None]); + } + + /// GIVEN statistics on WHEN the call ends THEN they are off in the same + /// step, so the next call starts with them off, and the listener drops + /// the last reading. + #[test] + fn given_statistics_on_when_the_call_ends_then_they_are_off() { + let calls = controller(FakeHost::new(true, None)); + let heard = Arc::new(Mutex::new(Vec::new())); + let taken = heard.clone(); + calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats))); + run_slot(&calls, 5); + assert!(calls.set_stats(true).is_ok()); + assert!( + !calls.inner.release(4), + "another call's end changes nothing" + ); + assert!(*calls.inner.stats_on.borrow()); + assert!(calls.inner.release(5)); + assert!(!*calls.inner.stats_on.borrow()); + assert_eq!(*plain(&heard), [None]); + assert!(matches!(calls.set_stats(true), Err(CallError::NotInCall))); + } + + /// GIVEN a running call WHEN its task runs THEN a switch of the statistics + /// reaches the worker once, and the same value is not sent again. + #[test] + fn given_the_statistics_switch_when_applied_then_the_worker_gets_each_change_once() { + let mut fixture = test_call( + no_admission(), + Arc::new(Flags::default()), + Arc::new(AtomicBool::new(false)), + ); + let call = &mut fixture.call; + let mut sent = false; + let mut pending = Some((Instant::now(), false)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(pending.is_none() && !sent, "off to off is not sent"); + pending = Some((Instant::now(), true)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(pending.is_none() && sent); + pending = Some((Instant::now(), true)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(sent, "on to on is not sent again"); + } + /// GIVEN a call alone for 30 seconds with a join that waits unread /// WHEN the alone deadline fires THEN the join is applied first and the /// call stays; with nothing waiting after another 30 seconds alone it diff --git a/crates/core/src/calls/mod.rs b/crates/core/src/calls/mod.rs index 2a106b0f..037e10b2 100644 --- a/crates/core/src/calls/mod.rs +++ b/crates/core/src/calls/mod.rs @@ -58,6 +58,7 @@ pub mod ring_events; pub mod rings; pub mod screen; pub mod sfu; +pub mod stats; pub mod status; pub mod video; pub mod worker; diff --git a/crates/core/src/calls/stats.rs b/crates/core/src/calls/stats.rs new file mode 100644 index 00000000..f47ed6d6 --- /dev/null +++ b/crates/core/src/calls/stats.rs @@ -0,0 +1,218 @@ +//! The call statistics that the page may see (ADR-0066). +//! +//! The worker's message is already bounded by the call protocol reader. This +//! module names each remote entry by the member it stands for, leaves out an +//! entry that no member stands for, and checks the result once more against +//! the limits the UI host enforces. + +use persephone_call_protocol as worker; +use persephone_contracts::{ + CallStats, CallStatsAudioReceived, CallStatsAudioSent, CallStatsConnection, CallStatsLimit, + CallStatsParticipant, CallStatsVideoReceived, CallStatsVideoSent, +}; + +fn limit(limit: worker::QualityLimit) -> CallStatsLimit { + match limit { + worker::QualityLimit::None => CallStatsLimit::None, + worker::QualityLimit::Cpu => CallStatsLimit::Cpu, + worker::QualityLimit::Bandwidth => CallStatsLimit::Bandwidth, + worker::QualityLimit::Other => CallStatsLimit::Other, + } +} + +fn audio_sent(audio: &worker::AudioSendStats) -> CallStatsAudioSent { + CallStatsAudioSent { + level: audio.level, + bitrate_kbps: audio.bitrate_kbps, + packets_sent: audio.packets_sent, + packets_lost: audio.packets_lost, + jitter_ms: audio.jitter_ms, + rtt_ms: audio.rtt_ms, + } +} + +fn video_sent(video: &worker::VideoSendStats) -> CallStatsVideoSent { + CallStatsVideoSent { + fps: video.fps, + width: video.width, + height: video.height, + bitrate_kbps: video.bitrate_kbps, + limit: limit(video.limit), + packets_lost: video.packets_lost, + } +} + +fn audio_received(audio: &worker::AudioReceiveStats) -> CallStatsAudioReceived { + CallStatsAudioReceived { + level: audio.level, + bitrate_kbps: audio.bitrate_kbps, + packets_received: audio.packets_received, + packets_lost: audio.packets_lost, + jitter_ms: audio.jitter_ms, + concealed_percent: audio.concealed_percent, + } +} + +fn video_received(video: &worker::VideoReceiveStats) -> CallStatsVideoReceived { + CallStatsVideoReceived { + fps: video.fps, + width: video.width, + height: video.height, + bitrate_kbps: video.bitrate_kbps, + dropped_fps: video.dropped_fps, + packets_lost: video.packets_lost, + } +} + +/// The page's view of `stats`. `member` gives the user ID and device ID of +/// the member that a worker participant (its connection and identity) +/// stands for, or `None` when the participant is no current member or its +/// connection does not speak for it. A device that more than one entry +/// stands for is listed once. `None` when the result is out of its limits. +pub fn view( + stats: &worker::CallStats, + member: impl Fn(u8, &str) -> Option<(String, String)>, +) -> Option { + let mut participants: Vec = Vec::new(); + for remote in &stats.remotes { + let Some((user_id, device_id)) = member(remote.connection, &remote.identity) else { + continue; + }; + if participants + .iter() + .any(|seen| seen.user_id == user_id && seen.device_id == device_id) + { + continue; + } + participants.push(CallStatsParticipant { + user_id, + device_id, + audio: remote.audio.as_ref().map(audio_received), + video: remote.video.as_ref().map(video_received), + }); + } + let view = CallStats { + microphone: stats.microphone.as_ref().map(audio_sent), + camera: stats.camera.as_ref().map(video_sent), + screen: stats.screen.as_ref().map(video_sent), + participants, + connections: stats + .connections + .iter() + .map(|link| CallStatsConnection { + connection: link.connection, + outgoing_kbps: link.outgoing_kbps, + send_kbps: link.send_kbps, + receive_kbps: link.receive_kbps, + rtt_ms: link.rtt_ms, + }) + .collect(), + }; + view.within_limits().then_some(view) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn remote(connection: u8, identity: &str) -> worker::RemoteStats { + worker::RemoteStats { + connection, + identity: identity.to_owned(), + audio: Some(worker::AudioReceiveStats { + level: 7, + bitrate_kbps: Some(30), + packets_received: 5, + packets_lost: 1, + jitter_ms: 2, + concealed_percent: None, + }), + video: None, + } + } + + fn members(connection: u8, identity: &str) -> Option<(String, String)> { + match (connection, identity) { + (0, "bob-backend") | (1, "bob-other") => { + Some(("@bob:example.org".into(), "BOB".into())) + } + (0, "eve-backend") => Some(("@eve:example.org".into(), "EVE".into())), + _ => None, + } + } + + /// GIVEN a reading with members, strangers and a repeated device WHEN it + /// is made for the page THEN only members are named, each device once, + /// and the numbers carry over. + #[test] + fn given_a_reading_when_viewed_then_only_current_members_are_named_once() { + let stats = worker::CallStats { + microphone: Some(worker::AudioSendStats { + level: 40, + bitrate_kbps: Some(32), + packets_sent: 9, + packets_lost: Some(1), + jitter_ms: Some(3), + rtt_ms: Some(20), + }), + remotes: vec![ + remote(0, "bob-backend"), + remote(0, "stranger"), + remote(1, "bob-other"), + remote(2, "bob-backend"), + remote(0, "eve-backend"), + ], + connections: vec![worker::ConnectionStats { + connection: 0, + outgoing_kbps: Some(2500), + send_kbps: None, + receive_kbps: Some(40), + rtt_ms: Some(18), + }], + ..worker::CallStats::default() + }; + let view = view(&stats, members).expect("within limits"); + let names: Vec<_> = view + .participants + .iter() + .map(|person| person.device_id.as_str()) + .collect(); + assert_eq!(names, ["BOB", "EVE"]); + assert_eq!(view.participants[0].audio.as_ref().unwrap().level, 7); + assert_eq!(view.microphone.as_ref().unwrap().rtt_ms, Some(20)); + assert_eq!(view.connections[0].outgoing_kbps, Some(2500)); + assert_eq!(view.connections[0].send_kbps, None); + assert!(view.camera.is_none() && view.screen.is_none()); + } + + /// GIVEN a member with an ID that the page would refuse WHEN the reading + /// is made THEN the whole reading is dropped. + #[test] + fn given_an_id_over_the_limit_when_viewed_then_the_reading_is_dropped() { + let stats = worker::CallStats { + remotes: vec![remote(0, "bob-backend")], + ..worker::CallStats::default() + }; + let long = |_: u8, _: &str| { + Some(( + "u".repeat(persephone_contracts::CALL_USER_ID_BYTES_MAX + 1), + "D".to_owned(), + )) + }; + assert!(view(&stats, long).is_none()); + } + + /// GIVEN a limit reason WHEN it is viewed THEN each worker value has its + /// page value. + #[test] + fn given_each_quality_limit_when_viewed_then_it_maps_one_to_one() { + for (from, to) in [ + (worker::QualityLimit::None, CallStatsLimit::None), + (worker::QualityLimit::Cpu, CallStatsLimit::Cpu), + (worker::QualityLimit::Bandwidth, CallStatsLimit::Bandwidth), + (worker::QualityLimit::Other, CallStatsLimit::Other), + ] { + assert_eq!(limit(from), to); + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 42d2d9ec..226d1ab9 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -179,6 +179,9 @@ struct Notifications { /// The newest levels of the other devices in the call, not yet sent /// (ADR-0059). They leave with the sound level, under its gap. participant_levels: Option>, + /// The newest call statistics reading, not yet sent (ADR-0066). A newer + /// one replaces it; it is dropped when the statistics go off. + call_stats: Option, /// The device test changed since the last notification (ADR-0059). device_test_changed: bool, /// The report of third-party modules changed since the last notification. @@ -338,6 +341,17 @@ impl Hub { self.changed.notify_all(); } + /// Keeps `stats` as the call statistics to send, or drops the waiting + /// reading for `None`. Only the newest waits. + fn call_stats_changed(&self, stats: Option) { + let mut notifications = lock(&self.notifications); + let wake = stats.is_some(); + notifications.call_stats = stats; + if wake { + self.changed.notify_all(); + } + } + /// The device test changed: one `call_device_test_changed` event waits. fn device_test_changed(&self) { let mut notifications = lock(&self.notifications); @@ -776,6 +790,12 @@ impl Core { } })); let tell = Arc::downgrade(&hub); + calls.set_stats_listener(Arc::new(move |stats| { + if let Some(hub) = tell.upgrade() { + hub.call_stats_changed(stats); + } + })); + let tell = Arc::downgrade(&hub); calls.set_test_listener(Arc::new(move || { if let Some(hub) = tell.upgrade() { hub.device_test_changed(); @@ -1537,6 +1557,7 @@ impl Core { } self.call_microphone(*auto_level, *gain) } + Call::CallStats { on } => self.call_stats(*on), Call::CallCamera { on } => self.call_camera(*on), Call::CallScreen { on } => self.call_screen(*on), // Its picture reaches only `serve`. @@ -2751,6 +2772,24 @@ impl Core { ok(&calls::status::status(&self.calls.state())) } + /// Turns the call's technical details on or off (ADR-0066). They are + /// read and sent only while on, which needs a call; turning them off + /// also drops a reading that waits. + fn call_stats(&self, on: bool) -> Outcome { + if let Err(code) = self.calls_open() { + return Outcome::Error(code); + } + match self.calls.set_stats(on) { + Ok(()) => { + if !on { + self.hub.call_stats_changed(None); + } + Outcome::Ok(serde_json::Value::Null) + } + Err(_) => Outcome::Error(ErrorCode::Unavailable), + } + } + /// Turns the camera on or off. Unlike mute, no call is an error: there is /// nothing to turn on. fn call_camera(&self, on: bool) -> Outcome { @@ -3875,6 +3914,7 @@ impl Core { && !notifications.modules_changed && !notifications.diagnostics_changed && !notifications.device_test_changed + && notifications.call_stats.is_none() && notifications.toast.is_none() && !video_due && !sound_due @@ -3939,6 +3979,10 @@ impl Core { }; let device_test = std::mem::take(&mut notifications.device_test_changed) .then_some(Event::CallDeviceTestChanged {}); + let call_stats = notifications + .call_stats + .take() + .map(|stats| Event::CallStats { stats }); let session = std::mem::take(&mut notifications.session_changed).then_some(Event::SessionChanged {}); let list = std::mem::take(&mut notifications.room_list_changed) @@ -3979,6 +4023,7 @@ impl Core { .chain(video) .chain(sound) .chain(levels) + .chain(call_stats) .chain(device_test) .chain(modules) .chain(diagnostics) @@ -4021,6 +4066,8 @@ impl Core { } fn close(&self) { + // The page that asked for the call statistics is gone (ADR-0066). + let _ = self.calls.set_stats(false); self.hub.closing.store(true, Ordering::SeqCst); lock(&self.hub.notifications).closed = true; self.hub.changed.notify_all(); @@ -4664,6 +4711,53 @@ mod tests { ); } + /// GIVEN several statistics readings before the event writer runs WHEN + /// the events are taken THEN only the newest leaves, at once, and a + /// reading dropped by the switch never does. + #[test] + fn given_statistics_readings_then_only_the_newest_leaves() { + let core = Core::default(); + let reading = |level: u8| persephone_contracts::CallStats { + microphone: Some(persephone_contracts::CallStatsAudioSent { + level, + bitrate_kbps: None, + packets_sent: 0, + packets_lost: None, + jitter_ms: None, + rtt_ms: None, + }), + ..persephone_contracts::CallStats::default() + }; + core.hub.call_stats_changed(Some(reading(1))); + core.hub.call_stats_changed(Some(reading(2))); + assert_eq!( + core.take_events(), + Some(vec![Event::CallStats { stats: reading(2) }]) + ); + // Dropped while it waits: nothing leaves, and the writer does not + // wake for it. + core.hub.call_stats_changed(Some(reading(3))); + core.hub.call_stats_changed(None); + core.hub.calls_changed(); + assert_eq!(core.take_events(), Some(vec![Event::CallChanged {}])); + } + + /// GIVEN the statistics command WHEN there is no call THEN turning them + /// on is `unavailable` and turning them off works, also after the UI + /// connection closed. + #[test] + fn given_the_statistics_command_then_it_needs_a_call() { + let core = Core::default(); + let stats = |on| core.call_stats(on); + assert!(matches!( + stats(true), + Outcome::Error(ErrorCode::Unavailable) + )); + assert!(matches!(stats(false), Outcome::Ok(serde_json::Value::Null))); + core.close(); + assert!(core.calls.set_stats(false).is_ok()); + } + /// GIVEN a waiting video event WHEN the connection closes THEN the writer /// stops instead of waiting for the gap. #[test] From 36607e4ec825425f0015721d35e5a9a79cb57123 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 01:52:58 +0000 Subject: [PATCH 16/51] Let the call window turn call statistics on and off Adds the call_stats command to the call window's capability only. The host keeps the channel while the details are open and tells the core to stop when the window reloads or closes. Co-Authored-By: Claude Opus 5.5 --- src-tauri/AGENTS.md | 1 + src-tauri/build.rs | 1 + src-tauri/capabilities/call.json | 3 +- .../permissions/autogenerated/call_stats.toml | 11 ++ src-tauri/src/lib.rs | 67 ++++++++++- src-tauri/tests/ipc.rs | 111 ++++++++++++++++++ 6 files changed, 189 insertions(+), 5 deletions(-) create mode 100644 src-tauri/permissions/autogenerated/call_stats.toml diff --git a/src-tauri/AGENTS.md b/src-tauri/AGENTS.md index 02f74a40..c763c42c 100644 --- a/src-tauri/AGENTS.md +++ b/src-tauri/AGENTS.md @@ -6,6 +6,7 @@ This area inherits `../AGENTS.md` and implements ADR-0004. - Keep launch and inherited-pipe ownership checks. Start the application through the core binary, `persephone`; `persephone-ui` requires its core channel. - When adding a command, update its Rust handler, `build.rs` registration, `capabilities/main.json`, the frontend bridge, core protocol/handler, and IPC tests together. Review the minimum permission required. - The call window (ADR-0060) is the `call` window with `call.html` and its own `capabilities/call.json`: call commands only, plus `call_devices` and `set_call_devices` (ADR-0065); the `ipc` test pins the list. Grant it nothing else without an ADR change. `Subscriptions` keeps each window's channels under its label; room channels belong to `main`. Both windows get capture protection through `CaptureState::set_window_applier`, and the call window goes when the main window goes. +- Call statistics (ADR-0066): the call window alone may call `call_stats { on, onStats }` (`allow-call-stats` in `capabilities/call.json`, not in `main.json`). `Subscriptions::stats` holds its channel only while the details are on, and `reset_subscriptions` drops it and tells the core to stop when the window reloads or goes. `dispatch` checks `CallStats::within_limits` again and sends only to channels in that map. - `permissions/autogenerated/` and ignored `gen/` schemas come from `tauri-build`. Change command registration and rebuild rather than hand-editing generated permissions. - Preserve local-origin checks, invoke-key checks, the explicit command allowlist, restrictive CSP, disabled new windows, and blocked external navigation. Do not enable generic plugins, dynamic permissions, payload tracing, or broader dependency features without review. - Treat page arguments as untrusted. Check bounds before relaying, and keep validation at the core boundary too. Tauri handler checks cannot bound allocations made before the handler runs. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 00da3fa2..9d18c631 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -60,6 +60,7 @@ fn main() { "call_microphone", "call_camera", "call_screen", + "call_stats", "call_video_frame", "call_status", "call_rings", diff --git a/src-tauri/capabilities/call.json b/src-tauri/capabilities/call.json index 33cfc2cf..2b4244c6 100644 --- a/src-tauri/capabilities/call.json +++ b/src-tauri/capabilities/call.json @@ -1,6 +1,6 @@ { "identifier": "call", - "description": "The call window may watch the session and call levels, read the call status and pictures, and mute, deafen, change the volume, turn the camera or screen on or off, list the call devices and change them, and leave or close its window, and nothing else: no rooms, messages, keys, account, files, links, plugins, events, paths or webview permissions (ADR-0060).", + "description": "The call window may watch the session and call levels, read the call status and pictures, turn the call's technical details on or off, and mute, deafen, change the volume, turn the camera or screen on or off, list the call devices and change them, and leave or close its window, and nothing else: no rooms, messages, keys, account, files, links, plugins, events, paths or webview permissions (ADR-0060).", "windows": ["call"], "permissions": [ "allow-watch-session", @@ -14,6 +14,7 @@ "allow-call-screen", "allow-call-devices", "allow-set-call-devices", + "allow-call-stats", "allow-close-call-window" ] } diff --git a/src-tauri/permissions/autogenerated/call_stats.toml b/src-tauri/permissions/autogenerated/call_stats.toml new file mode 100644 index 00000000..22b00191 --- /dev/null +++ b/src-tauri/permissions/autogenerated/call_stats.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-call-stats" +description = "Enables the call_stats command without any pre-configured scope." +commands.allow = ["call_stats"] + +[[permission]] +identifier = "deny-call-stats" +description = "Denies the call_stats command without any pre-configured scope." +commands.deny = ["call_stats"] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a2c84f50..676afbc5 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -44,9 +44,9 @@ pub mod launcher; use core_link::{Band, CoreError, CoreLink, Video}; use persephone_contracts::{ AccountChange, AccountSettings, AccountStatus, AppStatus, CallDeviceTestKind, - CallDeviceTestStatus, CallDevices, CallParticipantLevel, CallReadiness, CallRings, CallStatus, - ContactStatus, ConversationStart, DeviceList, DiagnosticsStatus, DisplayName, HomeserverFound, - ImagePick, ImageView, InviteList, JoinedRoom, NewSessions, NotificationLevel, + CallDeviceTestStatus, CallDevices, CallParticipantLevel, CallReadiness, CallRings, CallStats, + CallStatus, ContactStatus, ConversationStart, DeviceList, DiagnosticsStatus, DisplayName, + HomeserverFound, ImagePick, ImageView, InviteList, JoinedRoom, NewSessions, NotificationLevel, NotificationSettings, PendingMessage, ProfileList, ProxySetting, PublicRoomPage, RoomActivity, RoomChange, RoomCreation, RoomIdentityChanges, RoomInvite, RoomList, RoomMembers, RoomPicture, RoomReaders, RoomServers, RoomSettings, SecurityStatus, StoreState, ThreePidList, @@ -390,6 +390,10 @@ pub struct Subscriptions { sound_level: Mutex>>, /// Each page's channel for the other devices' levels (ADR-0059). levels: Mutex>>>, + /// Each page's channel for the call statistics (ADR-0066). A window has + /// one only while its page has the technical details open, so a reading + /// goes only to a page that asked for it. + stats: Mutex>>, toasts: Mutex, capture: Arc, } @@ -419,6 +423,18 @@ impl Subscriptions { .unwrap_or_else(|poisoned| poisoned.into_inner()) } + fn stats(&self) -> MutexGuard<'_, HashMap>> { + self.stats + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Drops the statistics channel of the window `label`. True when it had + /// one, so the core is told to stop reading. + pub fn forget_stats(&self, label: &str) -> bool { + self.stats().remove(label).is_some() + } + /// Tells every page's session channel about `what`. fn tell_sessions(&self, what: &'static str) { for channel in self.session().values() { @@ -499,6 +515,16 @@ impl Subscriptions { let _ = channel.send(levels.clone()); } } + // Bounded numbers and IDs only; a reading outside its limits is + // dropped whole. Only a window that asked for it has a channel. + Event::CallStats { stats } => { + if !stats.within_limits() { + return; + } + for channel in self.stats().values() { + let _ = channel.send(stats.clone()); + } + } Event::RingsChanged {} => self.tell_sessions("rings"), Event::ModulesChanged {} => self.tell_sessions("modules"), // The UI host's own records follow the switch; the page asks for @@ -587,6 +613,32 @@ fn watch_session( subscriptions.levels().insert(label, on_levels); } +/// Turns the call's technical details on or off for the calling window +/// (ADR-0066). Only the call window may call it. The channel is kept only +/// while they are on, after the core accepted. The core reads the numbers +/// only while they are on, and the host drops a reading outside its limits. +#[tauri::command] +async fn call_stats( + webview: Webview, + core: State<'_, CoreLink>, + subscriptions: State<'_, Arc>, + on: bool, + on_stats: Channel, +) -> Result<(), String> { + let label = webview.label().to_owned(); + if on { + // Before the core starts, so the first reading is not lost. + subscriptions.stats().insert(label.clone(), on_stats); + } else { + subscriptions.forget_stats(&label); + } + let result = relay::<()>(core.inner(), Call::CallStats { on }).await; + if on && result.is_err() { + subscriptions.forget_stats(&label); + } + result +} + /// Locks the core's session. Replies with the resulting state; `locking` /// means admitted work is still finishing, and calling again resumes the wait. #[tauri::command] @@ -2105,7 +2157,10 @@ fn restore_from_tray(app: &AppHandle) { /// would otherwise stay taken. Rooms belong to the main window only. fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &str) { let rooms = subscriptions.forget_window(label); - if rooms.is_empty() { + // A window that goes or reloads stops the call statistics it asked for + // (ADR-0066). + let stats = subscriptions.forget_stats(label); + if rooms.is_empty() && !stats { return; } let core = core.clone(); @@ -2113,6 +2168,9 @@ fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &s for room_id in rooms { let _ = core.call(Call::Unsubscribe { room_id }); } + if stats { + let _ = core.call(Call::CallStats { on: false }); + } }); } @@ -2187,6 +2245,7 @@ pub fn configure( call_microphone, call_camera, call_screen, + call_stats, call_video_frame, call_status, call_rings, diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index a273b4d8..9d1d2ed7 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -31,6 +31,8 @@ struct FakeCore { timeline_events: Mutex)>>, // What the stored account settings say about capture protection. capture_protection: AtomicBool, + // The call statistics switches that reached the core, in order. + stats_switches: Mutex>, } impl FakeCore { @@ -42,6 +44,7 @@ impl FakeCore { pasted: Mutex::new(None), timeline_events: Mutex::new(None), capture_protection: AtomicBool::new(true), + stats_switches: Mutex::new(Vec::new()), }) } } @@ -53,6 +56,9 @@ impl CoreTransport for FakeCore { if let Call::VerifyMember { room_id, user_id } = &call { *self.verified_member.lock().unwrap() = Some((room_id.clone(), user_id.clone())); } + if let Call::CallStats { on } = &call { + self.stats_switches.lock().unwrap().push(*on); + } if let Call::TimelineEvents { room_id, event_ids } = &call { *self.timeline_events.lock().unwrap() = Some((room_id.clone(), event_ids.clone())); } @@ -163,6 +169,7 @@ impl CoreTransport for FakeCore { Call::CallCamera { on } => Ok( serde_json::json!({"phase": "active", "roomId": "!r:example.invalid", "muted": false, "deafened": false, "volume": 100, "participants": [], "ended": null, "joinError": null, "camera": if on { "starting" } else { "off" }, "screen": "off", "video": []}), ), + Call::CallStats { .. } => Ok(serde_json::Value::Null), Call::CallScreen { on } => Ok( serde_json::json!({"phase": "active", "roomId": "!r:example.invalid", "muted": false, "deafened": false, "volume": 100, "participants": [], "ended": null, "joinError": null, "camera": "off", "screen": if on { "starting" } else { "off" }, "video": []}), ), @@ -1118,6 +1125,7 @@ fn given_shell_config_then_security_settings_are_restrictive() { "allow-call-screen", "allow-call-devices", "allow-set-call-devices", + "allow-call-stats", "allow-close-call-window" ]) ); @@ -1217,6 +1225,109 @@ fn given_the_call_window_then_it_lists_and_changes_call_devices() { } } +/// GIVEN the call statistics command WHEN the main window calls it THEN it is +/// refused before the core; WHEN the call window turns it on THEN the core +/// is told, and a reading reaches only that window's channel while it is on, +/// is dropped when out of its limits, and stops when the window turns it off, +/// reloads or closes. +#[test] +fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_open() { + use persephone_contracts::{CallStats, CallStatsAudioSent}; + let delivered: Arc>> = Arc::default(); + let record = delivered.clone(); + let subscriptions = Arc::new(Subscriptions::default()); + let core = FakeCore::new(true); + let app = configure( + mock_builder().channel_interceptor(move |_, callback, _, body| { + let body = match body { + tauri::ipc::InvokeResponseBody::Json(json) => json.clone(), + tauri::ipc::InvokeResponseBody::Raw(_) => "raw".into(), + }; + record.lock().unwrap().push((callback.0, body)); + true + }), + core.clone(), + subscriptions.clone(), + ) + .build(context()) + .unwrap(); + let main = create_main_window(&app).unwrap(); + let call = create_call_window(&app).unwrap(); + let reading = |level: u8| CallStats { + microphone: Some(CallStatsAudioSent { + level, + bitrate_kbps: Some(32), + packets_sent: 7, + packets_lost: None, + jitter_ms: None, + rtt_ms: None, + }), + ..CallStats::default() + }; + let stats_on = |on: bool| serde_json::json!({"on": on, "onStats": "__CHANNEL__:9"}); + let sent = |level: u8| { + let text = serde_json::to_string(&reading(level)).unwrap(); + delivered + .lock() + .unwrap() + .iter() + .filter(|(channel, body)| *channel == 9 && *body == text) + .count() + }; + + // The main window has no permission, so nothing reaches the core. + assert!(invoke_on(&main, "call_stats", app_origin(), stats_on(true)).is_err()); + assert!(core.stats_switches.lock().unwrap().is_empty()); + + // Not asked for: no channel, nothing is delivered. + subscriptions.dispatch(Event::CallStats { stats: reading(1) }); + assert_eq!(sent(1), 0); + + // A bad argument never reaches the core. + assert!( + invoke_on( + &call, + "call_stats", + app_origin(), + serde_json::json!({"on": "yes", "onStats": "__CHANNEL__:9"}) + ) + .is_err() + ); + assert!(core.stats_switches.lock().unwrap().is_empty()); + + // On: the core is told, and a reading in its limits is delivered. + assert_eq!( + invoke_on(&call, "call_stats", app_origin(), stats_on(true)), + Ok(serde_json::Value::Null) + ); + assert_eq!(*core.stats_switches.lock().unwrap(), [true]); + subscriptions.dispatch(Event::CallStats { stats: reading(2) }); + assert_eq!(sent(2), 1); + + // A reading outside its limits is dropped whole. + subscriptions.dispatch(Event::CallStats { + stats: reading(101), + }); + assert_eq!(sent(101), 0); + + // Off: the channel goes and the core is told. + assert_eq!( + invoke_on(&call, "call_stats", app_origin(), stats_on(false)), + Ok(serde_json::Value::Null) + ); + assert_eq!(*core.stats_switches.lock().unwrap(), [true, false]); + subscriptions.dispatch(Event::CallStats { stats: reading(3) }); + assert_eq!(sent(3), 0); + + // A window that is reloaded or closed drops its channel and tells the + // core to stop. + invoke_on(&call, "call_stats", app_origin(), stats_on(true)).unwrap(); + assert!(subscriptions.forget_stats(CALL_WINDOW)); + assert!(!subscriptions.forget_stats(CALL_WINDOW), "once"); + subscriptions.dispatch(Event::CallStats { stats: reading(4) }); + assert_eq!(sent(4), 0); +} + /// GIVEN device test commands THEN bounded IDs cross, a bad one never /// reaches the core, and a reply outside the contract is refused. #[test] From 646c01c26b067ae2cd1f751c898267ac7fff5b4a Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 01:52:58 +0000 Subject: [PATCH 17/51] Show call technical details in the call window A Technical details icon button opens a panel (CallStats.svelte) with a table per source. Formatting and contract checks live in callStats.ts. Co-Authored-By: Claude Opus 5.5 --- frontend/AGENTS.md | 1 + frontend/src/CallStats.svelte | 66 ++++++ frontend/src/CallWindow.svelte | 39 +++- frontend/src/Icon.svelte | 5 +- frontend/src/bridge/index.ts | 21 ++ frontend/src/callStats.ts | 329 +++++++++++++++++++++++++++ frontend/src/style.css | 58 +++++ frontend/tests/bridge-calls.test.mjs | 25 ++ frontend/tests/call-stats.test.mjs | 150 ++++++++++++ frontend/tests/render.test.mjs | 14 ++ 10 files changed, 706 insertions(+), 2 deletions(-) create mode 100644 frontend/src/CallStats.svelte create mode 100644 frontend/src/callStats.ts create mode 100644 frontend/tests/call-stats.test.mjs diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md index 962b28ff..de2ee451 100644 --- a/frontend/AGENTS.md +++ b/frontend/AGENTS.md @@ -4,6 +4,7 @@ This area inherits `../AGENTS.md`. - Build a locally bundled Svelte UI. Keep `vite.config.js` output in `../.local/build/frontend`, relative asset URLs, no inline assets, and no production source maps unless a reviewed requirement changes them. - There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. That includes `call_devices` and `set_call_devices` (ADR-0065) for `CallWindowDevices.svelte`, but no device tests. The choice of the large video is pure logic in `src/callView.ts`: a pick of the viewer wins, a shared screen is large only when nothing is picked, and a feed that goes away drops its pick. Scale pictures with CSS only; never ask the core for a larger one. +- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge. The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs as escaped text. The details and the device panel are open one at a time (`openDevices`, `openStats`). - Put all Tauri API access in `src/bridge/index.ts` or another module under `src/bridge/`. Components use the typed bridge. Do not call `invoke`, Tauri globals, or host APIs directly from components. - Import public DTOs from `../crates/contracts/generated/contracts.ts`. Change Rust definitions and run the exporter when the DTO contract changes. TypeScript types do not validate runtime input or authorize commands. - Render names and message bodies as escaped text. Preserve bidirectional isolation in `src/Message.svelte`, `src/RoomList.svelte`, and `src/Timeline.svelte`. Do not use `{@html}`, HTML insertion APIs, automatic previews, or arbitrary remote images. diff --git a/frontend/src/CallStats.svelte b/frontend/src/CallStats.svelte new file mode 100644 index 00000000..ab782b19 --- /dev/null +++ b/frontend/src/CallStats.svelte @@ -0,0 +1,66 @@ + + + { + if (event.key === 'Escape') onclose(); + }} +/> + + diff --git a/frontend/src/CallWindow.svelte b/frontend/src/CallWindow.svelte index c3f40eda..322deb68 100644 --- a/frontend/src/CallWindow.svelte +++ b/frontend/src/CallWindow.svelte @@ -53,6 +53,8 @@ import { callGrid, ROSTER_LABEL, SelfClose, type CallCell } from './callWindow'; import { AUTO_PICK, keepPick, largeKey, selectFeed, showAll, splitFeeds, type ViewPick } from './callView'; import CallWindowDevices from './CallWindowDevices.svelte'; + import CallStatsPanel from './CallStats.svelte'; + import { STATS_LABEL } from './callStats'; import Icon from './Icon.svelte'; import PersonName from './PersonName.svelte'; import { tileCanvas, tileLayout, type TileRef, type VideoPicture } from './video'; @@ -78,6 +80,9 @@ let pick = $state.raw(AUTO_PICK); let devicesOpen = $state(false); let devicesButton = $state(); + // The technical details panel (ADR-0066); it closes when the call ends. + let statsOpen = $state(false); + let statsButton = $state(); // Numbers the status reads, so an older answer never replaces a newer one. let request = 0; // The window closes itself after a call it saw ends, unless it is @@ -87,6 +92,7 @@ function take(next: CallStatus) { status = next; selfClose.status(inCall(next), next.phase === 'ended'); + if (!inCall(next)) statsOpen = false; if (next.phase !== 'active') { ownLevel = 0; levels = new Map(); @@ -225,6 +231,18 @@ void tick().then(() => devicesButton?.focus()); } + // One panel at a time: the technical details lie over the window's side, + // so they would hide part of the device panel, and Escape closes either. + function openDevices() { + statsOpen = false; + devicesOpen = true; + } + + function openStats() { + devicesOpen = false; + statsOpen = true; + } + function onKeydown(event: KeyboardEvent) { if (event.key === 'Escape' && devicesOpen) { event.preventDefault(); @@ -441,10 +459,21 @@ aria-controls="call-window-devices" aria-label={DEVICES_BUTTON_LABEL} title={DEVICES_BUTTON_LABEL} - onclick={() => (devicesOpen ? closeDevices() : (devicesOpen = true))} + onclick={() => (devicesOpen ? closeDevices() : openDevices())} > + {#if CAMERA_TEXT[status.camera] !== ''} @@ -460,4 +489,12 @@ {#if failure} {/if} + {#if joined && statsOpen} + { + statsOpen = false; + void tick().then(() => statsButton?.focus()); + }} + /> + {/if}
diff --git a/frontend/src/Icon.svelte b/frontend/src/Icon.svelte index 82d5616b..cf8e2e98 100644 --- a/frontend/src/Icon.svelte +++ b/frontend/src/Icon.svelte @@ -36,7 +36,8 @@ | 'volume' | 'video' | 'video-off' - | 'screen'; + | 'screen' + | 'activity';
@@ -84,31 +52,31 @@

{devicesNote(devices)}

{:else} - {#each recordingOptions as option (option.value)} {/each} - {#each playoutOptions as option (option.value)} {/each} - {#each cameraOptions as option (option.value)} {/each} - {/if} {#if result !== ''}

{result}

{/if} - {#if failure} - + {#if view.failure} + {/if}
diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts index ab4b73b7..e6f6e39d 100644 --- a/frontend/src/bridge/index.ts +++ b/frontend/src/bridge/index.ts @@ -557,12 +557,24 @@ export async function startCallStats(onStats: (stats: CallStats) => void): Promi const stats = parseCallStats(value); if (stats !== null) onStats(stats); }); - await invoke('call_stats', { on: true, onStats: channel }); + await inStatsTurn(() => invoke('call_stats', { on: true, onStats: channel })); } /** Turns the call's technical details off (ADR-0066). Safe to call when they are off. */ export async function stopCallStats(): Promise { - await invoke('call_stats', { on: false, onStats: new Channel(() => {}) }); + await inStatsTurn(() => invoke('call_stats', { on: false, onStats: new Channel(() => {}) })); +} + +// The host keeps one statistics channel per window, and the last start or +// stop it gets wins. So starts and stops go one at a time, in the order the +// page asked: the late stop of a closed panel can never turn off the panel +// opened after it. A failed one does not hold up the next. +let statsTurn: Promise = Promise.resolve(); + +function inStatsTurn(task: () => Promise): Promise { + const turn = statsTurn.then(task, task); + statsTurn = turn.catch(() => undefined); + return turn; } /** diff --git a/frontend/src/callDevicePanel.ts b/frontend/src/callDevicePanel.ts new file mode 100644 index 00000000..6dfbda0d --- /dev/null +++ b/frontend/src/callDevicePanel.ts @@ -0,0 +1,113 @@ +import type { CallDevices } from '../../crates/contracts/generated/contracts'; +import { DEVICE_FAILURE_TEXT, DEVICE_SAVE_FAILURE_TEXT, deviceChoice, deviceValue } from './calls.ts'; + +/** The three menus of the device panel; `''` is the system default. */ +export interface DeviceMenus { + recording: string; + playout: string; + camera: string; +} + +/** What the device panel shows besides the menus. */ +export interface DevicePanelState { + devices: CallDevices | null; + loading: boolean; + saving: boolean; + saved: boolean; + failure: string | null; +} + +/** The bridge calls the panel uses; the component passes the real ones. */ +export interface DevicePanelBridge { + list: () => Promise; + save: (recording: string | null, playout: string | null, camera: string | null) => Promise; +} + +const failureText = (reason: unknown, fallback: string) => DEVICE_FAILURE_TEXT[String(reason)] ?? fallback; + +/** + * The work of the call window's device panel (ADR-0065), apart from the + * view so its order rules have tests. + * + * - A load reads the lists and the saved choices. It does not start while a + * load or a save runs, because it would replace the menus under them. + * - Saves go to the core one at a time, in the order asked, so a menu + * changed while a save runs is sent after it and none is dropped. Each + * save sends the three menus as they were when it was asked, so the last + * one holds every change. Only the newest save sets the result line. + * - After `close`, no answer changes the panel. + */ +export class DevicePanel { + readonly #bridge: DevicePanelBridge; + readonly #onstate: (state: DevicePanelState) => void; + readonly #onmenus: (menus: DeviceMenus) => void; + #state: DevicePanelState = { devices: null, loading: false, saving: false, saved: false, failure: null }; + #queue: Promise = Promise.resolve(); + #saves = 0; + #newest = 0; + #open = true; + + constructor( + bridge: DevicePanelBridge, + onstate: (state: DevicePanelState) => void, + onmenus: (menus: DeviceMenus) => void + ) { + this.#bridge = bridge; + this.#onstate = onstate; + this.#onmenus = onmenus; + } + + get state(): DevicePanelState { + return this.#state; + } + + #set(change: Partial) { + this.#state = { ...this.#state, ...change }; + this.#onstate(this.#state); + } + + async load(): Promise { + if (!this.#open || this.#state.loading || this.#saves > 0) return; + this.#set({ loading: true, failure: null }); + try { + const devices = await this.#bridge.list(); + if (!this.#open) return; + this.#set({ devices, loading: false }); + this.#onmenus({ + recording: deviceValue(devices.selectedRecording), + playout: deviceValue(devices.selectedPlayout), + camera: deviceValue(devices.selectedCamera) + }); + } catch (reason) { + if (this.#open) this.#set({ loading: false, failure: failureText(reason, DEVICE_FAILURE_TEXT.core_unavailable) }); + } + } + + async save(menus: DeviceMenus): Promise { + if (!this.#open) return; + const mine = ++this.#newest; + this.#saves += 1; + this.#set({ saving: true, saved: false, failure: null }); + const choice = [deviceChoice(menus.recording), deviceChoice(menus.playout), deviceChoice(menus.camera)] as const; + const run = () => this.#bridge.save(...choice); + const turn = this.#queue.then(run, run); + this.#queue = turn.catch(() => undefined); + let failure: string | null = null; + try { + await turn; + } catch (reason) { + failure = failureText(reason, DEVICE_SAVE_FAILURE_TEXT); + } + this.#saves -= 1; + if (!this.#open) return; + if (mine === this.#newest) { + this.#set({ saving: this.#saves > 0, saved: failure === null, failure }); + } else { + this.#set({ saving: this.#saves > 0 }); + } + } + + close(): void { + this.#open = false; + } +} diff --git a/frontend/src/calls.ts b/frontend/src/calls.ts index 43b7b9a0..3c53224b 100644 --- a/frontend/src/calls.ts +++ b/frontend/src/calls.ts @@ -756,6 +756,7 @@ export const DEVICE_FAILURE_TEXT: Record = { core_unavailable: 'The call devices could not be listed.', invalid_argument: 'That device cannot be saved.' }; +export const DEVICE_SAVE_FAILURE_TEXT = 'The call devices could not be saved.'; /** * What the device panel of the call window says about a change during a @@ -775,13 +776,23 @@ export const DEVICES_BUTTON_LABEL = 'Device settings'; export const DEVICES_PANEL_LABEL = 'Call devices'; /** - * The line under the device menus after a save: nothing before a save, - * "switching" while it runs, the failure the status shows, or "switched". + * The line under the device menus: "switching" while a save runs, the + * failure the call status shows (also one from before the panel opened, or + * from the main window's settings), "switched" after a save, else nothing. */ export function deviceSwitchText(saved: boolean, saving: boolean, change: CallDeviceChange | null): string { if (saving) return DEVICE_SWITCHING_TEXT; - if (!saved) return ''; - return change === null ? DEVICE_SWITCHED_TEXT : DEVICE_SWITCH_TEXT[change]; + if (change !== null) return DEVICE_SWITCH_TEXT[change]; + return saved ? DEVICE_SWITCHED_TEXT : ''; +} + +/** The call window's view buttons (ADR-0065). */ +export const SHOW_ALL_LABEL = 'Show all'; +export const SHOW_LARGE_LABEL = 'Show large'; + +/** The label of a feed's button: a large feed goes back to all. */ +export function feedLabel(isLarge: boolean): string { + return isLarge ? SHOW_ALL_LABEL : SHOW_LARGE_LABEL; } /** The buttons that start each device test. */ diff --git a/frontend/tests/bridge-calls.test.mjs b/frontend/tests/bridge-calls.test.mjs index bdadd371..c1015e55 100644 --- a/frontend/tests/bridge-calls.test.mjs +++ b/frontend/tests/bridge-calls.test.mjs @@ -528,6 +528,37 @@ test('GIVEN the technical details WHEN turned on and off THEN the host is asked await assert.rejects(bridge.startCallStats(() => {}), (reason) => reason === 'unavailable'); }); +test('GIVEN a statistics start still at the host WHEN the panel closes and opens again THEN the host gets start, stop, start in that order', async () => { + const sent = []; + let release; + const first = new Promise((resolve) => (release = resolve)); + mockIPC((command, args) => { + sent.push(args.on); + return sent.length === 1 ? first.then(() => null) : null; + }); + const startA = bridge.startCallStats(() => {}); + const stopA = bridge.stopCallStats(); + const startB = bridge.startCallStats(() => {}); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(sent, [true], 'nothing else goes while the first start runs'); + release(); + await Promise.all([startA, stopA, startB]); + // The late stop of the closed panel comes before the new start, so the + // readings stay on for the panel that is open. + assert.deepEqual(sent, [true, false, true]); +}); + +test('GIVEN a statistics start that fails WHEN a stop follows THEN the stop is still sent', async () => { + const sent = []; + mockIPC((command, args) => { + sent.push(args.on); + return args.on ? Promise.reject('locked') : null; + }); + await assert.rejects(bridge.startCallStats(() => {}), (reason) => reason === 'locked'); + await bridge.stopCallStats(); + assert.deepEqual(sent, [true, false]); +}); + test('GIVEN the video frame call WHEN the host answers THEN an empty body is no picture, a whole picture is parsed and anything else is refused', async () => { const body = new Uint8Array(20 + 8); const prefix = new DataView(body.buffer); diff --git a/frontend/tests/call-device-panel.test.mjs b/frontend/tests/call-device-panel.test.mjs new file mode 100644 index 00000000..68740043 --- /dev/null +++ b/frontend/tests/call-device-panel.test.mjs @@ -0,0 +1,156 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { DevicePanel } from '../src/callDevicePanel.ts'; +import { DEVICE_FAILURE_TEXT, DEVICE_SAVE_FAILURE_TEXT } from '../src/calls.ts'; + +const DEVICES = { + supported: true, + recording: [{ id: 'mic-2', name: 'Desk microphone' }], + playout: [{ id: 'spk-1', name: 'Speakers' }], + cameras: [], + selectedRecording: 'mic-2', + selectedPlayout: null, + selectedCamera: null, + volume: 100, + unreadable: false +}; + +/** A promise and the functions that settle it, for answers that wait. */ +function later() { + let resolve; + let reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} + +/** A panel with the given bridge, and what it told its view. */ +function panel(bridge) { + const seen = { states: [], menus: [] }; + const made = new DevicePanel( + bridge, + (state) => seen.states.push(state), + (menus) => seen.menus.push(menus) + ); + return { panel: made, seen, last: () => seen.states.at(-1) }; +} + +const never = () => new Promise(() => {}); +const menus = (recording) => ({ recording, playout: '', camera: '' }); + +test('GIVEN the lists WHEN the panel loads THEN it shows them and fills the menus from the saved choices', async () => { + const { panel: made, seen, last } = panel({ list: async () => DEVICES, save: never }); + await made.load(); + assert.equal(seen.states[0].loading, true, 'it says it is loading first'); + assert.deepEqual(last(), { devices: DEVICES, loading: false, saving: false, saved: false, failure: null }); + assert.deepEqual(seen.menus, [{ recording: 'mic-2', playout: '', camera: '' }]); +}); + +test('GIVEN the core refuses WHEN the panel loads THEN it shows the failure and keeps no lists', async () => { + for (const [reason, text] of [ + ['core_unavailable', DEVICE_FAILURE_TEXT.core_unavailable], + ['something_else', DEVICE_FAILURE_TEXT.core_unavailable] + ]) { + const { panel: made, seen, last } = panel({ list: () => Promise.reject(reason), save: never }); + await made.load(); + assert.equal(last().failure, text, reason); + assert.equal(last().devices, null); + assert.equal(last().loading, false); + assert.deepEqual(seen.menus, []); + } +}); + +test('GIVEN a save WHEN the core accepts it THEN the panel says switched and sends the menus as choices', async () => { + const sent = []; + const { panel: made, seen, last } = panel({ + list: async () => DEVICES, + save: async (...choice) => sent.push(choice) + }); + await made.save({ recording: 'mic-2', playout: '', camera: 'cam-1' }); + assert.deepEqual(sent, [['mic-2', null, 'cam-1']], 'an empty menu is the system default'); + assert.equal(seen.states[0].saving, true); + assert.deepEqual(last(), { devices: null, loading: false, saving: false, saved: true, failure: null }); +}); + +test('GIVEN a save WHEN the core refuses it THEN the panel shows the failure and does not say switched', async () => { + for (const [reason, text] of [ + ['invalid_argument', DEVICE_FAILURE_TEXT.invalid_argument], + ['unknown', DEVICE_SAVE_FAILURE_TEXT] + ]) { + const { panel: made, last } = panel({ list: never, save: () => Promise.reject(reason) }); + await made.save(menus('mic-2')); + assert.equal(last().failure, text, reason); + assert.equal(last().saved, false); + assert.equal(last().saving, false); + } +}); + +test('GIVEN a save that runs WHEN another menu changes THEN that save is sent after it, none is dropped, and the newest sets the result', async () => { + const first = later(); + const sent = []; + const { panel: made, last } = panel({ + list: never, + save: (...choice) => { + sent.push(choice); + return sent.length === 1 ? first.promise : Promise.resolve(); + } + }); + const one = made.save(menus('mic-1')); + const two = made.save(menus('mic-2')); + await Promise.resolve(); + assert.deepEqual(sent, [['mic-1', null, null]], 'the second waits for the first'); + assert.equal(last().saving, true); + first.reject('core_unavailable'); + await Promise.all([one, two]); + assert.deepEqual(sent, [['mic-1', null, null], ['mic-2', null, null]]); + // The second save held every change and worked, so the first's failure is old news. + assert.deepEqual([last().saving, last().saved, last().failure], [false, true, null]); +}); + +test('GIVEN a save that runs WHEN a refresh is asked THEN it does not start and replace the menus', async () => { + let lists = 0; + const first = later(); + const { panel: made, seen } = panel({ + list: async () => { + lists += 1; + return DEVICES; + }, + save: () => first.promise + }); + const saving = made.save(menus('mic-2')); + await made.load(); + assert.equal(lists, 0); + first.resolve(); + await saving; + await made.load(); + assert.equal(lists, 1, 'after the save it loads'); + assert.equal(seen.menus.length, 1); +}); + +test('GIVEN a closed panel WHEN a late answer comes THEN the panel does not change', async () => { + const listed = later(); + const saved = later(); + const { panel: made, seen } = panel({ list: () => listed.promise, save: () => saved.promise }); + const loading = made.load(); + made.close(); + listed.resolve(DEVICES); + await loading; + const told = seen.states.length; + assert.deepEqual(seen.menus, []); + await made.save(menus('mic-2')); + await made.load(); + assert.equal(seen.states.length, told, 'a closed panel starts nothing'); +}); + +test('GIVEN a closed panel WHEN a running save ends THEN it says nothing', async () => { + const saved = later(); + const { panel: made, seen } = panel({ list: never, save: () => saved.promise }); + const saving = made.save(menus('mic-2')); + const told = seen.states.length; + made.close(); + saved.reject('core_unavailable'); + await saving; + assert.equal(seen.states.length, told); +}); diff --git a/frontend/tests/call-view.test.mjs b/frontend/tests/call-view.test.mjs index b9de4034..dcdf2e9b 100644 --- a/frontend/tests/call-view.test.mjs +++ b/frontend/tests/call-view.test.mjs @@ -9,7 +9,15 @@ import { showAll, splitFeeds } from '../src/callView.ts'; -import { DEVICE_SWITCH_TEXT, DEVICE_SWITCHED_TEXT, DEVICE_SWITCHING_TEXT, deviceSwitchText } from '../src/calls.ts'; +import { + DEVICE_SWITCH_TEXT, + DEVICE_SWITCHED_TEXT, + DEVICE_SWITCHING_TEXT, + deviceSwitchText, + feedLabel, + SHOW_ALL_LABEL, + SHOW_LARGE_LABEL +} from '../src/calls.ts'; const cameras = ['own', 'a', 'b']; const withScreen = [...cameras, 'screen']; @@ -78,6 +86,12 @@ test('GIVEN a key that is not in the call WHEN it is selected THEN nothing chang assert.equal(largeKey(selectFeed(AUTO_PICK, 'zzz', cameras), cameras), null); }); +test('GIVEN a feed button WHEN it is labelled THEN a large feed goes back to all and the others show large', () => { + assert.equal(feedLabel(true), SHOW_ALL_LABEL); + assert.equal(feedLabel(false), SHOW_LARGE_LABEL); + assert.notEqual(SHOW_ALL_LABEL, SHOW_LARGE_LABEL); +}); + test('GIVEN no large feed WHEN the cells are split THEN all stay in order', () => { const cells = cameras.map((key) => ({ key })); const split = splitFeeds(cells, null); @@ -91,6 +105,9 @@ test('GIVEN the device panel WHEN a change is read THEN each result has its own assert.equal(deviceSwitchText(true, false, null), DEVICE_SWITCHED_TEXT); for (const change of ['not_found', 'unsupported', 'kept', 'failed']) { assert.equal(deviceSwitchText(true, false, change), DEVICE_SWITCH_TEXT[change]); + // A failure from before the panel opened shows too. + assert.equal(deviceSwitchText(false, false, change), DEVICE_SWITCH_TEXT[change]); + assert.equal(deviceSwitchText(false, true, change), DEVICE_SWITCHING_TEXT); } assert.match(DEVICE_SWITCH_TEXT.not_found, /not connected/); assert.match(DEVICE_SWITCH_TEXT.unsupported, /Linux/); diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs index 5ff3c4ba..3e045ec2 100644 --- a/frontend/tests/render.test.mjs +++ b/frontend/tests/render.test.mjs @@ -319,7 +319,7 @@ test('GIVEN a call with a camera on and one off WHEN the call window renders THE // One icon button opens the technical details; the panel is closed. assert.equal((html.match(/aria-label="Technical details"/g) ?? []).length, 1); - assert.match(html, /class="secondary call-stats-button"[^>]*aria-pressed="false"/); + assert.match(html, /class="secondary call-stats-button"[^>]*aria-expanded="false"[^>]*aria-controls="call-window-stats"/); assert.doesNotMatch(html, /class="call-stats"/); const { body: idle } = render(CallWindow, { props: {} }); @@ -330,7 +330,7 @@ test('GIVEN a call with a camera on and one off WHEN the call window renders THE test('GIVEN the technical details panel WHEN it renders before a reading THEN it waits, has a close button and shows no table', async () => { const { default: CallStats } = await vite.ssrLoadModule('/src/CallStats.svelte'); const { body } = render(CallStats, { props: { onclose() {} } }); - assert.match(body, /role="dialog" aria-label="Technical details"/); + assert.match(body, /id="call-window-stats" class="call-stats" role="dialog" aria-label="Technical details"/); assert.match(body, /aria-label="Close technical details"/); assert.match(body, /Waiting for the first reading\./); assert.doesNotMatch(body, /(app: &AppHandle) { /// Drops a window's subscriptions when its page (re)loads or the window /// goes: the new page holds none of the old channels, and the core's slots -/// would otherwise stay taken. Rooms belong to the main window only. -fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &str) { +/// would otherwise stay taken. Rooms belong to the main window only. The +/// page-load and window-destroyed handlers call it; it is public for the +/// IPC tests, because the mock runtime sends neither event. +pub fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &str) { let rooms = subscriptions.forget_window(label); // A window that goes or reloads stops the call statistics it asked for // (ADR-0066). diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index 9d1d2ed7..895b2fd2 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -6,7 +6,7 @@ use persephone_desktop::{ BAND_PREFIX_BYTES, CALL_WINDOW, MAIN_WINDOW, Subscriptions, VIDEO_PREFIX_BYTES, configure, context, core_link::{Band, CoreError, CoreLink, CoreTransport, Video}, - create_call_window, create_main_window, + create_call_window, create_main_window, reset_subscriptions, }; use std::sync::{ Arc, Mutex, @@ -1320,9 +1320,21 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ assert_eq!(sent(3), 0); // A window that is reloaded or closed drops its channel and tells the - // core to stop. + // core to stop, through the handler its page load and its close use. invoke_on(&call, "call_stats", app_origin(), stats_on(true)).unwrap(); - assert!(subscriptions.forget_stats(CALL_WINDOW)); + assert_eq!(*core.stats_switches.lock().unwrap(), [true, false, true]); + let link: CoreLink = core.clone(); + reset_subscriptions(&link, &subscriptions, CALL_WINDOW); + // The stop goes on a blocking task, so wait for it, but not forever. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while core.stats_switches.lock().unwrap().len() < 4 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!( + *core.stats_switches.lock().unwrap(), + [true, false, true, false] + ); + // The channel went with it, so another reset has nothing to stop. assert!(!subscriptions.forget_stats(CALL_WINDOW), "once"); subscriptions.dispatch(Event::CallStats { stats: reading(4) }); assert_eq!(sent(4), 0); From 8ae45feec00c13ba75e6e072278c4d0726094ef1 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 09:09:28 +0000 Subject: [PATCH 23/51] Address the third review of the call window view - Key each worker statistics counter by its track and time each counter by its own read, so a track switch or a slow read gives no wrong rate. - Keep the statistics cadence across a quick off and on. - Give each transport of a connection its own counters, and show no total while one transport is missing. - Make the statistics DTOs required-nullable and read them in the core protocol with a map-only reader that stops each list at its limit. - Tie the page's statistics bounds to the worker protocol's at compile time, export them to the page, and record that tag 16 and version 11 belong to the microphone-gain change. - Drop a feed pick when its camera goes off, and put the action in each feed button's name. - Order the host's statistics stop against starts, keep the channel only after the core accepts, and undo a start that a reload overtook. - Test the refused statistics start and the relayed device choice. Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/AGENTS.md | 2 +- crates/call-protocol/src/stats.rs | 4 + crates/call-worker/AGENTS.md | 2 +- crates/call-worker/src/mapping/stats.rs | 294 ++++++++---- crates/call-worker/src/mapping/stats/tests.rs | 182 +++++-- crates/call-worker/src/session.rs | 6 +- crates/call-worker/src/session/stats_probe.rs | 454 +++++++++++++----- crates/contracts/AGENTS.md | 2 +- crates/contracts/generated/contracts.ts | 15 + crates/contracts/src/lib.rs | 57 ++- crates/contracts/tests/contracts.rs | 45 ++ crates/core-protocol/src/lib.rs | 282 +++++++++-- crates/core/src/calls/stats.rs | 12 + .../0066-show-call-statistics-on-request.md | 29 +- frontend/src/CallWindow.svelte | 17 +- frontend/src/callStats.ts | 29 +- frontend/src/callView.ts | 10 + frontend/tests/call-view.test.mjs | 28 ++ src-tauri/AGENTS.md | 2 +- src-tauri/src/lib.rs | 118 ++++- src-tauri/tests/ipc.rs | 79 +++ 21 files changed, 1334 insertions(+), 335 deletions(-) diff --git a/crates/call-protocol/AGENTS.md b/crates/call-protocol/AGENTS.md index 22e51013..2b7a8b78 100644 --- a/crates/call-protocol/AGENTS.md +++ b/crates/call-protocol/AGENTS.md @@ -15,7 +15,7 @@ This crate defines the bounded binary messages between the key-holding core and - Sound level meter (ADR-0055 amendment of 2026-11-23): wire version 9 added `FromWorker::SoundLevel { level }`, 0 to `MAX_SOUND_LEVEL` (100). `Reader::sound_level` refuses a larger value. - Devices and levels (ADR-0059): wire version 10 added `ToWorker::TestDevice { test, device }` (a first message only, like `ListDevices`; `DeviceTest` is a closed set), `ToWorker::SetDevices { recording, playout, camera }` (the camera choice applies from the next camera start; `DevicesSet` answers for the microphone and speaker only), `FromWorker::ParticipantLevel { connection, identity, level }`, `FromWorker::ParticipantMuted { connection, identity, muted }` and `FromWorker::DevicesSet { failure }` (0 for none, else a `FailureCode`). `SoundLevel` is now the own microphone's level. - Microphone settings (ADR-0062): wire version 11 added `ToWorker::SetMicrophone { auto_level, mic_gain }` (tag 16, no answer), and `Join` ends with `auto_level` and `mic_gain` (two bytes). `Reader::mic_gain` refuses a gain over `MAX_MIC_GAIN_PERCENT` (400) or off the step of `MIC_GAIN_STEP_PERCENT` (5); use `valid_mic_gain` wherever a gain is used. -- Call statistics (ADR-0066): wire version 12 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer leaves out entries past the limits. +- Call statistics (ADR-0066): wire version 12 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer leaves out entries past the limits. Tag 16 and wire version 11 are the microphone settings above (ADR-0062). The next wire change takes tag 18 and the next free version. The `MAX_STATS_*` bounds are repeated as `CALL_STATS_*` in `crates/contracts`; `crates/core/src/calls/stats.rs` checks at compile time that they match. - Coordinate wire changes with `crates/core` and `crates/call-worker` (planned), and bump the version byte. ## Checks diff --git a/crates/call-protocol/src/stats.rs b/crates/call-protocol/src/stats.rs index cdb4a246..69858c36 100644 --- a/crates/call-protocol/src/stats.rs +++ b/crates/call-protocol/src/stats.rs @@ -4,6 +4,10 @@ //! checks. There is no text except the participants' identities, which the //! worker has already validated for other messages. There is no address, //! port, candidate type, SSRC or codec name. +//! +//! The page's contract repeats the `MAX_STATS_*` bounds as `CALL_STATS_*` +//! in `persephone-contracts`. The core checks at compile time that they +//! match. Change them together. use super::{DecodeError, MAX_OTHER_CONNECTIONS, MAX_PARTICIPANTS, Reader, put_str}; diff --git a/crates/call-worker/AGENTS.md b/crates/call-worker/AGENTS.md index f3afecd9..0fe995e8 100644 --- a/crates/call-worker/AGENTS.md +++ b/crates/call-worker/AGENTS.md @@ -30,7 +30,7 @@ The contained process that runs one call (ADR-0043). It joins one LiveKit room w - Device tests (ADR-0059): `TestDevice` is a first message, like `ListDevices`; it connects to no server. `session::test_device` opens a sound test's device first (`sound_test::open`, off the runtime threads), then applies stage 2, then runs it (`Opened::run`, on its own thread). `sound_test.rs` listens (15 s, own level) or plays a 440 Hz tone (1.5 s). Windows: WASAPI in shared mode; `E_ACCESSDENIED` is `DeviceDenied`. Linux: one PulseAudio stream through the `libpulse.so.0` handle of `pulse.rs`, the default stream with no device name and `PA_STREAM_DONT_MOVE`; a `pulse:` choice is checked with `sound_paths` as for a `Join` and reaches the stream through `PULSE_SOURCE` or `PULSE_SINK`; any other chosen ID is `DeviceNotFound`; it must open before stage 2 (new socket); `PA_ERR_ACCESS` is `DeviceDenied`. macOS: a Core Audio HAL I/O procedure (32-bit float only) on the default device or the chosen UID; the device is found before the microphone permission is checked, so a missing device never prompts; a refused permission is `DeviceDenied`. Never request a permission in a default-run test on macOS: outside an app bundle it ends the process. The camera test takes the portal remote that the core sends before `TestDevice` (`Grant::take`), opens the camera as a call does and sends pictures on tile 0 for at most 30 s. `Leave` ends any test, which ends with `Left` or `Failed`. - Microphone settings (ADR-0062): `Join` carries `auto_level` and `mic_gain`, and `SetMicrophone` changes them in a running call. `mapping::Microphone::new` is the worker's own check (a gain over 400 percent or off the step of 5 is `Protocol`; the protocol reader refuses it first). The gain goes to the voice engine's audio processing module through `native::capture_processing::set_capture_gain_percent` (a process-wide value that every live factory applies); the automatic level goes to the published microphone track through `RtcAudioTrack::set_auto_gain_control`. Both apply at once, and `apply_microphone` applies both again after each `SetDevices`. The device tests (`sound_test.rs`) do not use them. A refusal is noted, never fatal. - Audio notes (ADR-0058 amendment of 2026-11-25): `note_audio` in `session.rs` writes `Note` records of the target `persephone::call_worker::audio` while the log is on: the devices at the join (counts and how each was chosen, never an ID or name), the microphone settings with what the audio processing module reports, and every 5 seconds the own level, the playout state and each remote audio track's packets, samples and level (`measure_levels`). Keep them to counts, flags and levels. Never add an identity, a device ID or name, a key or a token. -- Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since the reading before (a reset, a missing earlier value or a zero interval gives no rate, never a wrong one) and clamps every number to the protocol bound. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue. +- Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since each counter's sample before, over the time between the two reads, keyed by track ID or transport (a reset, a new track, a missing earlier value, a zero interval or a connection with an unread transport gives no rate, never a wrong one) and clamps every number to the protocol bound. Turning the statistics off and on keeps the one-second spacing of reads. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue. - Pictures never use the control queue. `output.rs` keeps at most one waiting picture per tile (newest wins), and control messages always go out first. Pictures are RGBA in byte order R, G, B, A, at most 640x360 and 15 per second per camera tile, and at most 1280x720 and 5 per second on the screen tile (5), checked by tile index before allocation. ## Build diff --git a/crates/call-worker/src/mapping/stats.rs b/crates/call-worker/src/mapping/stats.rs index e8016c74..1a34f039 100644 --- a/crates/call-worker/src/mapping/stats.rs +++ b/crates/call-worker/src/mapping/stats.rs @@ -1,8 +1,11 @@ //! Turns raw WebRTC counters into the call statistics message (ADR-0066). //! //! Pure: no LiveKit types, no I/O and no clock. The caller gives each -//! reading a time in milliseconds, and the book makes rates from the change -//! of a counter since the reading before. +//! track's and each transport's numbers the time they were read, in +//! milliseconds, and the book makes each rate from the change of a counter +//! since its sample before, over the time between the two samples. A +//! track's counters are kept under its track ID, so a new track never +//! compares with an older one. use std::collections::HashMap; @@ -111,6 +114,9 @@ fn kbps_from_bits(bits_per_second: f64) -> Option { /// The own microphone track. #[derive(Clone, Debug, Default, PartialEq)] pub struct RawOwnAudio { + /// The track ID, which keys its counters, and the time of its read. + pub track: String, + pub at_ms: u64, /// Linear, 0.0 to 1.0. pub level: f64, pub bytes_sent: u64, @@ -125,6 +131,8 @@ pub struct RawOwnAudio { /// the sum of their bytes and the largest layer's size and frame rate. #[derive(Clone, Debug, PartialEq)] pub struct RawOwnVideo { + pub track: String, + pub at_ms: u64, pub fps: f64, pub width: u32, pub height: u32, @@ -137,6 +145,8 @@ pub struct RawOwnVideo { /// participant; the smallest track id when it has more). #[derive(Clone, Debug, Default, PartialEq)] pub struct RawRemoteAudio { + pub track: String, + pub at_ms: u64, /// Linear, 0.0 to 1.0. pub level: f64, pub bytes_received: u64, @@ -150,6 +160,8 @@ pub struct RawRemoteAudio { /// The video of one remote participant. #[derive(Clone, Debug, Default, PartialEq)] pub struct RawRemoteVideo { + pub track: String, + pub at_ms: u64, pub fps: f64, pub width: u32, pub height: u32, @@ -166,23 +178,43 @@ pub struct RawRemote { pub video: Option, } +/// Which transport of a connection a link is. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum LinkRole { + /// The own room's single peer connection, which sends and receives. + Single, + Publisher, + Subscriber, +} + +/// The byte counters of one transport, read at `at_ms`. +#[derive(Clone, Debug, PartialEq)] +pub struct RawLink { + pub role: LinkRole, + pub at_ms: u64, + pub bytes_sent: u64, + pub bytes_received: u64, +} + /// One connection to an SFU. #[derive(Clone, Debug, Default, PartialEq)] pub struct RawConnection { pub connection: u8, /// WebRTC's estimate of the bandwidth for sending, in bit/s. pub outgoing_bits_per_second: Option, - /// The bytes sent and received on the connection's transports. - pub bytes_sent: Option, - pub bytes_received: Option, pub rtt_seconds: Option, + /// The transports whose bytes add up to the connection's totals, each + /// role once. + pub links: Vec, + /// Whether every transport that the connection uses was read. When one + /// was not, the totals would be short, so the byte rates are unknown. + pub complete: bool, } -/// One reading of everything. +/// One reading of everything. Each part carries the time it was read, on a +/// clock that only goes forward. #[derive(Clone, Debug, Default, PartialEq)] pub struct RawStats { - /// Milliseconds on a clock that only goes forward. - pub at_ms: u64, pub microphone: Option, pub camera: Option, pub screen: Option, @@ -190,14 +222,17 @@ pub struct RawStats { pub connections: Vec, } -/// What a counter belongs to. +/// What a counter belongs to: an own track by its track ID, a remote track +/// by connection, identity and track ID, or one transport of a connection. +/// A new track starts with no earlier value, so a switch (a camera after a +/// screen share, a new microphone) never gives a wrong rate. #[derive(Clone, Debug, Eq, Hash, PartialEq)] enum Source { - Microphone, - Camera, - Screen, - Remote(u8, String), - Connection(u8), + Microphone(String), + Camera(String), + Screen(String), + Remote(u8, String, String), + Link(u8, LinkRole), } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] @@ -213,43 +248,65 @@ enum Counter { type Key = (Source, Counter); -/// Remembers the last counters, so a reading gives rates. +/// A counter's value and the time it was read. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct Sample { + value: u64, + at_ms: u64, +} + +/// Remembers the last sample of each counter, so a reading gives rates. #[derive(Debug, Default)] pub struct StatsBook { - at_ms: Option, - counters: HashMap, + counters: HashMap, } /// The counters of one reading while it is made. struct Reading<'a> { - /// The time since the reading before, or `None` for the first reading - /// and for one at the same time or earlier. - interval_ms: Option, - before: &'a HashMap, - now: HashMap, + before: &'a HashMap, + now: HashMap, } impl Reading<'_> { - /// The change of a counter since the reading before. The counter is kept - /// for the next reading in any case. + /// The change of a counter since its sample before, and the time + /// between the two. `None` for a counter with no sample before, one that + /// was reset, and a sample at the time of the one before or earlier. A + /// sample at the same time keeps the one before, so the next sample + /// still has a rate; any other sample is kept for the next reading. fn delta( &mut self, source: &Source, counter: Counter, - value: u64, + sample: Sample, width: Width, - ) -> Option { + ) -> Option<(u64, u64)> { let key = (source.clone(), counter); - let delta = self - .interval_ms - .and_then(|_| counter_delta(self.before.get(&key).copied(), value, width)); - self.now.insert(key, value); - delta + let before = self.before.get(&key).copied(); + if let Some(before) = before + && before.at_ms == sample.at_ms + { + self.now.insert(key, before); + return None; + } + self.now.insert(key, sample); + let before = before?; + let interval = sample + .at_ms + .checked_sub(before.at_ms) + .filter(|interval| *interval > 0)?; + Some(( + counter_delta(Some(before.value), sample.value, width)?, + interval, + )) } - fn kbps(&mut self, source: &Source, counter: Counter, bytes: u64) -> Option { - let delta = self.delta(source, counter, bytes, Width::Bits64); - kbps(delta?, self.interval_ms?) + fn kbps(&mut self, source: &Source, counter: Counter, bytes: u64, at_ms: u64) -> Option { + let sample = Sample { + value: bytes, + at_ms, + }; + let (delta, interval) = self.delta(source, counter, sample, Width::Bits64)?; + kbps(delta, interval) } } @@ -257,56 +314,36 @@ impl StatsBook { /// Forgets every counter, so the next reading has no rates. Call it when /// the statistics are turned on, so a pause is not a long interval. pub fn reset(&mut self) { - self.at_ms = None; self.counters.clear(); } - /// The statistics message for `raw`. Rates are `None` for the first - /// reading, for a reading at the time of the one before, and for a - /// counter that was not there before or was reset. A reading at the - /// time of the one before changes nothing, so the next reading still - /// has a rate. Entries past the limits and entries the protocol would - /// refuse are left out. + /// The statistics message for `raw`. A rate is `None` for a counter with + /// no sample before (the first reading, a new track), one that was + /// reset, and one read at the time of its sample before or earlier. + /// Entries past the limits and entries the protocol would refuse are + /// left out. Counters that the reading does not show are forgotten. pub fn next(&mut self, raw: &RawStats) -> CallStats { - // The same time twice is a zero interval: no rates, and no change - // of what the next reading compares with. - let same_time = self.at_ms == Some(raw.at_ms); - let interval_ms = if same_time { - None - } else { - self.at_ms - .and_then(|before| raw.at_ms.checked_sub(before)) - .filter(|interval| *interval > 0) - }; let before = std::mem::take(&mut self.counters); let mut reading = Reading { - interval_ms, before: &before, now: HashMap::new(), }; - let stats = CallStats { - microphone: raw - .microphone - .as_ref() - .map(|audio| own_audio(&mut reading, audio)), - camera: raw - .camera - .as_ref() - .map(|video| own_video(&mut reading, &Source::Camera, video)), - screen: raw - .screen - .as_ref() - .map(|video| own_video(&mut reading, &Source::Screen, video)), - remotes: remotes(&mut reading, &raw.remotes), - connections: connections(&mut reading, &raw.connections), - }; - let now = reading.now; - if same_time { - self.counters = before; - } else { - self.counters = now; - self.at_ms = Some(raw.at_ms); - } + let stats = + CallStats { + microphone: raw + .microphone + .as_ref() + .map(|audio| own_audio(&mut reading, audio)), + camera: raw.camera.as_ref().map(|video| { + own_video(&mut reading, &Source::Camera(video.track.clone()), video) + }), + screen: raw.screen.as_ref().map(|video| { + own_video(&mut reading, &Source::Screen(video.track.clone()), video) + }), + remotes: remotes(&mut reading, &raw.remotes), + connections: connections(&mut reading, &raw.connections), + }; + self.counters = reading.now; stats } } @@ -314,7 +351,12 @@ impl StatsBook { fn own_audio(reading: &mut Reading<'_>, audio: &RawOwnAudio) -> AudioSendStats { AudioSendStats { level: sound_level(audio.level), - bitrate_kbps: reading.kbps(&Source::Microphone, Counter::BytesSent, audio.bytes_sent), + bitrate_kbps: reading.kbps( + &Source::Microphone(audio.track.clone()), + Counter::BytesSent, + audio.bytes_sent, + audio.at_ms, + ), packets_sent: unsigned(audio.packets_sent), packets_lost: audio.packets_lost.map(count), jitter_ms: audio.jitter_seconds.and_then(millis), @@ -327,7 +369,7 @@ fn own_video(reading: &mut Reading<'_>, source: &Source, video: &RawOwnVideo) -> fps: frames_per_second(video.fps), width: side(video.width), height: side(video.height), - bitrate_kbps: reading.kbps(source, Counter::BytesSent, video.bytes_sent), + bitrate_kbps: reading.kbps(source, Counter::BytesSent, video.bytes_sent, video.at_ms), limit: video.limit, packets_lost: video.packets_lost.map(count), } @@ -347,23 +389,39 @@ fn remotes(reading: &mut Reading<'_>, raw: &[RawRemote]) -> Vec { { continue; } - let source = Source::Remote(remote.connection, remote.identity.clone()); + let track = |track: &str| { + Source::Remote(remote.connection, remote.identity.clone(), track.to_owned()) + }; let audio = remote.audio.as_ref().map(|audio| { - let total = reading.delta( - &source, - Counter::TotalSamples, - audio.total_samples, - Width::Bits64, - ); - let concealed = reading.delta( - &source, - Counter::ConcealedSamples, - audio.concealed_samples, - Width::Bits64, - ); + let source = track(&audio.track); + let sample = |value| Sample { + value, + at_ms: audio.at_ms, + }; + let total = reading + .delta( + &source, + Counter::TotalSamples, + sample(audio.total_samples), + Width::Bits64, + ) + .map(|(delta, _)| delta); + let concealed = reading + .delta( + &source, + Counter::ConcealedSamples, + sample(audio.concealed_samples), + Width::Bits64, + ) + .map(|(delta, _)| delta); AudioReceiveStats { level: sound_level(audio.level), - bitrate_kbps: reading.kbps(&source, Counter::AudioBytes, audio.bytes_received), + bitrate_kbps: reading.kbps( + &source, + Counter::AudioBytes, + audio.bytes_received, + audio.at_ms, + ), packets_received: unsigned(audio.packets_received), packets_lost: count(audio.packets_lost), jitter_ms: millis(audio.jitter_seconds).unwrap_or(0), @@ -371,19 +429,27 @@ fn remotes(reading: &mut Reading<'_>, raw: &[RawRemote]) -> Vec { } }); let video = remote.video.as_ref().map(|video| { + let source = track(&video.track); let dropped = reading.delta( &source, Counter::FramesDropped, - video.frames_dropped, + Sample { + value: video.frames_dropped, + at_ms: video.at_ms, + }, Width::Bits32, ); VideoReceiveStats { fps: frames_per_second(video.fps), width: side(video.width), height: side(video.height), - bitrate_kbps: reading.kbps(&source, Counter::VideoBytes, video.bytes_received), + bitrate_kbps: reading.kbps( + &source, + Counter::VideoBytes, + video.bytes_received, + video.at_ms, + ), dropped_fps: dropped - .zip(reading.interval_ms) .and_then(|(delta, interval)| per_second(delta, interval)) .map(|rate| u8::try_from(rate.min(u64::from(MAX_STATS_FPS))).unwrap_or(0)), packets_lost: count(video.packets_lost), @@ -421,21 +487,47 @@ fn connections(reading: &mut Reading<'_>, raw: &[RawConnection]) -> Vec, + connection: &RawConnection, + counter: Counter, + bytes: fn(&RawLink) -> u64, +) -> Option { + let mut total = Some(0_u32); + let mut roles: Vec = Vec::new(); + for link in &connection.links { + if roles.contains(&link.role) { + continue; + } + roles.push(link.role); + let source = Source::Link(connection.connection, link.role); + let rate = reading.kbps(&source, counter, bytes(link), link.at_ms); + total = total + .zip(rate) + .map(|(sum, rate)| sum.saturating_add(rate).min(MAX_STATS_KBPS)); + } + total.filter(|_| connection.complete && !roles.is_empty()) +} + #[cfg(test)] mod tests; diff --git a/crates/call-worker/src/mapping/stats/tests.rs b/crates/call-worker/src/mapping/stats/tests.rs index c0b7237f..c3b69bb5 100644 --- a/crates/call-worker/src/mapping/stats/tests.rs +++ b/crates/call-worker/src/mapping/stats/tests.rs @@ -3,6 +3,8 @@ use persephone_call_protocol::MAX_IDENTITY_BYTES; fn audio_in(bytes: u64) -> RawRemoteAudio { RawRemoteAudio { + track: "TR_audio".to_owned(), + at_ms: 0, level: 0.5, bytes_received: bytes, packets_received: 100, @@ -24,6 +26,8 @@ fn remote(identity: &str, audio: Option) -> RawRemote { fn mic(bytes: u64) -> RawOwnAudio { RawOwnAudio { + track: "TR_mic".to_owned(), + at_ms: 0, level: 1.0, bytes_sent: bytes, packets_sent: 5, @@ -35,8 +39,10 @@ fn mic(bytes: u64) -> RawOwnAudio { fn reading(at_ms: u64, bytes: u64) -> RawStats { RawStats { - at_ms, - microphone: Some(mic(bytes)), + microphone: Some(RawOwnAudio { + at_ms, + ..mic(bytes) + }), ..RawStats::default() } } @@ -189,10 +195,7 @@ fn given_a_reset_book_when_read_then_the_first_reading_has_no_rate() { fn given_a_track_that_goes_and_returns_when_read_then_its_rate_starts_again() { let mut book = StatsBook::default(); book.next(&reading(1000, 0)); - book.next(&RawStats { - at_ms: 2000, - ..RawStats::default() - }); + book.next(&RawStats::default()); assert_eq!(bitrate(&book.next(&reading(3000, 99_000))), None); assert_eq!( bitrate(&book.next(&reading(4000, 99_000 + 125_000))), @@ -206,10 +209,10 @@ fn given_a_track_that_goes_and_returns_when_read_then_its_rate_starts_again() { fn given_concealed_samples_when_read_then_the_share_is_of_the_last_interval() { let mut book = StatsBook::default(); let with = |at_ms, total, concealed| RawStats { - at_ms, remotes: vec![remote( "@a:example.org:D", Some(RawRemoteAudio { + at_ms, total_samples: total, concealed_samples: concealed, ..audio_in(0) @@ -233,9 +236,9 @@ fn given_concealed_samples_when_read_then_the_share_is_of_the_last_interval() { fn given_dropped_frames_when_read_then_the_rate_is_per_second() { let mut book = StatsBook::default(); let with = |at_ms, dropped| RawStats { - at_ms, remotes: vec![RawRemote { video: Some(RawRemoteVideo { + at_ms, fps: 29.97, width: 1280, height: 720, @@ -258,10 +261,7 @@ fn given_dropped_frames_when_read_then_the_rate_is_per_second() { /// message holds only valid ones, each once, and at most the limit. #[test] fn given_bad_participants_when_read_then_only_valid_distinct_ones_stay() { - let mut raw = RawStats { - at_ms: 1000, - ..RawStats::default() - }; + let mut raw = RawStats::default(); raw.remotes.push(remote("", None)); raw.remotes.push(remote("bad\nname", None)); raw.remotes @@ -292,24 +292,42 @@ fn given_bad_participants_when_read_then_only_valid_distinct_ones_stay() { ); } +fn link(role: LinkRole, at_ms: u64, sent: u64, received: u64) -> RawLink { + RawLink { + role, + at_ms, + bytes_sent: sent, + bytes_received: received, + } +} + +fn connection(number: u8, links: Vec, complete: bool) -> RawConnection { + RawConnection { + connection: number, + outgoing_bits_per_second: Some(3_000_000.0), + rtt_seconds: Some(0.02), + links, + complete, + } +} + /// GIVEN connections that repeat or do not exist WHEN read THEN each real /// one is there once and the rates follow the transport bytes. #[test] fn given_connections_when_read_then_rates_follow_the_transport_bytes() { - let link = |connection, sent, received| RawConnection { - connection, - outgoing_bits_per_second: Some(3_000_000.0), - bytes_sent: Some(sent), - bytes_received: Some(received), - rtt_seconds: Some(0.02), + let one = |number, at_ms, sent, received| { + connection( + number, + vec![link(LinkRole::Single, at_ms, sent, received)], + true, + ) }; let raw = |at_ms, sent, received| RawStats { - at_ms, connections: vec![ - link(0, sent, received), - link(0, 0, 0), - link(1, sent, received), - link(MAX_OTHER_CONNECTIONS + 1, 0, 0), + one(0, at_ms, sent, received), + one(0, at_ms, 0, 0), + one(1, at_ms, sent, received), + one(MAX_OTHER_CONNECTIONS + 1, at_ms, 0, 0), ], ..RawStats::default() }; @@ -331,7 +349,6 @@ fn given_connections_when_read_then_rates_follow_the_transport_bytes() { fn given_a_participant_that_left_when_read_then_its_counters_are_forgotten() { let mut book = StatsBook::default(); let both = RawStats { - at_ms: 1000, remotes: vec![ remote("@a:example.org:D", Some(audio_in(1))), remote("@b:example.org:D", Some(audio_in(1))), @@ -341,13 +358,124 @@ fn given_a_participant_that_left_when_read_then_its_counters_are_forgotten() { book.next(&both); let held = book.counters.len(); book.next(&RawStats { - at_ms: 2000, - remotes: vec![remote("@a:example.org:D", Some(audio_in(1)))], + remotes: vec![remote( + "@a:example.org:D", + Some(RawRemoteAudio { + at_ms: 1000, + ..audio_in(1) + }), + )], ..RawStats::default() }); assert!(book.counters.len() < held); assert!(book.counters.keys().all(|(source, _)| matches!( source, - Source::Remote(0, identity) if identity == "@a:example.org:D" + Source::Remote(0, identity, _) if identity == "@a:example.org:D" ))); } + +/// GIVEN a participant whose video moves from one track to another (the +/// camera after a screen share) WHEN read THEN the new track has no rate +/// until its second reading, however its counters compare with the old +/// track's. +#[test] +fn given_a_new_track_for_a_participant_when_read_then_no_rate_crosses_tracks() { + let mut book = StatsBook::default(); + let with = |track: &str, at_ms, bytes, dropped| RawStats { + remotes: vec![RawRemote { + video: Some(RawRemoteVideo { + track: track.to_owned(), + at_ms, + bytes_received: bytes, + frames_dropped: dropped, + ..RawRemoteVideo::default() + }), + ..remote("@a:example.org:D", None) + }], + ..RawStats::default() + }; + let video = |stats: CallStats| stats.remotes[0].video.unwrap(); + book.next(&with("TR_screen", 1000, 100_000, 3)); + let switched = video(book.next(&with("TR_camera", 2000, 250_000, 9))); + assert_eq!(switched.bitrate_kbps, None, "never compared with the share"); + assert_eq!(switched.dropped_fps, None); + let next = video(book.next(&with("TR_camera", 3000, 250_000 + 125_000, 10))); + assert_eq!(next.bitrate_kbps, Some(1000)); + assert_eq!(next.dropped_fps, Some(1)); + // The own microphone after a device change is a new track too. + book.next(&reading(4000, 10_000)); + let new_mic = book.next(&RawStats { + microphone: Some(RawOwnAudio { + track: "TR_mic_2".to_owned(), + at_ms: 5000, + ..mic(500_000) + }), + ..RawStats::default() + }); + assert_eq!(bitrate(&new_mic), None); +} + +/// GIVEN two tracks read at different times in one reading WHEN the rates +/// are made THEN each uses the time between its own two reads, so a slow +/// read of another track never changes them. +#[test] +fn given_tracks_read_at_different_times_when_rated_then_each_uses_its_own_interval() { + let mut book = StatsBook::default(); + let with = |mic_at, remote_at, bytes| RawStats { + microphone: Some(RawOwnAudio { + at_ms: mic_at, + ..mic(bytes) + }), + remotes: vec![remote( + "@a:example.org:D", + Some(RawRemoteAudio { + at_ms: remote_at, + ..audio_in(bytes) + }), + )], + ..RawStats::default() + }; + book.next(&with(1000, 1000, 0)); + let stats = book.next(&with(2000, 2700, 125_000)); + assert_eq!(bitrate(&stats), Some(1000), "one second for the microphone"); + assert_eq!( + stats.remotes[0].audio.unwrap().bitrate_kbps, + Some(588), + "1.7 seconds for the remote track" + ); +} + +/// GIVEN a connection with a publisher and a subscriber transport WHEN one +/// transport was not read THEN the totals are unknown in that reading and +/// in the next one, and never jump; the reading after has the true rate. +#[test] +fn given_a_transport_that_was_not_read_when_rated_then_the_totals_are_unknown() { + let mut book = StatsBook::default(); + let both = |at_ms, published, subscribed| RawStats { + connections: vec![connection( + 0, + vec![ + link(LinkRole::Publisher, at_ms, published, 0), + link(LinkRole::Subscriber, at_ms, subscribed, 0), + ], + true, + )], + ..RawStats::default() + }; + let send = |stats: CallStats| stats.connections[0].send_kbps; + assert_eq!(send(book.next(&both(1000, 100_000, 50_000))), None); + assert_eq!(send(book.next(&both(2000, 200_000, 60_000))), Some(880)); + // The publisher's read missed its deadline. + let short = RawStats { + connections: vec![connection( + 0, + vec![link(LinkRole::Subscriber, 3000, 70_000, 0)], + false, + )], + ..RawStats::default() + }; + assert_eq!(send(book.next(&short)), None, "a short total is unknown"); + // The publisher has no sample before, so no jump on its return. + assert_eq!(send(book.next(&both(4000, 400_000, 80_000))), None); + assert_eq!(send(book.next(&both(5000, 420_000, 90_000))), Some(240)); +} diff --git a/crates/call-worker/src/session.rs b/crates/call-worker/src/session.rs index 4f6a2193..1f9498b4 100644 --- a/crates/call-worker/src/session.rs +++ b/crates/call-worker/src/session.rs @@ -2638,8 +2638,10 @@ impl Call<'_> { } participants += 1; // One microphone, and the camera before a screen share. - // The smallest track id breaks a tie, so every read - // follows the same track and its counters never jump. + // The smallest track id breaks a tie, so the reads + // follow one track while it stays. When the choice + // moves to another track, the book keys counters by + // track ID, so the new track starts without a rate. let mut audio: Option<(TrackSid, RemoteAudioTrack)> = None; let mut video: Option<(bool, TrackSid, RemoteVideoTrack)> = None; for publication in participant.track_publications().values() { diff --git a/crates/call-worker/src/session/stats_probe.rs b/crates/call-worker/src/session/stats_probe.rs index 1044e9d8..e1032d9f 100644 --- a/crates/call-worker/src/session/stats_probe.rs +++ b/crates/call-worker/src/session/stats_probe.rs @@ -5,10 +5,12 @@ //! under a deadline, so the event loop never waits for it. It reads only //! while the core has turned the statistics on, and at most once a second. //! The task gives back plain numbers (`RawStats`); `mapping::stats` makes -//! the message from them. Nothing here keeps a track, an address or a name: -//! only the numbers that the message carries leave the parse functions. +//! the message from them. Nothing here keeps a track handle, an address or a +//! name: only the numbers that the message carries, and each track's ID with +//! the time of its read, leave the parse functions. The ID keys the track's +//! counters in the worker and never leaves it. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::future::Future; use std::pin::Pin; use std::time::Duration; @@ -24,8 +26,8 @@ use tokio::time::Instant; use super::read_all; use crate::mapping::stats::{ - RawConnection, RawOwnAudio, RawOwnVideo, RawRemote, RawRemoteAudio, RawRemoteVideo, RawStats, - StatsBook, + LinkRole, RawConnection, RawLink, RawOwnAudio, RawOwnVideo, RawRemote, RawRemoteAudio, + RawRemoteVideo, RawStats, StatsBook, }; /// The shortest time between two reads. @@ -54,14 +56,49 @@ pub struct Sources { pub remote_video: Vec<(u8, String, RemoteVideoTrack)>, } -/// The reading of one track: its statistics, or none when they could not be -/// read. -enum Read { - Microphone(Vec), - Camera(Vec), - Screen(Vec), - RemoteAudio(u8, String, Vec), - RemoteVideo(u8, String, Vec), +/// Which track a read is of. +enum ReadKind { + Microphone, + Camera, + Screen, + RemoteAudio(u8, String), + RemoteVideo(u8, String), +} + +/// The reading of one track: its statistics (none when they could not be +/// read), its track ID, and the time the read finished on the probe's +/// clock. libwebrtc gathers a track's statistics just before its read +/// finishes, so that time is the time of its counters. +struct Read { + kind: ReadKind, + track: String, + at_ms: u64, + stats: Vec, +} + +impl Read { + fn new(kind: ReadKind, track: String, base: std::time::Instant, stats: Vec) -> Self { + Self { + kind, + track, + at_ms: since(base), + stats, + } + } +} + +/// Milliseconds since `base`. +fn since(base: std::time::Instant) -> u64 { + u64::try_from(base.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +/// The transports a read needs: the own room's publisher when an own track +/// is read, and each connection's subscriber when one of its remote tracks +/// is read. +#[derive(Default)] +struct Asked { + own: bool, + remote: BTreeSet, } type Job = Pin + Send>>; @@ -109,14 +146,14 @@ impl StatsProbe { } /// Turns the reads on or off (`SetStats`). Turning them on starts a new - /// series: the first reading has no rates. + /// series: the first reading has no rates. The time of the last start is + /// kept, so turning them off and on never reads more than once a second. pub fn set(&mut self, on: bool) { if on == self.on { return; } self.on = on; self.generation += 1; - self.started = None; self.book.reset(); // A read that runs ends by its deadline and reports; its report is // dropped by its number. The slot is freed only by that report. @@ -175,53 +212,66 @@ impl StatsProbe { async fn read(sources: Sources, base: std::time::Instant) -> RawStats { let deadline = Instant::now() + STATS_READ_BUDGET; let one_connection = sources.one_connection; + let mut asked = Asked::default(); let mut jobs: Vec = Vec::new(); if let Some(track) = sources.microphone { + asked.own = true; + let sid = track.sid().to_string(); jobs.push(Box::pin(async move { - Read::Microphone(track.get_stats().await.unwrap_or_default()) - })); - } - if let Some(track) = sources.camera { - jobs.push(Box::pin(async move { - Read::Camera(track.get_stats().await.unwrap_or_default()) + let stats = track.get_stats().await.unwrap_or_default(); + Read::new(ReadKind::Microphone, sid, base, stats) })); } - if let Some(track) = sources.screen { + for (kind, track) in [ + (ReadKind::Camera, sources.camera), + (ReadKind::Screen, sources.screen), + ] { + let Some(track) = track else { + continue; + }; + asked.own = true; + let sid = track.sid().to_string(); jobs.push(Box::pin(async move { - Read::Screen(track.get_stats().await.unwrap_or_default()) + let stats = track.get_stats().await.unwrap_or_default(); + Read::new(kind, sid, base, stats) })); } for (connection, identity, track) in sources.remote_audio { + asked.remote.insert(connection); + let sid = track.sid().to_string(); jobs.push(Box::pin(async move { - Read::RemoteAudio( - connection, - identity, - track.get_stats().await.unwrap_or_default(), + let stats = track.get_stats().await.unwrap_or_default(); + Read::new( + ReadKind::RemoteAudio(connection, identity), + sid, + base, + stats, ) })); } for (connection, identity, track) in sources.remote_video { + asked.remote.insert(connection); + let sid = track.sid().to_string(); jobs.push(Box::pin(async move { - Read::RemoteVideo( - connection, - identity, - track.get_stats().await.unwrap_or_default(), + let stats = track.get_stats().await.unwrap_or_default(); + Read::new( + ReadKind::RemoteVideo(connection, identity), + sid, + base, + stats, ) })); } let reads = read_all(deadline, jobs).await.into_iter().flatten(); - let at_ms = u64::try_from(base.elapsed().as_millis()).unwrap_or(u64::MAX); - assemble(at_ms, one_connection, reads) + assemble(&asked, one_connection, reads) } /// Makes the raw reading from what the reads gave. A track whose read did /// not finish is left out. `one_connection` says that the own room's tracks -/// all use one transport (see [`Sources::one_connection`]). -fn assemble(at_ms: u64, one_connection: bool, reads: impl Iterator) -> RawStats { - let mut raw = RawStats { - at_ms, - ..RawStats::default() - }; +/// all use one transport (see [`Sources::one_connection`]). A connection +/// whose needed transport (see [`Asked`]) no read gave is not complete. +fn assemble(asked: &Asked, one_connection: bool, reads: impl Iterator) -> RawStats { + let mut raw = RawStats::default(); // The first transport of the own tracks (the publisher) and of the // remote tracks of each connection (the subscriber). Each track's // statistics hold only its own streams and the transport they use. @@ -229,30 +279,31 @@ fn assemble(at_ms: u64, one_connection: bool, reads: impl Iterator) let mut subscribers: HashMap = HashMap::new(); let mut remotes: HashMap<(u8, String), RawRemote> = HashMap::new(); for read in reads { - match read { - Read::Microphone(stats) => { - raw.microphone = own_audio(&stats); - publisher = publisher.or_else(|| link(&stats)); + let found = link(&read); + match &read.kind { + ReadKind::Microphone => { + raw.microphone = own_audio(&read); + publisher = publisher.or(found); } - Read::Camera(stats) => { - raw.camera = own_video(&stats); - publisher = publisher.or_else(|| link(&stats)); + ReadKind::Camera => { + raw.camera = own_video(&read); + publisher = publisher.or(found); } - Read::Screen(stats) => { - raw.screen = own_video(&stats); - publisher = publisher.or_else(|| link(&stats)); + ReadKind::Screen => { + raw.screen = own_video(&read); + publisher = publisher.or(found); } - Read::RemoteAudio(connection, identity, stats) => { - if let Some(link) = link(&stats) { - subscribers.entry(connection).or_insert(link); + ReadKind::RemoteAudio(connection, identity) => { + if let Some(found) = found { + subscribers.entry(*connection).or_insert(found); } - remote(&mut remotes, connection, identity).audio = remote_audio(&stats); + remote(&mut remotes, *connection, identity).audio = remote_audio(&read); } - Read::RemoteVideo(connection, identity, stats) => { - if let Some(link) = link(&stats) { - subscribers.entry(connection).or_insert(link); + ReadKind::RemoteVideo(connection, identity) => { + if let Some(found) = found { + subscribers.entry(*connection).or_insert(found); } - remote(&mut remotes, connection, identity).video = remote_video(&stats); + remote(&mut remotes, *connection, identity).video = remote_video(&read); } } } @@ -262,44 +313,56 @@ fn assemble(at_ms: u64, one_connection: bool, reads: impl Iterator) raw.connections = (0..=MAX_OTHER_CONNECTIONS) .filter_map(|connection| { let subscriber = subscribers.get(&connection); - let (own, subscriber) = match connection { - // One peer connection: both reads saw the same transport. - 0 if one_connection => (publisher.as_ref().or(subscriber), None), - 0 => (publisher.as_ref(), subscriber), - _ => (None, subscriber), + let remote_asked = asked.remote.contains(&connection); + let links: Vec<(LinkRole, Option<&Link>, bool)> = match connection { + // One peer connection: every read of the room saw the same + // transport, so any one of them gives it. + 0 if one_connection => vec![( + LinkRole::Single, + publisher.as_ref().or(subscriber), + asked.own || remote_asked, + )], + 0 => vec![ + (LinkRole::Publisher, publisher.as_ref(), asked.own), + (LinkRole::Subscriber, subscriber, remote_asked), + ], + _ => vec![(LinkRole::Subscriber, subscriber, remote_asked)], }; - connection_stats(connection, own, subscriber) + connection_stats(connection, &links) }) .collect(); raw } -fn remote( - remotes: &mut HashMap<(u8, String), RawRemote>, +fn remote<'a>( + remotes: &'a mut HashMap<(u8, String), RawRemote>, connection: u8, - identity: String, -) -> &mut RawRemote { + identity: &str, +) -> &'a mut RawRemote { remotes - .entry((connection, identity.clone())) + .entry((connection, identity.to_owned())) .or_insert_with(|| RawRemote { connection, - identity, + identity: identity.to_owned(), audio: None, video: None, }) } /// The numbers of one peer connection's transport and its selected pair of -/// addresses. The addresses themselves are never read. +/// addresses, and the time of the read that gave them. The addresses +/// themselves are never read. #[derive(Clone, Debug, Default, PartialEq)] struct Link { + at_ms: u64, bytes_sent: u64, bytes_received: u64, outgoing_bits_per_second: Option, rtt_seconds: Option, } -fn link(stats: &[RtcStats]) -> Option { +fn link(read: &Read) -> Option { + let stats = &read.stats; let mut transports = stats.iter().filter_map(|stat| match stat { RtcStats::Transport(transport) => Some(transport), _ => None, @@ -314,6 +377,7 @@ fn link(stats: &[RtcStats]) -> Option { _ => None, }); Some(Link { + at_ms: read.at_ms, bytes_sent: transport.transport.bytes_sent, bytes_received: transport.transport.bytes_received, outgoing_bits_per_second: selected @@ -325,34 +389,54 @@ fn link(stats: &[RtcStats]) -> Option { }) } -/// The connection's numbers: what is sent and received in total on its -/// transports, the estimate of the outgoing bandwidth, and the round-trip -/// time. `None` when no transport was read. +/// The connection's numbers from its transports (`role`, the link a read +/// gave, whether a read needed it): each transport's bytes, the estimate of +/// the outgoing bandwidth, and the round-trip time. `None` when no +/// transport was read. Not complete when a needed transport is missing. fn connection_stats( connection: u8, - publisher: Option<&Link>, - subscriber: Option<&Link>, + transports: &[(LinkRole, Option<&Link>, bool)], ) -> Option { - let links: Vec<&Link> = publisher.into_iter().chain(subscriber).collect(); - if links.is_empty() { + let read: Vec<(LinkRole, &Link)> = transports + .iter() + .filter_map(|(role, link, _)| link.map(|link| (*role, link))) + .collect(); + if read.is_empty() { return None; } Some(RawConnection { connection, - outgoing_bits_per_second: links.iter().find_map(|link| link.outgoing_bits_per_second), - bytes_sent: Some(links.iter().map(|link| link.bytes_sent).sum()), - bytes_received: Some(links.iter().map(|link| link.bytes_received).sum()), - rtt_seconds: links.iter().find_map(|link| link.rtt_seconds), + outgoing_bits_per_second: read + .iter() + .find_map(|(_, link)| link.outgoing_bits_per_second), + rtt_seconds: read.iter().find_map(|(_, link)| link.rtt_seconds), + links: read + .iter() + .map(|(role, link)| RawLink { + role: *role, + at_ms: link.at_ms, + bytes_sent: link.bytes_sent, + bytes_received: link.bytes_received, + }) + .collect(), + complete: transports + .iter() + .all(|(_, link, needed)| link.is_some() || !needed), }) } -fn own_audio(stats: &[RtcStats]) -> Option { +fn own_audio(read: &Read) -> Option { + let stats = &read.stats; let mut audio: Option = None; for stat in stats { if let RtcStats::OutboundRtp(outbound) = stat && outbound.stream.kind == "audio" { - let audio = audio.get_or_insert_with(RawOwnAudio::default); + let audio = audio.get_or_insert_with(|| RawOwnAudio { + track: read.track.clone(), + at_ms: read.at_ms, + ..RawOwnAudio::default() + }); audio.bytes_sent = audio.bytes_sent.saturating_add(outbound.sent.bytes_sent); audio.packets_sent = audio .packets_sent @@ -388,7 +472,8 @@ fn limit(reason: QualityLimitationReason) -> QualityLimit { /// The own video track: the bytes of every layer, and the size, frame rate /// and limit of the largest one. -fn own_video(stats: &[RtcStats]) -> Option { +fn own_video(read: &Read) -> Option { + let stats = &read.stats; let mut video: Option = None; let mut largest = 0_u64; for stat in stats { @@ -404,6 +489,8 @@ fn own_video(stats: &[RtcStats]) -> Option { None => { largest = size; video = Some(RawOwnVideo { + track: read.track.clone(), + at_ms: read.at_ms, fps: outbound.outbound.frames_per_second, width: outbound.outbound.frame_width, height: outbound.outbound.frame_height, @@ -440,16 +527,20 @@ fn own_video(stats: &[RtcStats]) -> Option { Some(video.clone()) } -fn remote_audio(stats: &[RtcStats]) -> Option { +fn remote_audio(read: &Read) -> Option { let mut audio: Option = None; - for stat in stats { + for stat in &read.stats { let RtcStats::InboundRtp(inbound) = stat else { continue; }; if inbound.stream.kind != "audio" { continue; } - let audio = audio.get_or_insert_with(RawRemoteAudio::default); + let audio = audio.get_or_insert_with(|| RawRemoteAudio { + track: read.track.clone(), + at_ms: read.at_ms, + ..RawRemoteAudio::default() + }); audio.level = audio.level.max(inbound.inbound.audio_level); audio.bytes_received = audio .bytes_received @@ -471,16 +562,20 @@ fn remote_audio(stats: &[RtcStats]) -> Option { audio } -fn remote_video(stats: &[RtcStats]) -> Option { +fn remote_video(read: &Read) -> Option { let mut video: Option = None; - for stat in stats { + for stat in &read.stats { let RtcStats::InboundRtp(inbound) = stat else { continue; }; if inbound.stream.kind != "video" { continue; } - let video = video.get_or_insert_with(RawRemoteVideo::default); + let video = video.get_or_insert_with(|| RawRemoteVideo { + track: read.track.clone(), + at_ms: read.at_ms, + ..RawRemoteVideo::default() + }); video.fps = video.fps.max(inbound.inbound.frames_per_second); video.width = video.width.max(inbound.inbound.frame_width); video.height = video.height.max(inbound.inbound.frame_height); @@ -547,6 +642,28 @@ mod tests { probe.shutdown(); } + /// GIVEN a read that finished WHEN the statistics go off and on again + /// within a second THEN no read starts before a second since the last + /// start, and the next one has no rates. + #[tokio::test] + async fn given_a_quick_off_and_on_when_ticked_then_reads_stay_a_second_apart() { + let (mut probe, mut reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + let (generation, raw) = reports.recv().await.unwrap(); + assert!(probe.end(generation, raw).is_some()); + probe.set(false); + probe.set(true); + assert_eq!( + tick(&mut probe, start + Duration::from_millis(100)), + 0, + "the toggle keeps the time of the last start" + ); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1); + probe.shutdown(); + } + /// GIVEN a read that runs WHEN the statistics go off and on again THEN /// the old read's report gives no message and the slot stays taken until /// it reports, so two reads never run together. @@ -597,15 +714,14 @@ mod tests { /// up. #[test] fn given_a_connection_without_transports_when_assembled_then_it_has_no_entry() { - let raw = assemble(5, false, std::iter::empty()); - assert_eq!(raw.at_ms, 5); + let raw = assemble(&Asked::default(), false, std::iter::empty()); assert!(raw.connections.is_empty() && raw.remotes.is_empty()); let raw = assemble( - 6, + &asked(true, &[1]), false, [ - Read::Microphone(Vec::new()), - Read::RemoteAudio(1, "x".into(), Vec::new()), + read(ReadKind::Microphone, 6, Vec::new()), + read(ReadKind::RemoteAudio(1, "x".into()), 6, Vec::new()), ] .into_iter(), ); @@ -624,36 +740,83 @@ mod tests { vec![RtcStats::Transport(transport)] } + fn read(kind: ReadKind, at_ms: u64, stats: Vec) -> Read { + Read { + kind, + track: "TR".to_owned(), + at_ms, + stats, + } + } + + fn asked(own: bool, remote: &[u8]) -> Asked { + Asked { + own, + remote: remote.iter().copied().collect(), + } + } + fn reads() -> impl Iterator { [ - Read::Microphone(on_transport(100, 40)), - Read::RemoteAudio(0, "a".into(), on_transport(101, 41)), - Read::RemoteVideo(1, "b".into(), on_transport(7, 9)), + read(ReadKind::Microphone, 10, on_transport(100, 40)), + read( + ReadKind::RemoteAudio(0, "a".into()), + 11, + on_transport(101, 41), + ), + read(ReadKind::RemoteVideo(1, "b".into()), 12, on_transport(7, 9)), ] .into_iter() } + /// Each connection's (number, links as role, time, sent, received, and + /// whether it is complete). + fn links(raw: &RawStats) -> Vec<(u8, Vec<(LinkRole, u64, u64, u64)>, bool)> { + raw.connections + .iter() + .map(|c| { + let links = c + .links + .iter() + .map(|l| (l.role, l.at_ms, l.bytes_sent, l.bytes_received)) + .collect(); + (c.connection, links, c.complete) + }) + .collect() + } + /// GIVEN the own room uses one peer connection WHEN the reading is /// assembled THEN its transport is counted once, from the own tracks, /// and another connection keeps its own numbers. #[test] fn given_one_peer_connection_when_assembled_then_its_transport_counts_once() { - let raw = assemble(1, true, reads()); - let bytes: Vec<_> = raw - .connections - .iter() - .map(|c| (c.connection, c.bytes_sent, c.bytes_received)) - .collect(); - assert_eq!(bytes, [(0, Some(100), Some(40)), (1, Some(7), Some(9))]); + let raw = assemble(&asked(true, &[0, 1]), true, reads()); + assert_eq!( + links(&raw), + [ + (0, vec![(LinkRole::Single, 10, 100, 40)], true), + (1, vec![(LinkRole::Subscriber, 12, 7, 9)], true), + ] + ); } /// GIVEN the own room uses a publisher and a subscriber connection WHEN - /// the reading is assembled THEN both transports are added. + /// the reading is assembled THEN both transports are there, each with + /// the time of its own read. #[test] - fn given_two_peer_connections_when_assembled_then_both_transports_add() { - let raw = assemble(1, false, reads()); - assert_eq!(raw.connections[0].bytes_sent, Some(201)); - assert_eq!(raw.connections[0].bytes_received, Some(81)); + fn given_two_peer_connections_when_assembled_then_both_transports_are_there() { + let raw = assemble(&asked(true, &[0, 1]), false, reads()); + assert_eq!( + links(&raw)[0], + ( + 0, + vec![ + (LinkRole::Publisher, 10, 100, 40), + (LinkRole::Subscriber, 11, 101, 41) + ], + true + ) + ); } /// GIVEN one peer connection and no own track WHEN the reading is @@ -661,11 +824,72 @@ mod tests { #[test] fn given_one_peer_connection_without_own_tracks_then_the_remote_transport_counts() { let raw = assemble( - 1, + &asked(false, &[0]), true, - [Read::RemoteAudio(0, "a".into(), on_transport(3, 5))].into_iter(), + [read( + ReadKind::RemoteAudio(0, "a".into()), + 3, + on_transport(3, 5), + )] + .into_iter(), + ); + assert_eq!(links(&raw), [(0, vec![(LinkRole::Single, 3, 3, 5)], true)]); + } + + /// GIVEN two peer connections and an own track whose read did not finish + /// WHEN the reading is assembled THEN the connection has the subscriber + /// only and is not complete, so its totals are unknown, never short. + #[test] + fn given_a_missing_publisher_read_when_assembled_then_the_connection_is_not_complete() { + let raw = assemble( + &asked(true, &[0]), + false, + [read( + ReadKind::RemoteAudio(0, "a".into()), + 3, + on_transport(3, 5), + )] + .into_iter(), + ); + assert_eq!( + links(&raw), + [(0, vec![(LinkRole::Subscriber, 3, 3, 5)], false)] + ); + } + + /// GIVEN reads of tracks WHEN the reading is assembled THEN each track's + /// numbers carry its track ID and the time of its own read. + #[test] + fn given_reads_when_assembled_then_each_track_has_its_id_and_time() { + let mut outbound = livekit::webrtc::stats::OutboundRtpStats::default(); + outbound.stream.kind = "audio".to_owned(); + let mut inbound = livekit::webrtc::stats::InboundRtpStats::default(); + inbound.stream.kind = "video".to_owned(); + let raw = assemble( + &asked(true, &[0]), + true, + [ + Read { + kind: ReadKind::Microphone, + track: "TR_mic".to_owned(), + at_ms: 20, + stats: vec![RtcStats::OutboundRtp(outbound)], + }, + Read { + kind: ReadKind::RemoteVideo(0, "a".into()), + track: "TR_cam".to_owned(), + at_ms: 27, + stats: vec![RtcStats::InboundRtp(inbound)], + }, + ] + .into_iter(), + ); + let microphone = raw.microphone.unwrap(); + assert_eq!( + (microphone.track.as_str(), microphone.at_ms), + ("TR_mic", 20) ); - assert_eq!(raw.connections[0].bytes_sent, Some(3)); - assert_eq!(raw.connections[0].bytes_received, Some(5)); + let video = raw.remotes[0].video.as_ref().unwrap(); + assert_eq!((video.track.as_str(), video.at_ms), ("TR_cam", 27)); } } diff --git a/crates/contracts/AGENTS.md b/crates/contracts/AGENTS.md index cbad71d7..f17c7e03 100644 --- a/crates/contracts/AGENTS.md +++ b/crates/contracts/AGENTS.md @@ -8,7 +8,7 @@ This crate defines small Rust view types and exports their TypeScript representa - Inspect `frontend/src/bridge/index.ts`, core view production, and Tauri consumers for compatibility. Static TypeScript types do not validate untrusted runtime data. - Keep sample data synthetic, including hostile text that must remain inert when rendered. -- Call statistics (ADR-0066): `CallStats` and its parts hold integers with bounds (`CALL_STATS_*`). `CallStats::within_limits` is the check that the core, the UI host and the page's `parseCallStats` all repeat; change them together. +- Call statistics (ADR-0066): `CallStats` and its parts hold integers with bounds (`CALL_STATS_*`). `CallStats::within_limits` is the check that the core, the UI host and the page's `parseCallStats` all repeat; change them together. The `CALL_STATS_*` bounds repeat `MAX_STATS_*` in `crates/call-protocol/src/stats.rs`, and `crates/core/src/calls/stats.rs` checks at compile time that they match. Each `Option` field is required-nullable (`Option::deserialize`): the key must be there, and only its value may be null. ## Checks diff --git a/crates/contracts/generated/contracts.ts b/crates/contracts/generated/contracts.ts index 8e47d641..d8d17907 100644 --- a/crates/contracts/generated/contracts.ts +++ b/crates/contracts/generated/contracts.ts @@ -1014,3 +1014,18 @@ export const CALL_DEVICE_ID_BYTES_MAX = 255; /** The top of a call sound level meter. */ export const CALL_SOUND_LEVEL_MAX = 100; + +/** The highest call statistic bitrate, in kbit/s. */ +export const CALL_STATS_KBPS_MAX = 1000000; + +/** The longest call statistic time, in milliseconds. */ +export const CALL_STATS_MS_MAX = 60000; + +/** The highest call statistic frame rate. */ +export const CALL_STATS_FPS_MAX = 120; + +/** The longest call statistic picture side, in pixels. */ +export const CALL_STATS_SIDE_MAX = 16384; + +/** The most connections in one call statistics reading. */ +export const CALL_STATS_CONNECTIONS_MAX = 4; diff --git a/crates/contracts/src/lib.rs b/crates/contracts/src/lib.rs index c304bf6c..45c8a195 100644 --- a/crates/contracts/src/lib.rs +++ b/crates/contracts/src/lib.rs @@ -2455,6 +2455,11 @@ pub struct CallParticipantLevel { pub level: u8, } +// The `CALL_STATS_*` bounds repeat `MAX_STATS_*` of the call protocol, which +// the worker clamps each number to. A number over a bound here drops the +// whole reading, so the core checks at compile time that both sets match +// (`crates/core/src/calls/stats.rs`). Change them together. + /// The highest bitrate or bandwidth a call statistic shows, in kbit/s. pub const CALL_STATS_KBPS_MAX: u32 = 1_000_000; /// The longest time a call statistic shows, in milliseconds. @@ -2478,19 +2483,25 @@ pub enum CallStatsLimit { } /// The own microphone. An unknown value is null: a rate needs two readings, -/// and the far end reports loss, jitter and round-trip time later. +/// and the far end reports loss, jitter and round-trip time later. Each +/// value that may be null is still a required key, here and in the other +/// statistics types. #[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct CallStatsAudioSent { /// 0 to [`CALL_SOUND_LEVEL_MAX`]. pub level: u8, /// Kbit/s, at most [`CALL_STATS_KBPS_MAX`]. + #[serde(deserialize_with = "Option::deserialize")] pub bitrate_kbps: Option, pub packets_sent: u32, /// Packets the far end reports lost. + #[serde(deserialize_with = "Option::deserialize")] pub packets_lost: Option, /// Milliseconds, at most [`CALL_STATS_MS_MAX`]. + #[serde(deserialize_with = "Option::deserialize")] pub jitter_ms: Option, + #[serde(deserialize_with = "Option::deserialize")] pub rtt_ms: Option, } @@ -2503,8 +2514,10 @@ pub struct CallStatsVideoSent { /// At most [`CALL_STATS_SIDE_MAX`] each. pub width: u16, pub height: u16, + #[serde(deserialize_with = "Option::deserialize")] pub bitrate_kbps: Option, pub limit: CallStatsLimit, + #[serde(deserialize_with = "Option::deserialize")] pub packets_lost: Option, } @@ -2514,11 +2527,13 @@ pub struct CallStatsVideoSent { pub struct CallStatsAudioReceived { /// 0 to [`CALL_SOUND_LEVEL_MAX`]. pub level: u8, + #[serde(deserialize_with = "Option::deserialize")] pub bitrate_kbps: Option, pub packets_received: u32, pub packets_lost: u32, pub jitter_ms: u16, /// The share of the last second's samples that WebRTC made up, 0 to 100. + #[serde(deserialize_with = "Option::deserialize")] pub concealed_percent: Option, } @@ -2529,8 +2544,10 @@ pub struct CallStatsVideoReceived { pub fps: u8, pub width: u16, pub height: u16, + #[serde(deserialize_with = "Option::deserialize")] pub bitrate_kbps: Option, /// Frames dropped each second, at most [`CALL_STATS_FPS_MAX`]. + #[serde(deserialize_with = "Option::deserialize")] pub dropped_fps: Option, pub packets_lost: u32, } @@ -2542,7 +2559,9 @@ pub struct CallStatsVideoReceived { pub struct CallStatsParticipant { pub user_id: String, pub device_id: String, + #[serde(deserialize_with = "Option::deserialize")] pub audio: Option, + #[serde(deserialize_with = "Option::deserialize")] pub video: Option, } @@ -2553,10 +2572,14 @@ pub struct CallStatsParticipant { pub struct CallStatsConnection { pub connection: u8, /// The bandwidth that WebRTC estimates for sending, kbit/s. + #[serde(deserialize_with = "Option::deserialize")] pub outgoing_kbps: Option, /// Everything sent and received on the connection, kbit/s. + #[serde(deserialize_with = "Option::deserialize")] pub send_kbps: Option, + #[serde(deserialize_with = "Option::deserialize")] pub receive_kbps: Option, + #[serde(deserialize_with = "Option::deserialize")] pub rtt_ms: Option, } @@ -2566,8 +2589,11 @@ pub struct CallStatsConnection { #[derive(Clone, Debug, Default, Deserialize, Serialize, TS, PartialEq, Eq)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct CallStats { + #[serde(deserialize_with = "Option::deserialize")] pub microphone: Option, + #[serde(deserialize_with = "Option::deserialize")] pub camera: Option, + #[serde(deserialize_with = "Option::deserialize")] pub screen: Option, /// At most [`CALL_PARTICIPANTS_MAX`], each device once. pub participants: Vec, @@ -3236,6 +3262,35 @@ pub fn generated_typescript() -> String { output.push_str(&format!( "\n/** The top of a call sound level meter. */\nexport const CALL_SOUND_LEVEL_MAX = {CALL_SOUND_LEVEL_MAX};\n" )); + for (doc, name, value) in [ + ( + "The highest call statistic bitrate, in kbit/s.", + "CALL_STATS_KBPS_MAX", + u64::from(CALL_STATS_KBPS_MAX), + ), + ( + "The longest call statistic time, in milliseconds.", + "CALL_STATS_MS_MAX", + u64::from(CALL_STATS_MS_MAX), + ), + ( + "The highest call statistic frame rate.", + "CALL_STATS_FPS_MAX", + u64::from(CALL_STATS_FPS_MAX), + ), + ( + "The longest call statistic picture side, in pixels.", + "CALL_STATS_SIDE_MAX", + u64::from(CALL_STATS_SIDE_MAX), + ), + ( + "The most connections in one call statistics reading.", + "CALL_STATS_CONNECTIONS_MAX", + CALL_STATS_CONNECTIONS_MAX as u64, + ), + ] { + output.push_str(&format!("\n/** {doc} */\nexport const {name} = {value};\n")); + } output } diff --git a/crates/contracts/tests/contracts.rs b/crates/contracts/tests/contracts.rs index 88125f93..a3186369 100644 --- a/crates/contracts/tests/contracts.rs +++ b/crates/contracts/tests/contracts.rs @@ -1089,6 +1089,51 @@ fn call_stats_cross_with_camel_case_names_and_refuse_unknown_fields() { } } +/// GIVEN a statistics reading WHEN a value that may be null is null THEN it +/// reads as unknown, and WHEN its key is left out THEN the reading is +/// refused: the key is required, as the TypeScript contract declares. +#[test] +fn call_stats_need_each_nullable_key() { + let json = serde_json::to_value(sample_call_stats()).unwrap(); + for (path, keys) in [ + ("", &["microphone", "camera", "screen"][..]), + ( + "/microphone", + &["bitrateKbps", "packetsLost", "jitterMs", "rttMs"], + ), + ("/camera", &["bitrateKbps", "packetsLost"]), + ("/participants/0", &["audio", "video"]), + ( + "/participants/0/audio", + &["bitrateKbps", "concealedPercent"], + ), + ("/participants/0/video", &["bitrateKbps", "droppedFps"]), + ( + "/connections/0", + &["outgoingKbps", "sendKbps", "receiveKbps", "rttMs"], + ), + ] { + for key in keys { + let mut null = json.clone(); + null.pointer_mut(path).unwrap()[*key] = serde_json::Value::Null; + assert!( + serde_json::from_value::(null).is_ok(), + "{path}/{key} may be null" + ); + let mut missing = json.clone(); + let object = missing.pointer_mut(path).unwrap().as_object_mut().unwrap(); + assert!( + object.remove(*key).is_some(), + "{path}/{key} is in the sample" + ); + assert!( + serde_json::from_value::(missing).is_err(), + "{path}/{key} may not be left out" + ); + } + } +} + /// GIVEN a statistics reading with one value over its bound, too many or /// repeated entries, or an overlong ID WHEN it is checked THEN it is /// refused whole. diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index edab3bfa..a3ebe190 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -1176,13 +1176,14 @@ pub fn levels_within_limits(levels: &[persephone_contracts::CallParticipantLevel }) } -/// Reads a statistics reading and refuses one with a number over its bound, -/// too many or repeated entries or an overlong ID. The frame that carries it -/// is already bounded by the transport. +/// Reads a statistics reading. Only a JSON object is read, each list stops +/// at its limit before it builds one more entry, and each ID is bounded +/// before it is copied. `CallStats::within_limits` then checks the numbers +/// and repeats: a reading that fails is refused whole. fn bounded_stats<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result { - let stats = persephone_contracts::CallStats::deserialize(deserializer)?; + let stats = deserializer.deserialize_map(WireStats)?; if stats.within_limits() { Ok(stats) } else { @@ -1190,48 +1191,187 @@ fn bounded_stats<'de, D: serde::Deserializer<'de>>( } } -/// Reads a level list and refuses an entry past [`MAX_CALL_LEVELS`], an -/// overlong ID or a level out of range before it keeps it, so a hostile list -/// allocates at most the limits. +/// The map-only reader of a statistics reading. Every key is required, and +/// the keys of the parts that may be null take `null`. +struct WireStats; + +impl<'de> serde::de::Visitor<'de> for WireStats { + type Value = persephone_contracts::CallStats; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a call statistics object") + } + + fn visit_map>(self, mut map: A) -> Result { + use serde::de::Error; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + enum Field { + Microphone, + Camera, + Screen, + Participants, + Connections, + } + let (mut microphone, mut camera, mut screen) = (None, None, None); + let (mut participants, mut connections) = (None, None); + while let Some(field) = map.next_key::()? { + let fresh = match field { + Field::Microphone => microphone.replace(map.next_value()?).is_none(), + Field::Camera => camera.replace(map.next_value()?).is_none(), + Field::Screen => screen.replace(map.next_value()?).is_none(), + Field::Participants => participants + .replace(map.next_value::>()?) + .is_none(), + Field::Connections => connections + .replace(map.next_value::>()?) + .is_none(), + }; + if !fresh { + return Err(A::Error::custom("duplicate call statistics field")); + } + } + let participants = participants.ok_or_else(|| A::Error::missing_field("participants"))?; + Ok(persephone_contracts::CallStats { + microphone: microphone.ok_or_else(|| A::Error::missing_field("microphone"))?, + camera: camera.ok_or_else(|| A::Error::missing_field("camera"))?, + screen: screen.ok_or_else(|| A::Error::missing_field("screen"))?, + participants: participants + .0 + .into_iter() + .map(|participant| persephone_contracts::CallStatsParticipant { + user_id: participant.user_id.0, + device_id: participant.device_id.0, + audio: participant.audio, + video: participant.video, + }) + .collect(), + connections: connections + .ok_or_else(|| A::Error::missing_field("connections"))? + .0, + }) + } +} + +/// One device of a statistics reading as it crosses, with its IDs bounded. +/// Only a JSON object is read, and every key is required. +struct WireParticipant { + user_id: BoundedText, + device_id: BoundedText, + audio: Option, + video: Option, +} + +impl<'de> Deserialize<'de> for WireParticipant { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + enum Field { + UserId, + DeviceId, + Audio, + Video, + } + struct Entry; + impl<'de> serde::de::Visitor<'de> for Entry { + type Value = WireParticipant; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a call statistics participant object") + } + + fn visit_map>( + self, + mut map: A, + ) -> Result { + use serde::de::Error; + let (mut user_id, mut device_id, mut audio, mut video) = (None, None, None, None); + while let Some(field) = map.next_key::()? { + let fresh = match field { + Field::UserId => user_id.replace(map.next_value()?).is_none(), + Field::DeviceId => device_id.replace(map.next_value()?).is_none(), + Field::Audio => audio.replace(map.next_value()?).is_none(), + Field::Video => video.replace(map.next_value()?).is_none(), + }; + if !fresh { + return Err(A::Error::custom("duplicate call statistics field")); + } + } + Ok(WireParticipant { + user_id: user_id.ok_or_else(|| A::Error::missing_field("userId"))?, + device_id: device_id.ok_or_else(|| A::Error::missing_field("deviceId"))?, + audio: audio.ok_or_else(|| A::Error::missing_field("audio"))?, + video: video.ok_or_else(|| A::Error::missing_field("video"))?, + }) + } + } + deserializer.deserialize_map(Entry) + } +} + +/// Reads a level list and refuses an entry past [`MAX_CALL_LEVELS`] or an +/// overlong ID before it keeps it, so a hostile list allocates at most the +/// limits, and then a level out of range. fn bounded_levels<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { - struct Levels; - impl<'de> serde::de::Visitor<'de> for Levels { - type Value = Vec; + let BoundedList(levels) = BoundedList::::deserialize(deserializer)?; + if levels + .iter() + .any(|level| level.level > MAX_CALL_SOUND_LEVEL) + { + return Err(serde::de::Error::custom("call levels out of bounds")); + } + Ok(levels + .into_iter() + .map(|level| persephone_contracts::CallParticipantLevel { + user_id: level.user_id.0, + device_id: level.device_id.0, + level: level.level, + }) + .collect()) +} - fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "at most {MAX_CALL_LEVELS} call levels") - } +/// A list of at most `N` entries. The entry past the limit is refused +/// before it is built: a full list only checks for one more, unbuilt. +struct BoundedList(Vec); + +impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for BoundedList { + fn deserialize>(deserializer: D) -> Result { + struct List(std::marker::PhantomData); + impl<'de, T: Deserialize<'de>, const N: usize> serde::de::Visitor<'de> for List { + type Value = BoundedList; - fn visit_seq>( - self, - mut seq: A, - ) -> Result { - let mut levels = Vec::new(); - loop { - // A full list only checks for one more entry, unbuilt. - if levels.len() == MAX_CALL_LEVELS { - if seq.next_element::()?.is_some() { - return Err(serde::de::Error::custom("call levels out of bounds")); + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "a list of at most {N} entries") + } + + fn visit_seq>( + self, + mut seq: A, + ) -> Result { + let mut entries = Vec::new(); + loop { + if entries.len() == N { + if seq.next_element::()?.is_some() { + return Err(serde::de::Error::custom(format_args!( + "list over its limit of {N} entries" + ))); + } + return Ok(BoundedList(entries)); } - return Ok(levels); - } - let Some(level) = seq.next_element::()? else { - return Ok(levels); - }; - if level.level > MAX_CALL_SOUND_LEVEL { - return Err(serde::de::Error::custom("call levels out of bounds")); + let Some(entry) = seq.next_element()? else { + return Ok(BoundedList(entries)); + }; + entries.push(entry); } - levels.push(persephone_contracts::CallParticipantLevel { - user_id: level.user_id.0, - device_id: level.device_id.0, - level: level.level, - }); } } + deserializer.deserialize_seq(List(std::marker::PhantomData)) } - deserializer.deserialize_seq(Levels) } /// One entry of a level list as it crosses, with its IDs bounded. Only a @@ -4230,6 +4370,25 @@ mod timeline_events_wire_tests { let mut extra = reading(1, "@a:example.org"); extra["address"] = "10.0.0.1".into(); assert!(event(extra).is_err()); + for key in ["microphone", "screen", "participants", "connections"] { + let mut missing = reading(1, "@a:example.org"); + missing.as_object_mut().unwrap().remove(key); + assert!(event(missing).is_err(), "{key}"); + } + for key in ["audio", "deviceId"] { + let mut missing = reading(1, "@a:example.org"); + missing["participants"][0] + .as_object_mut() + .unwrap() + .remove(key); + assert!(event(missing).is_err(), "{key}"); + } + let mut no_rate = reading(1, "@a:example.org"); + no_rate["camera"] + .as_object_mut() + .unwrap() + .remove("bitrateKbps"); + assert!(event(no_rate).is_err()); let wire = serde_json::to_string(&CoreMessage::Event(Event::CallStats { stats: persephone_contracts::CallStats::default(), })) @@ -4238,6 +4397,52 @@ mod timeline_events_wire_tests { assert!(serde_json::from_str::(&wire).is_ok()); } + /// GIVEN statistics events with a list past its limit, a positional + /// array or a repeated key WHEN read THEN each is refused: the reader + /// takes objects only and stops a list at its limit as it reads. + #[test] + fn given_call_stats_past_their_limits_or_in_arrays_then_they_are_refused() { + let event = |stats: serde_json::Value| { + serde_json::from_value::( + serde_json::json!({"event": {"call_stats": {"stats": stats}}}), + ) + }; + let participant = |index: usize| { + serde_json::json!({"userId": format!("@u{index}:example.org"), "deviceId": "D", + "audio": null, "video": null}) + }; + let connection = |index: usize| { + serde_json::json!({"connection": index, "outgoingKbps": null, "sendKbps": null, + "receiveKbps": null, "rttMs": null}) + }; + let reading = |participants: usize, connections: usize| { + serde_json::json!({ + "microphone": null, "camera": null, "screen": null, + "participants": (0..participants).map(participant).collect::>(), + "connections": (0..connections).map(connection).collect::>(), + }) + }; + let full = persephone_contracts::CALL_STATS_CONNECTIONS_MAX; + assert!(event(reading(MAX_CALL_LEVELS, full)).is_ok()); + assert!(event(reading(MAX_CALL_LEVELS + 1, 0)).is_err()); + // An entry past the limit is refused unbuilt, whatever it holds. + let mut over = reading(MAX_CALL_LEVELS, 0); + over["participants"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({"anything": [1, 2, 3]})); + let error = event(over).unwrap_err(); + assert!(error.to_string().contains("over its limit"), "{error}"); + assert!(event(reading(0, full + 1)).is_err()); + assert!(event(serde_json::json!([null, null, null, [], []])).is_err()); + let mut positional = reading(0, 0); + positional["participants"] = serde_json::json!([["@a:example.org", "D", null, null]]); + assert!(event(positional).is_err()); + let twice = r#"{"event":{"call_stats":{"stats":{"microphone":null,"microphone":null, + "camera":null,"screen":null,"participants":[],"connections":[]}}}}"#; + assert!(serde_json::from_str::(twice).is_err()); + } + /// GIVEN call level events WHEN read THEN bounded ones are kept, and a /// level over the top, too many devices or an overlong ID is refused. #[test] @@ -4282,10 +4487,7 @@ mod timeline_events_wire_tests { let missing = br#"{"event":{"call_levels":{"levels":[{"userId":"@a:example.org","deviceId":"D"}]}}}"#; assert!(serde_json::from_slice::(missing).is_err()); - assert!( - error.to_string().contains("call levels out of bounds"), - "{error}" - ); + assert!(error.to_string().contains("over its limit"), "{error}"); let longest = "a".repeat(MAX_USER_ID_BYTES); assert!(event(serde_json::json!([one(1, &longest)])).is_ok()); let device = "D".repeat(MAX_DEVICE_ID_BYTES + 1); diff --git a/crates/core/src/calls/stats.rs b/crates/core/src/calls/stats.rs index f47ed6d6..86fe299a 100644 --- a/crates/core/src/calls/stats.rs +++ b/crates/core/src/calls/stats.rs @@ -11,6 +11,18 @@ use persephone_contracts::{ CallStatsParticipant, CallStatsVideoReceived, CallStatsVideoSent, }; +// The page's bounds repeat the worker protocol's. The worker clamps each +// number to its protocol bound, and `CallStats::within_limits` drops a +// reading whole on a number over the page's bound, so the two must match. +const _: () = { + assert!(persephone_contracts::CALL_STATS_KBPS_MAX == worker::MAX_STATS_KBPS); + assert!(persephone_contracts::CALL_STATS_MS_MAX == worker::MAX_STATS_MS); + assert!(persephone_contracts::CALL_STATS_FPS_MAX == worker::MAX_STATS_FPS); + assert!(persephone_contracts::CALL_STATS_SIDE_MAX == worker::MAX_STATS_SIDE); + assert!(persephone_contracts::CALL_STATS_CONNECTIONS_MAX == worker::MAX_STATS_CONNECTIONS); + assert!(persephone_contracts::CALL_PARTICIPANTS_MAX == worker::MAX_PARTICIPANTS); +}; + fn limit(limit: worker::QualityLimit) -> CallStatsLimit { match limit { worker::QualityLimit::None => CallStatsLimit::None, diff --git a/docs/adr/0066-show-call-statistics-on-request.md b/docs/adr/0066-show-call-statistics-on-request.md index 03831294..e2ddf762 100644 --- a/docs/adr/0066-show-call-statistics-on-request.md +++ b/docs/adr/0066-show-call-statistics-on-request.md @@ -82,17 +82,24 @@ for the answer, and a reading is old when the page asks for it. tracks, and of one audio and one video track of each remote participant (at most 32 participants, so at most 64 remote reads): the microphone, and the camera before a screen share, with the smallest track ID when there - are more, so each read follows the same track and its counters never jump. + are more, so the reads follow one track while it stays. Each read keeps + its track ID and the time it finished. libwebrtc gives each track only its own streams and the transport they use. The own room uses LiveKit's single peer connection when the server offers it; its own and remote tracks then read one transport, which counts - once. With a publisher and a subscriber connection, both add. The connection - numbers come from the transport and the selected candidate pair that those - reports already include. A connection with no track has no entry. -* `mapping/stats.rs` is pure. `StatsBook` keeps the last counters and makes - each rate from the change since the reading before. A counter that fell, a - counter with no earlier value, and a zero or negative interval give no rate - (`null`), never a wrong one. A 32-bit counter that wrapped counts across + once. With a publisher and a subscriber connection, both add, each from its + own counters. The connection numbers come from the transport and the + selected candidate pair that those reports already include. A connection + with no track has no entry. When a transport that a connection uses was + not read (its read missed the deadline), the connection's send and + receive rates are unknown for that reading, never short. +* `mapping/stats.rs` is pure. `StatsBook` keeps the last sample of each + counter, with the time of the read that gave it, under the track's ID (or + the connection's transport). Each rate is the change since that sample, + over the time between the two reads, so a slow read of another track + never changes it, and a new track never compares with an old one. A + counter that fell, a counter with no earlier value, and a zero or + negative interval give no rate (`null`), never a wrong one. A 32-bit counter that wrapped counts across the wrap. Every number is clamped to its bound, and an entry whose identity or connection the protocol would refuse is left out. * The reading goes to `Output::offer_stats`. It never waits, it replaces a @@ -128,6 +135,12 @@ candidate type, SSRC, codec or other text. * The core keeps only the newest reading and sends it as `Event::CallStats`. The UI host reads the event with the same limits and sends it only to the channel of a window that turned the details on. +* The UI host keeps a window's channel only after the core accepted the + start. Its own stop on a reload or close is a request too, so the host + lets one change of the core's switch run at a time, and each ends with the + switch as the kept channels want. A start that a reload or close overtook + keeps no channel and turns the switch off again; a late stop does not + undo the start of the page that came next. * The capability `call` gains `allow-call-stats`, and nothing else. The main window does not have it. diff --git a/frontend/src/CallWindow.svelte b/frontend/src/CallWindow.svelte index a50146d0..7b1db789 100644 --- a/frontend/src/CallWindow.svelte +++ b/frontend/src/CallWindow.svelte @@ -53,7 +53,7 @@ volumeValue } from './calls'; import { callGrid, ROSTER_LABEL, SelfClose, type CallCell } from './callWindow'; - import { AUTO_PICK, keepPick, largeKey, selectFeed, showAll, splitFeeds, type ViewPick } from './callView'; + import { AUTO_PICK, feedKeys, keepPick, largeKey, selectFeed, showAll, splitFeeds, type ViewPick } from './callView'; import CallWindowDevices from './CallWindowDevices.svelte'; import CallStatsPanel from './CallStats.svelte'; import { STATS_LABEL } from './callStats'; @@ -215,7 +215,8 @@ }); const grid = $derived(callGrid(status)); - const keys = $derived(grid.map((cell) => cell.key)); + // Only a cell with a picture is a feed: a camera that goes off drops its pick. + const keys = $derived(feedKeys(grid)); const large = $derived(largeKey(pick, keys)); const view = $derived(splitFeeds(grid, large)); @@ -305,7 +306,17 @@ {@const shape = cell.tile === null ? undefined : shapes[cell.tile]} {@const layout = shape && cell.tile !== null ? tileLayout(shape.width, shape.height, shape.rotation, cell.own) : null}
- +{/snippet} +
{callAnnouncement(status, dismissed)}
@@ -111,10 +119,7 @@ {#if ended} {:else if !full} - + {@render callWindowButton()} {:else} - + {@render callWindowButton()} {/if} @@ -205,7 +207,7 @@ {#if !ended && full && screenText !== ''}

{screenText}

{/if} - {#if !ended && full && status.deviceChange} + {#if !ended && status.deviceChange}

{DEVICE_CHANGE_TEXT[status.deviceChange]}

{/if} {#if ended} diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs index bb35e38b..d6f6960d 100644 --- a/frontend/tests/render.test.mjs +++ b/frontend/tests/render.test.mjs @@ -260,7 +260,12 @@ test('GIVEN a call window that opens WHEN the call bar renders THEN it shows the assert.match(short, /class="secondary call-window-open"/); assert.match(short, />Declined(app: AppHandle) -> Result<(), String> { if let Some(window) = app.get_webview_window(CALL_WINDOW) { let _ = window.unminimize(); - window.show().map_err(|_| UNAVAILABLE.to_string())?; + window.show().map_err(|error| { + eprintln!("persephone-ui: cannot show the call window: {error}"); + UNAVAILABLE.to_string() + })?; let _ = window.set_focus(); return Ok(()); } From 982960c1b5e3a713a7f40ce0439e8045b987a169 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 21:57:10 +0000 Subject: [PATCH 36/51] Keep the camera and screen share notes in the short call bar The main window has no other place for them, so a camera that did not start or a running screen share was not seen while the call window was closed. The render test now checks that the bar stays short when a note shows, and ADR-0060 names each note the short bar keeps. Co-Authored-By: Claude Opus 5.5 --- .../adr/0060-show-calls-in-a-separate-call-window.md | 6 ++++-- frontend/src/CallBar.svelte | 12 ++++++------ frontend/tests/render.test.mjs | 12 ++++++++---- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/docs/adr/0060-show-calls-in-a-separate-call-window.md b/docs/adr/0060-show-calls-in-a-separate-call-window.md index 741215b5..db624c28 100644 --- a/docs/adr/0060-show-calls-in-a-separate-call-window.md +++ b/docs/adr/0060-show-calls-in-a-separate-call-window.md @@ -57,8 +57,10 @@ commands. call window opens, the main window's call bar shows only the phone icon, the room, the phase, the "Call window" button and, after a declined ring (ADR-0052), the "Declined" note, which the call window does not show. It - also shows the device change note, so a failed microphone or speaker is - seen while the call window is closed. When the call window cannot open for + also shows the camera, screen share and device change notes, so a camera + that did not start, a running or refused screen share and a failed + microphone or speaker are seen while the call window is closed. The + volume, the level meter and the participants show with the controls only. When the call window cannot open for the call, the call bar shows all of its controls and the main window shows the video tiles under it, so the call can still be muted or left. A later open that works makes the bar short again. An ended call still shows its diff --git a/frontend/src/CallBar.svelte b/frontend/src/CallBar.svelte index 6e1c561d..fb1baf3d 100644 --- a/frontend/src/CallBar.svelte +++ b/frontend/src/CallBar.svelte @@ -37,10 +37,10 @@ // // The call window holds the call's controls (ADR-0060). While it can open, // the bar shows only the room, the phase, a "Call window" button, the - // "Declined" note, which the call window does not show, and the device - // change note, which must be seen while the call window is closed. When it - // could not open (`full`), the bar shows every control, so the call can - // still be muted or left here. + // "Declined" note, which the call window does not show, and the camera, + // screen share and device change notes, which must be seen while the call + // window is closed. When it could not open (`full`), the bar shows every + // control, so the call can still be muted or left here. let { status, dismissed, @@ -201,10 +201,10 @@
{/if} - {#if !ended && full && cameraText !== ''} + {#if !ended && cameraText !== ''}

{cameraText}

{/if} - {#if !ended && full && screenText !== ''} + {#if !ended && screenText !== ''}

{screenText}

{/if} {#if !ended && status.deviceChange} diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs index d6f6960d..a694f6ee 100644 --- a/frontend/tests/render.test.mjs +++ b/frontend/tests/render.test.mjs @@ -259,13 +259,17 @@ test('GIVEN a call window that opens WHEN the call bar renders THEN it shows the assert.match(short, />In callDeclined]*>The chosen camera is not connected]*>You are sharing your screen Date: Wed, 25 Nov 2026 21:58:09 +0000 Subject: [PATCH 37/51] Record the failed call page gap in ADR-0060 The main window counts the call window as open when the host shows it, so a call page that fails to start leaves no mute or leave control. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0060-show-calls-in-a-separate-call-window.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/adr/0060-show-calls-in-a-separate-call-window.md b/docs/adr/0060-show-calls-in-a-separate-call-window.md index db624c28..f1c3b83d 100644 --- a/docs/adr/0060-show-calls-in-a-separate-call-window.md +++ b/docs/adr/0060-show-calls-in-a-separate-call-window.md @@ -110,3 +110,9 @@ commands. * A second web view uses more memory during a call. * Names and the chosen theme are not shown in the call window. * The page code for the grid repeats some of `CallVideo.svelte`. +* Known limitation (25 November 2026): the main window counts the call + window as open when the host shows it, not when its page works. If the + call page fails to start after the window shows, neither window offers + mute or leave for that call. A ready signal from the call page, or a + Leave button in the short bar, would close this gap; the owner has not + chosen one yet. From 33b78778a3108452a3d6e41566ae42f6548c0d1d Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 21:58:56 +0000 Subject: [PATCH 38/51] Address the fourth call window review: stats off, bounds, device label - The worker drops a statistics reading that waits in the output slot when the core turns the statistics off, so none is written after the off. A reading the writer already took can still follow; the core drops readings while off, and the FromWorker::Stats doc says so. - The core protocol bounds the statistics participants by the contract's CALL_PARTICIPANTS_MAX, not the level-list constant. - The compile-time drift check also ties CALL_SOUND_LEVEL_MAX to the worker protocol's MAX_SOUND_LEVEL. - Each remote device's statistics section carries its device ID, and the caption shows it as escaped text, so one person's two devices differ. - The IPC statistics test's wait asserts at its deadline and names the switches it saw. Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/src/lib.rs | 4 +++- crates/call-worker/src/output.rs | 37 ++++++++++++++++++++++++++++++ crates/call-worker/src/session.rs | 6 +++++ crates/core-protocol/src/lib.rs | 12 ++++++---- crates/core/src/calls/stats.rs | 1 + frontend/src/CallStats.svelte | 3 ++- frontend/src/callStats.ts | 15 ++++++++---- frontend/src/style.css | 5 ++++ frontend/tests/call-stats.test.mjs | 28 +++++++++++++++++++++- src-tauri/tests/ipc.rs | 14 +++++++---- 10 files changed, 110 insertions(+), 15 deletions(-) diff --git a/crates/call-protocol/src/lib.rs b/crates/call-protocol/src/lib.rs index 3c405814..d82c4614 100644 --- a/crates/call-protocol/src/lib.rs +++ b/crates/call-protocol/src/lib.rs @@ -749,7 +749,9 @@ pub enum FromWorker { message: String, }, /// The call's statistics, as numbers with units (ADR-0066). Sent at - /// most once a second, and only while [`ToWorker::SetStats`] is on. + /// most once a second, and only while [`ToWorker::SetStats`] is on. The + /// off drops a reading that waits; one that the worker was already + /// writing can still follow the off, and the core drops it. Stats(CallStats), } diff --git a/crates/call-worker/src/output.rs b/crates/call-worker/src/output.rs index 535ef96e..f674427f 100644 --- a/crates/call-worker/src/output.rs +++ b/crates/call-worker/src/output.rs @@ -250,6 +250,13 @@ impl Output { let _ = self.queue.try_send(Item::Wake); } + /// Drops the statistics reading that waits, when the core turns the + /// statistics off (ADR-0066). A reading that the writer took before + /// this call can still go out; the core drops a reading while off. + pub fn clear_stats(&self) { + drop(self.slots.take_stats()); + } + /// Drops the picture that waits for a tile. Call it after the tile's /// producer has stopped and before `VideoStopped`. pub fn clear_picture(&self, tile: u8) { @@ -659,6 +666,36 @@ mod tests { ); } + /// GIVEN a reading that waits WHEN the statistics go off before the + /// writer runs THEN the reading is not written, and a reading offered + /// after that goes out. + #[test] + fn given_a_waiting_reading_when_stats_go_off_then_it_is_not_written() { + let (output, receiver) = Output::new(); + output.offer_stats(stats_with_level(3)); + output.clear_stats(); + output + .queue + .try_send(output.slots.queued(FromWorker::Left)) + .unwrap(); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + assert_eq!(read_all(wire), vec![WorkerItem::Message(FromWorker::Left)]); + + let (output, receiver) = Output::new(); + output.offer_stats(stats_with_level(3)); + output.clear_stats(); + output.offer_stats(stats_with_level(4)); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + assert_eq!( + read_all(wire), + vec![WorkerItem::Message(FromWorker::Stats(stats_with_level(4)))] + ); + } + /// GIVEN a full control queue WHEN a reading is offered THEN the offer /// does not block and takes no place in the queue, and the reading goes /// out after the queue drains. diff --git a/crates/call-worker/src/session.rs b/crates/call-worker/src/session.rs index 1f9498b4..6dfcc438 100644 --- a/crates/call-worker/src/session.rs +++ b/crates/call-worker/src/session.rs @@ -3275,10 +3275,16 @@ async fn event_loop( return End::Left; } Some(Input::Message(message)) => { + // The off also drops a reading that waits in the output + // slot, so none is written after the off (ADR-0066). + let stats_off = matches!(message, ToWorker::SetStats { on: false }); match call.handle_command(message).await { Ok(reply) => outgoing.extend(reply), Err(code) => return End::Failed(code), } + if stats_off { + output.clear_stats(); + } } Some(Input::Bad) => return End::Failed(FailureCode::Protocol), }, diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index a3ebe190..bc32c7e9 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -1221,7 +1221,10 @@ impl<'de> serde::de::Visitor<'de> for WireStats { Field::Camera => camera.replace(map.next_value()?).is_none(), Field::Screen => screen.replace(map.next_value()?).is_none(), Field::Participants => participants - .replace(map.next_value::>()?) + .replace(map.next_value::>()?) .is_none(), Field::Connections => connections .replace(map.next_value:: CallStatsLimit { diff --git a/frontend/src/CallStats.svelte b/frontend/src/CallStats.svelte index 6a2833bb..5acf1fd4 100644 --- a/frontend/src/CallStats.svelte +++ b/frontend/src/CallStats.svelte @@ -53,7 +53,8 @@ {#each sections as section (section.key)}
{#each section.rows as row (row.label)} diff --git a/frontend/src/callStats.ts b/frontend/src/callStats.ts index 1637de42..bd5ef319 100644 --- a/frontend/src/callStats.ts +++ b/frontend/src/callStats.ts @@ -236,11 +236,16 @@ export interface StatsRow { value: string; } -/** The numbers of one source. A device shows its user ID through `userId`; the other sources have a title. */ +/** + * The numbers of one source. A device shows its user ID through `userId` and + * its device ID as inert text, so one person's two devices can be told apart; + * the other sources have a title. + */ export interface StatsSection { key: string; title: string; userId: string | null; + deviceId: string | null; rows: StatsRow[]; } @@ -300,19 +305,20 @@ function receivedRows(entry: CallStatsParticipant): StatsRow[] { export function statsSections(stats: CallStats): StatsSection[] { const sections: StatsSection[] = []; if (stats.microphone) { - sections.push({ key: 'microphone', title: 'Your microphone', userId: null, rows: audioSentRows(stats.microphone) }); + sections.push({ key: 'microphone', title: 'Your microphone', userId: null, deviceId: null, rows: audioSentRows(stats.microphone) }); } if (stats.camera) { - sections.push({ key: 'camera', title: 'Your camera', userId: null, rows: videoSentRows(stats.camera) }); + sections.push({ key: 'camera', title: 'Your camera', userId: null, deviceId: null, rows: videoSentRows(stats.camera) }); } if (stats.screen) { - sections.push({ key: 'screen', title: 'Your screen share', userId: null, rows: videoSentRows(stats.screen) }); + sections.push({ key: 'screen', title: 'Your screen share', userId: null, deviceId: null, rows: videoSentRows(stats.screen) }); } for (const entry of stats.participants) { sections.push({ key: JSON.stringify(['device', entry.userId, entry.deviceId]), title: '', userId: entry.userId, + deviceId: entry.deviceId, rows: receivedRows(entry) }); } @@ -321,6 +327,7 @@ export function statsSections(stats: CallStats): StatsSection[] { key: `connection ${link.connection}`, title: connectionName(link.connection), userId: null, + deviceId: null, rows: [ { label: 'Available upload bandwidth', value: kbps(link.outgoingKbps) }, { label: 'Total send rate', value: kbps(link.sendKbps) }, diff --git a/frontend/src/style.css b/frontend/src/style.css index 50a87731..109e2fda 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -4092,6 +4092,11 @@ mark { overflow-wrap: anywhere; } +.call-stats-device { + color: var(--ink3); + font-weight: 400; +} + .call-stats-table th, .call-stats-table td { padding: 3px 0; diff --git a/frontend/tests/call-stats.test.mjs b/frontend/tests/call-stats.test.mjs index f5637dec..8ef3e6e8 100644 --- a/frontend/tests/call-stats.test.mjs +++ b/frontend/tests/call-stats.test.mjs @@ -71,9 +71,35 @@ test('GIVEN a reading WHEN the sections are made THEN own sources come first, th assert.equal(rows(3)['Video receive bitrate'], UNKNOWN_VALUE); assert.equal(rows(4)['Available upload bandwidth'], '2,500 kbit/s'); assert.equal(rows(4)['Total receive rate'], UNKNOWN_VALUE); - // A device is shown by its user ID component, never as title text. + // A device is shown by its user ID component and its device ID, never as title text. assert.equal(sections[3].title, ''); assert.equal(sections[3].userId, '@bob:s'); + assert.equal(sections[3].deviceId, 'B'); + assert.deepEqual( + sections.filter((section) => section.userId === null).map((section) => section.deviceId), + [null, null, null, null] + ); +}); + +test('GIVEN one person in the call from two devices WHEN the sections are made THEN each section names its own device', () => { + const sections = statsSections( + reading({ + microphone: null, + camera: null, + participants: [ + { userId: '@bob:s', deviceId: 'PHONE', audio: null, video: null }, + { userId: '@bob:s', deviceId: 'DESK', audio: null, video: null } + ], + connections: [] + }) + ); + assert.deepEqual( + sections.map((section) => [section.userId, section.deviceId]), + [ + ['@bob:s', 'PHONE'], + ['@bob:s', 'DESK'] + ] + ); }); test('GIVEN no camera, no screen and a device without media WHEN the sections are made THEN only what exists shows, and the device says so', () => { diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index 49c54400..59ad1153 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -1325,12 +1325,18 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ }; // A stop of the host goes on a task of its own, so wait for it, but not // forever: the mock runtime sends no page or window events, so nothing - // else would end the wait. + // else would end the wait. A switch that never comes fails here, by name. let wait_for = |count: usize| { let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while core.stats_switches.lock().unwrap().len() < count - && std::time::Instant::now() < deadline - { + loop { + let seen = core.stats_switches.lock().unwrap().clone(); + if seen.len() >= count { + break; + } + assert!( + std::time::Instant::now() < deadline, + "waited 10 s for {count} statistics switches, saw {seen:?}" + ); std::thread::sleep(std::time::Duration::from_millis(10)); } }; From 1d9bb4cc6378378843de3f4395ab3afd20128af6 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 22:26:06 +0000 Subject: [PATCH 39/51] Address the fifth call window review: strict readers, one reading in flight - Read the call_stats event content and every nested statistics record as JSON objects only, so a positional array is refused. - Read a newer statistics switch before a retry sends a kept one. - Say "Saved" after a device change, not "Switched". - Show an empty state for a reading with no measurements, and say that statistics are missing, not that there is no media. - Send the call window one statistics reading at a time; only the newest waits until the page calls call_stats_read. - Count every delivery in the rejected-reading tests. Co-Authored-By: Claude Opus 5.5 --- crates/core-protocol/src/lib.rs | 181 ++++++++++++++++-- crates/core/src/calls/controller.rs | 32 +++- ...o-and-change-devices-in-the-call-window.md | 6 +- .../0066-show-call-statistics-on-request.md | 4 +- frontend/AGENTS.md | 2 +- frontend/src/CallStats.svelte | 7 +- frontend/src/bridge/index.ts | 26 ++- frontend/src/callStats.ts | 13 +- frontend/src/calls.ts | 12 +- frontend/tests/bridge-calls.test.mjs | 31 ++- frontend/tests/call-device-panel.test.mjs | 4 +- frontend/tests/call-stats.test.mjs | 13 +- frontend/tests/call-view.test.mjs | 5 +- src-tauri/AGENTS.md | 2 +- src-tauri/build.rs | 1 + src-tauri/capabilities/call.json | 1 + .../autogenerated/call_stats_read.toml | 11 ++ src-tauri/src/lib.rs | 72 ++++++- src-tauri/tests/ipc.rs | 94 +++++++-- 19 files changed, 452 insertions(+), 65 deletions(-) create mode 100644 src-tauri/permissions/autogenerated/call_stats_read.toml diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index bc32c7e9..75b43703 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -1128,8 +1128,8 @@ pub enum Event { /// [`Call::CallStats`] is on: numbers with units, and the validated IDs /// of the devices. Coalesced: only the newest waits. A reading that is /// out of bounds is refused whole. + #[serde(deserialize_with = "call_stats_content")] CallStats { - #[serde(deserialize_with = "bounded_stats")] stats: persephone_contracts::CallStats, }, /// A device test started, changed or ended (ADR-0059): ask for @@ -1176,6 +1176,84 @@ pub fn levels_within_limits(levels: &[persephone_contracts::CallParticipantLevel }) } +/// Reads the content of [`Event::CallStats`]. Only a JSON object with the one +/// key `stats` is read: the derived reader would also take a positional +/// array. A repeated or unknown key is an error. +fn call_stats_content<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + struct Content; + impl<'de> serde::de::Visitor<'de> for Content { + type Value = persephone_contracts::CallStats; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("an object with the key `stats`") + } + + fn visit_map>( + self, + mut map: A, + ) -> Result { + use serde::de::Error; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + enum Field { + Stats, + } + let mut stats = None; + while let Some(Field::Stats) = map.next_key::()? { + if stats.replace(map.next_value::()?).is_some() { + return Err(A::Error::duplicate_field("stats")); + } + } + stats + .map(|stats| stats.0) + .ok_or_else(|| A::Error::missing_field("stats")) + } + } + deserializer.deserialize_map(Content) +} + +/// A statistics reading, read by [`bounded_stats`]. +struct WireStatsValue(persephone_contracts::CallStats); + +impl<'de> Deserialize<'de> for WireStatsValue { + fn deserialize>(deserializer: D) -> Result { + bounded_stats(deserializer).map(WireStatsValue) + } +} + +/// Wraps a deserializer so that a struct reads only from a JSON object. A +/// derived struct reader also takes a positional array, which is not the +/// contract. +struct MapOnlyDeserializer(D); + +impl<'de, D: serde::Deserializer<'de>> serde::Deserializer<'de> for MapOnlyDeserializer { + type Error = D::Error; + + fn deserialize_any>( + self, + visitor: V, + ) -> Result { + self.0.deserialize_map(visitor) + } + + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +/// A value read through [`MapOnlyDeserializer`]. +struct MapOnly(T); + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for MapOnly { + fn deserialize>(deserializer: D) -> Result { + T::deserialize(MapOnlyDeserializer(deserializer)).map(MapOnly) + } +} + /// Reads a statistics reading. Only a JSON object is read, each list stops /// at its limit before it builds one more entry, and each ID is bounded /// before it is copied. `CallStats::within_limits` then checks the numbers @@ -1217,9 +1295,21 @@ impl<'de> serde::de::Visitor<'de> for WireStats { let (mut participants, mut connections) = (None, None); while let Some(field) = map.next_key::()? { let fresh = match field { - Field::Microphone => microphone.replace(map.next_value()?).is_none(), - Field::Camera => camera.replace(map.next_value()?).is_none(), - Field::Screen => screen.replace(map.next_value()?).is_none(), + Field::Microphone => microphone + .replace( + map.next_value::>>()?, + ) + .is_none(), + Field::Camera => camera + .replace( + map.next_value::>>()?, + ) + .is_none(), + Field::Screen => screen + .replace( + map.next_value::>>()?, + ) + .is_none(), Field::Participants => participants .replace(map.next_value:: serde::de::Visitor<'de> for WireStats { .is_none(), Field::Connections => connections .replace(map.next_value::, { persephone_contracts::CALL_STATS_CONNECTIONS_MAX }, >>()?) .is_none(), @@ -1239,22 +1329,31 @@ impl<'de> serde::de::Visitor<'de> for WireStats { } let participants = participants.ok_or_else(|| A::Error::missing_field("participants"))?; Ok(persephone_contracts::CallStats { - microphone: microphone.ok_or_else(|| A::Error::missing_field("microphone"))?, - camera: camera.ok_or_else(|| A::Error::missing_field("camera"))?, - screen: screen.ok_or_else(|| A::Error::missing_field("screen"))?, + microphone: microphone + .ok_or_else(|| A::Error::missing_field("microphone"))? + .map(|audio| audio.0), + camera: camera + .ok_or_else(|| A::Error::missing_field("camera"))? + .map(|video| video.0), + screen: screen + .ok_or_else(|| A::Error::missing_field("screen"))? + .map(|video| video.0), participants: participants .0 .into_iter() .map(|participant| persephone_contracts::CallStatsParticipant { user_id: participant.user_id.0, device_id: participant.device_id.0, - audio: participant.audio, - video: participant.video, + audio: participant.audio.map(|audio| audio.0), + video: participant.video.map(|video| video.0), }) .collect(), connections: connections .ok_or_else(|| A::Error::missing_field("connections"))? - .0, + .0 + .into_iter() + .map(|connection| connection.0) + .collect(), }) } } @@ -1264,8 +1363,8 @@ impl<'de> serde::de::Visitor<'de> for WireStats { struct WireParticipant { user_id: BoundedText, device_id: BoundedText, - audio: Option, - video: Option, + audio: Option>, + video: Option>, } impl<'de> Deserialize<'de> for WireParticipant { @@ -4437,7 +4536,15 @@ mod timeline_events_wire_tests { .push(serde_json::json!({"anything": [1, 2, 3]})); let error = event(over).unwrap_err(); assert!(error.to_string().contains("over its limit"), "{error}"); - assert!(event(reading(0, full + 1)).is_err()); + // The entry past the limit cannot be a connection, so only the early + // limit can refuse it. + let mut too_many = reading(0, full); + too_many["connections"] + .as_array_mut() + .unwrap() + .push(serde_json::json!("x")); + let error = event(too_many).unwrap_err(); + assert!(error.to_string().contains("over its limit"), "{error}"); assert!(event(serde_json::json!([null, null, null, [], []])).is_err()); let mut positional = reading(0, 0); positional["participants"] = serde_json::json!([["@a:example.org", "D", null, null]]); @@ -4447,6 +4554,52 @@ mod timeline_events_wire_tests { assert!(serde_json::from_str::(twice).is_err()); } + /// GIVEN statistics events on the byte path WHEN the content or a part is + /// positional THEN it is refused, and an object with null parts is kept. + #[test] + fn given_call_stats_bytes_with_positional_parts_then_they_are_refused() { + let read = |json: &str| serde_json::from_slice::(json.as_bytes()); + let content = |stats: &str| format!(r#"{{"event":{{"call_stats":{stats}}}}}"#); + let reading = |microphone: &str, participants: &str, connections: &str| { + format!( + r#"{{"microphone":{microphone},"camera":null,"screen":null,"participants":{participants},"connections":{connections}}}"# + ) + }; + let valid = reading("null", "[]", "[]"); + assert!(read(&content(&format!(r#"{{"stats":{valid}}}"#))).is_ok()); + // The content is an object with the key `stats`, and no other key. + assert!(read(&content(&format!("[{valid}]"))).is_err()); + assert!(read(&content("{}")).is_err()); + assert!(read(&content(&format!(r#"{{"stats":{valid},"stats":{valid}}}"#))).is_err()); + assert!(read(&content(&format!(r#"{{"stats":{valid},"extra":1}}"#))).is_err()); + // Each nested record is an object too. + let with = |microphone: &str, participants: &str, connections: &str| { + content(&format!( + r#"{{"stats":{}}}"#, + reading(microphone, participants, connections) + )) + }; + assert!(read(&with("[1,null,null,null]", "[]", "[]")).is_err()); + assert!(read(&with("null", "[]", "[[0,null,null,null,null]]")).is_err()); + assert!( + read(&with( + "null", + r#"[{"userId":"@a:example.org","deviceId":"D","audio":[1,null,null,null,null],"video":null}]"#, + "[]" + )) + .is_err() + ); + // GIVEN objects with null parts THEN they are kept. + assert!( + read(&with( + r#"{"level":1,"bitrateKbps":null,"packetsSent":0,"packetsLost":null,"jitterMs":null,"rttMs":null}"#, + r#"[{"userId":"@a:example.org","deviceId":"D","audio":null,"video":null}]"#, + r#"[{"connection":0,"outgoingKbps":null,"sendKbps":null,"receiveKbps":null,"rttMs":null}]"# + )) + .is_ok() + ); + } + /// GIVEN call level events WHEN read THEN bounded ones are kept, and a /// level over the top, too many devices or an overlong ID is refused. #[test] diff --git a/crates/core/src/calls/controller.rs b/crates/core/src/calls/controller.rs index f1e2893e..cb822fe4 100644 --- a/crates/core/src/calls/controller.rs +++ b/crates/core/src/calls/controller.rs @@ -2962,6 +2962,14 @@ fn take_newer_choice( } } +/// Replaces a kept statistics switch with a newer one that waits unread in +/// `switch`, so a retry never sends an older value. +fn take_newer_switch(switch: &mut watch::Receiver, pending: &mut Option<(Instant, bool)>) { + if switch.has_changed().unwrap_or(false) { + *pending = Some((Instant::now(), *switch.borrow_and_update())); + } +} + /// Gives the call a microphone and speaker choice. The same choice as the /// last one changes nothing, so saving only the camera does not restart the /// sound of a running call; with `again` (the last change failed) it is @@ -4265,7 +4273,13 @@ impl Call { Some(at) => time::sleep_until(at.into()).await, None => std::future::pending().await, } - } => self.apply_stats(&mut pending_stats, &mut stats_sent)?, + } => { + // `select!` picks a ready arm at random: a newer switch + // that waits unread replaces the kept one first, so the + // worker never gets an older value. + take_newer_switch(&mut stats_switch, &mut pending_stats); + self.apply_stats(&mut pending_stats, &mut stats_sent)?; + } remote = portal_done(&mut self.portal) => self.portal_finished(inner, remote)?, (picked, cancelled) = screen_pick_done(&mut self.screen_pick) => { if cancelled { @@ -6571,6 +6585,22 @@ mod tests { assert!(!devices.has_changed().unwrap(), "the newer choice is read"); } + /// GIVEN a statistics switch kept for a retry and a newer value not read + /// yet WHEN the retry is due THEN the newer value replaces the kept one; + /// with no newer value the kept one stays. + #[test] + fn given_the_statistics_switch_with_a_newer_value_then_a_retry_sends_the_newer() { + let sender = watch::channel(false).0; + let mut switch = sender.subscribe(); + let mut pending = Some((Instant::now(), true)); + take_newer_switch(&mut switch, &mut pending); + assert_eq!(pending.map(|(_, on)| on), Some(true), "nothing newer"); + sender.send_replace(false); + take_newer_switch(&mut switch, &mut pending); + assert_eq!(pending.map(|(_, on)| on), Some(false), "the newer wins"); + assert!(!switch.has_changed().unwrap(), "the newer value is read"); + } + /// GIVEN two members with a sound level WHEN one leaves the call THEN /// its level goes from the meters at once, and the member that stays /// keeps its level; a prune with no change sends nothing. diff --git a/docs/adr/0065-choose-the-large-video-and-change-devices-in-the-call-window.md b/docs/adr/0065-choose-the-large-video-and-change-devices-in-the-call-window.md index 01126c00..ce9eac57 100644 --- a/docs/adr/0065-choose-the-large-video-and-change-devices-in-the-call-window.md +++ b/docs/adr/0065-choose-the-large-video-and-change-devices-in-the-call-window.md @@ -82,14 +82,16 @@ already has. * The capability `call` gets two more commands: `call_devices` and `set_call_devices`. It still has no device tests, no call start, no rooms and no files. The host test of the call window's command set checks this. -* The panel shows what happened: switched; the chosen device is not connected +* The panel shows what happened: saved; the chosen device is not connected (`not_found`); the microphone could not be opened and the old one is kept (`kept`); this system cannot switch during a call (`unsupported`, Linux today); or the sound may have stopped and a lost speaker needs a rejoin (`failed`). A call that ends because of its audio device shows its end reason as before (`AudioDevice`). * The call status has no mark for a change that worked. The panel therefore - says "switched" when it saved the choice and the status shows no failure. + says only "saved" when it saved the choice and the status shows no + failure, and adds that a failure shows on the same line. It cannot tell + "worked" from "not answered yet", so it never says "switched". A failure that the status shows is shown whether or not the panel saved anything, so a failure from before the panel opened (or from the main window's settings) is in view when the panel opens to fix it. diff --git a/docs/adr/0066-show-call-statistics-on-request.md b/docs/adr/0066-show-call-statistics-on-request.md index 8945d2a0..f221b428 100644 --- a/docs/adr/0066-show-call-statistics-on-request.md +++ b/docs/adr/0066-show-call-statistics-on-request.md @@ -138,7 +138,9 @@ candidate type, SSRC, codec or other text. is dropped. * The core keeps only the newest reading and sends it as `Event::CallStats`. The UI host reads the event with the same limits and sends it only to the - channel of a window that turned the details on. + channel of a window that turned the details on. The UI host sends each + page one reading at a time: the next waits until the page says, with + `call_stats_read`, that it handled the last one, and only the newest waits. * The UI host keeps a window's channel only after the core accepted the start. Its own stop on a reload or close is a request too, so the host lets one change of the core's switch run at a time, and each ends with the diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md index 7c2cc386..853e9772 100644 --- a/frontend/AGENTS.md +++ b/frontend/AGENTS.md @@ -4,7 +4,7 @@ This area inherits `../AGENTS.md`. - Build a locally bundled Svelte UI. Keep `vite.config.js` output in `../.local/build/frontend`, relative asset URLs, no inline assets, and no production source maps unless a reviewed requirement changes them. - There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. That includes `call_devices` and `set_call_devices` (ADR-0065) for `CallWindowDevices.svelte`, but no device tests. Its load and save order (saves one at a time, none dropped, the newest sets the result) is in `src/callDevicePanel.ts`, which takes the bridge calls as arguments. The choice of the large video is pure logic in `src/callView.ts`: a pick of the viewer wins, a shared screen is large only when nothing is picked, and a feed that goes away drops its pick. Scale pictures with CSS only; never ask the core for a larger one. -- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs as escaped text. The details and the device panel are open one at a time (`openDevices`, `openStats`). +- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. After each reading, handled or dropped, the bridge calls `call_stats_read` with the page count, so the host sends the next (it holds one in flight per page). The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs as escaped text. The details and the device panel are open one at a time (`openDevices`, `openStats`). - Put all Tauri API access in `src/bridge/index.ts` or another module under `src/bridge/`. Components use the typed bridge. Do not call `invoke`, Tauri globals, or host APIs directly from components. - Import public DTOs from `../crates/contracts/generated/contracts.ts`. Change Rust definitions and run the exporter when the DTO contract changes. TypeScript types do not validate runtime input or authorize commands. - Render names and message bodies as escaped text. Preserve bidirectional isolation in `src/Message.svelte`, `src/RoomList.svelte`, and `src/Timeline.svelte`. Do not use `{@html}`, HTML insertion APIs, automatic previews, or arbitrary remote images. diff --git a/frontend/src/CallStats.svelte b/frontend/src/CallStats.svelte index 5acf1fd4..342f1e88 100644 --- a/frontend/src/CallStats.svelte +++ b/frontend/src/CallStats.svelte @@ -2,7 +2,7 @@ import { onDestroy, onMount } from 'svelte'; import type { CallStats } from '../../crates/contracts/generated/contracts'; import { startCallStats, stopCallStats } from './bridge'; - import { STATS_FAILED_TEXT, STATS_LABEL, STATS_WAITING_TEXT, statsSections } from './callStats'; + import { STATS_FAILED_TEXT, STATS_LABEL, statsNote, statsSections } from './callStats'; import Icon from './Icon.svelte'; import PersonName from './PersonName.svelte'; @@ -30,6 +30,7 @@ }); const sections = $derived(stats ? statsSections(stats) : []); + const note = $derived(statsNote(stats, sections)); {#if failed} - {:else if stats === null} -

{STATS_WAITING_TEXT}

+ {:else if note !== null} +

{note}

{:else} {#each sections as section (section.key)}
- {#if section.userId !== null}{:else}{section.title}{/if} + {#if section.userId !== null}{#if section.deviceId !== null} + ({section.deviceId}){/if}{:else}{section.title}{/if}
diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts index 8b00bdab..637d805c 100644 --- a/frontend/src/bridge/index.ts +++ b/frontend/src/bridge/index.ts @@ -555,12 +555,20 @@ export function callCamera(on: boolean): Promise { * second. Only the call window may call it, after {@link watchSession}: the * request carries the page's count, and with none it fails with * `core_unavailable` and asks nothing. A reading that does not match the - * contract is dropped whole. Turn them off with {@link stopCallStats}. + * contract is dropped whole. The host sends one reading at a time: after + * each one, handled or dropped, the bridge tells the host with + * `call_stats_read`, and only then comes the next. Turn them off with + * {@link stopCallStats}. */ export async function startCallStats(onStats: (stats: CallStats) => void): Promise { + const page = statsPage; const channel = new Channel((value) => { - const stats = parseCallStats(value); - if (stats !== null) onStats(stats); + try { + const stats = parseCallStats(value); + if (stats !== null) onStats(stats); + } finally { + statsHandled(page); + } }); await inStatsTurn(() => statsPage === null @@ -582,6 +590,18 @@ export async function stopCallStats(): Promise { ); } +// Tells the host that the page handled a statistics reading, so it sends the +// next. Nothing waits for the answer: a reload makes the count stale, and the +// host refuses it, which is expected. +function statsHandled(page: number | null): void { + if (page === null) return; + try { + invoke('call_stats_read', { page }).catch(() => undefined); + } catch { + // The bridge is gone with the page. + } +} + // The page's count from `watch_session` (ADR-0066). The host takes a // statistics request only with the count of the page its window shows now, // so a request that reaches it after a reload or close changes nothing. diff --git a/frontend/src/callStats.ts b/frontend/src/callStats.ts index bd5ef319..915c8f8f 100644 --- a/frontend/src/callStats.ts +++ b/frontend/src/callStats.ts @@ -293,7 +293,7 @@ function videoReceivedRows(video: CallStatsVideoReceived): StatsRow[] { function receivedRows(entry: CallStatsParticipant): StatsRow[] { const rows = [...(entry.audio ? audioReceivedRows(entry.audio) : []), ...(entry.video ? videoReceivedRows(entry.video) : [])]; - return rows.length > 0 ? rows : [{ label: 'Receiving', value: 'No audio or video' }]; + return rows.length > 0 ? rows : [{ label: 'Receiving', value: 'No audio or video statistics available' }]; } /** @@ -341,6 +341,17 @@ export function statsSections(stats: CallStats): StatsSection[] { /** Said while no reading has arrived. */ export const STATS_WAITING_TEXT = 'Waiting for the first reading.'; +/** Said when a reading has arrived but holds no measurements. */ +export const STATS_EMPTY_TEXT = 'No statistics available yet'; +/** + * The note that stands in for the tables: the waiting text before the first + * reading, the empty text for a reading with no sections, and nothing when + * there is something to show. + */ +export function statsNote(stats: CallStats | null, sections: readonly StatsSection[]): string | null { + if (stats === null) return STATS_WAITING_TEXT; + return sections.length === 0 ? STATS_EMPTY_TEXT : null; +} /** Said when the details cannot be turned on. */ export const STATS_FAILED_TEXT = 'The technical details could not be started.'; /** The button that opens the panel, and the panel's name. */ diff --git a/frontend/src/calls.ts b/frontend/src/calls.ts index 3c53224b..b2a6530a 100644 --- a/frontend/src/calls.ts +++ b/frontend/src/calls.ts @@ -761,8 +761,9 @@ export const DEVICE_SAVE_FAILURE_TEXT = 'The call devices could not be saved.'; /** * What the device panel of the call window says about a change during a * call (ADR-0065). A failure is the call status's `deviceChange` (ADR-0059). - * The status has no mark for a change that worked, so `null` after a save - * reads as switched. A speaker that is lost needs a rejoin (`failed`). + * The status has no mark for a change that worked, so `null` cannot tell + * "worked" from "not answered yet". After a save the panel says only that + * the choice is saved, and a failure shows when the worker answers. A speaker that is lost needs a rejoin (`failed`). */ export const DEVICE_SWITCH_TEXT: Record = { not_found: 'The chosen microphone or speaker is not connected. The call keeps the one it had.', @@ -770,7 +771,8 @@ export const DEVICE_SWITCH_TEXT: Record = { kept: 'The chosen microphone could not be opened. The call keeps the one it had.', failed: 'The microphone or speaker could not be changed, and the sound may have stopped. A lost speaker needs a rejoin: leave the call and join it again.' }; -export const DEVICE_SWITCHED_TEXT = 'Switched. A camera change applies the next time you turn the camera on.'; +export const DEVICE_SAVED_TEXT = + 'Saved. If the call cannot use it, this line tells you. A camera change applies the next time you turn the camera on.'; export const DEVICE_SWITCHING_TEXT = 'Switching…'; export const DEVICES_BUTTON_LABEL = 'Device settings'; export const DEVICES_PANEL_LABEL = 'Call devices'; @@ -778,12 +780,12 @@ export const DEVICES_PANEL_LABEL = 'Call devices'; /** * The line under the device menus: "switching" while a save runs, the * failure the call status shows (also one from before the panel opened, or - * from the main window's settings), "switched" after a save, else nothing. + * from the main window's settings), "saved" after a save, else nothing. */ export function deviceSwitchText(saved: boolean, saving: boolean, change: CallDeviceChange | null): string { if (saving) return DEVICE_SWITCHING_TEXT; if (change !== null) return DEVICE_SWITCH_TEXT[change]; - return saved ? DEVICE_SWITCHED_TEXT : ''; + return saved ? DEVICE_SAVED_TEXT : ''; } /** The call window's view buttons (ADR-0065). */ diff --git a/frontend/tests/bridge-calls.test.mjs b/frontend/tests/bridge-calls.test.mjs index 751890cb..92da9768 100644 --- a/frontend/tests/bridge-calls.test.mjs +++ b/frontend/tests/bridge-calls.test.mjs @@ -23,7 +23,7 @@ before(async () => { // arguments the page sends, without Tauri's own State, Window and Channel. const host = await readFile(new URL('../../src-tauri/src/lib.rs', import.meta.url), 'utf8'); hostArguments = new Map(); - for (const [, name, parameters] of host.matchAll(/async fn ([a-z_]+)(?:<[^>]*>)?\(([^)]*)\)/g)) { + for (const [, name, parameters] of host.matchAll(/(?:async )?fn ([a-z_]+)(?:<[^>]*>)?\(([^)]*)\)/g)) { const names = [...parameters.matchAll(/([a-z_]+):\s*([A-Za-z]+)/g)] .filter(([, , type]) => !['State', 'Window', 'Webview', 'WebviewWindow', 'AppHandle'].includes(type)) .map(([, parameter]) => camel(parameter)); @@ -530,10 +530,17 @@ test('GIVEN the technical details WHEN turned on and off THEN the host is asked calls[0].args.onStats.onmessage(value); } assert.deepEqual(seen, [reading]); + // Each message, handled or dropped, tells the host to send the next. + const reads = calls.filter((call) => call.command === 'call_stats_read'); + assert.equal(reads.length, 5); + assert.ok(reads.every((call) => call.args.page === 4 && Object.keys(call.args).length === 1)); + assert.ok(registered.has('call_stats_read')); + assert.deepEqual(hostArguments.get('call_stats_read'), ['page']); await bridge.stopCallStats(); - assert.equal(calls[1].command, 'call_stats'); - assert.equal(calls[1].args.on, false); - assert.equal(calls[1].args.page, 4); + const stop = calls[calls.length - 1]; + assert.equal(stop.command, 'call_stats'); + assert.equal(stop.args.on, false); + assert.equal(stop.args.page, 4); // The host registers the command with exactly these arguments. assert.ok(registered.has('call_stats')); assert.deepEqual(hostArguments.get('call_stats'), ['on', 'onStats', 'page']); @@ -541,6 +548,22 @@ test('GIVEN the technical details WHEN turned on and off THEN the host is asked await assert.rejects(bridge.startCallStats(() => {}), (reason) => reason === 'unavailable'); }); +test('GIVEN a stale page count WHEN the host refuses the read of a reading THEN the page goes on and the reading still reaches it', async () => { + await watchAs(8); + const channels = []; + mockIPC((command, args) => { + if (command === 'call_stats_read') return Promise.reject('invalid_argument'); + channels.push(args.onStats); + return null; + }); + const seen = []; + await bridge.startCallStats((stats) => seen.push(stats)); + const reading = { microphone: null, camera: null, screen: null, participants: [], connections: [] }; + channels[0].onmessage(reading); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(seen, [reading]); +}); + test('GIVEN no usable page count from the host WHEN the technical details are turned on THEN the start fails and asks nothing, and a stop asks nothing', async () => { for (const reply of [null, -1, 1.5, '3', Number.MAX_SAFE_INTEGER + 2]) { await watchAs(reply); diff --git a/frontend/tests/call-device-panel.test.mjs b/frontend/tests/call-device-panel.test.mjs index 68740043..966bf01b 100644 --- a/frontend/tests/call-device-panel.test.mjs +++ b/frontend/tests/call-device-panel.test.mjs @@ -62,7 +62,7 @@ test('GIVEN the core refuses WHEN the panel loads THEN it shows the failure and } }); -test('GIVEN a save WHEN the core accepts it THEN the panel says switched and sends the menus as choices', async () => { +test('GIVEN a save WHEN the core accepts it THEN the panel says saved and sends the menus as choices', async () => { const sent = []; const { panel: made, seen, last } = panel({ list: async () => DEVICES, @@ -74,7 +74,7 @@ test('GIVEN a save WHEN the core accepts it THEN the panel says switched and sen assert.deepEqual(last(), { devices: null, loading: false, saving: false, saved: true, failure: null }); }); -test('GIVEN a save WHEN the core refuses it THEN the panel shows the failure and does not say switched', async () => { +test('GIVEN a save WHEN the core refuses it THEN the panel shows the failure and does not say saved', async () => { for (const [reason, text] of [ ['invalid_argument', DEVICE_FAILURE_TEXT.invalid_argument], ['unknown', DEVICE_SAVE_FAILURE_TEXT] diff --git a/frontend/tests/call-stats.test.mjs b/frontend/tests/call-stats.test.mjs index 8ef3e6e8..e31c1e5c 100644 --- a/frontend/tests/call-stats.test.mjs +++ b/frontend/tests/call-stats.test.mjs @@ -10,6 +10,9 @@ import { parseCallStats, percent, resolution, + STATS_EMPTY_TEXT, + STATS_WAITING_TEXT, + statsNote, statsSections, UNKNOWN_VALUE } from '../src/callStats.ts'; @@ -110,7 +113,7 @@ test('GIVEN no camera, no screen and a device without media WHEN the sections ar sections.map((section) => section.key).filter((key) => key === 'camera' || key === 'screen'), [] ); - assert.deepEqual(sections[1].rows, [{ label: 'Receiving', value: 'No audio or video' }]); + assert.deepEqual(sections[1].rows, [{ label: 'Receiving', value: 'No audio or video statistics available' }]); }); test('GIVEN a reading inside the contract WHEN it is parsed THEN it is kept', () => { @@ -174,3 +177,11 @@ test('GIVEN a hostile user ID WHEN the sections are made THEN it is only text fo assert.equal(device.userId, hostile); assert.ok(device.rows.every((row) => !row.value.includes('<'))); }); + +test('GIVEN no reading, an empty reading and a reading with measurements WHEN the note is chosen THEN each gets its own text or none', () => { + const empty = { microphone: null, camera: null, screen: null, participants: [], connections: [] }; + assert.equal(statsNote(null, []), STATS_WAITING_TEXT); + assert.equal(statsNote(empty, statsSections(empty)), STATS_EMPTY_TEXT); + assert.equal(STATS_EMPTY_TEXT, 'No statistics available yet'); + assert.equal(statsNote(reading(), statsSections(reading())), null); +}); diff --git a/frontend/tests/call-view.test.mjs b/frontend/tests/call-view.test.mjs index b7ea3b01..af3e1bd3 100644 --- a/frontend/tests/call-view.test.mjs +++ b/frontend/tests/call-view.test.mjs @@ -12,7 +12,7 @@ import { } from '../src/callView.ts'; import { DEVICE_SWITCH_TEXT, - DEVICE_SWITCHED_TEXT, + DEVICE_SAVED_TEXT, DEVICE_SWITCHING_TEXT, deviceSwitchText, feedLabel, @@ -130,7 +130,8 @@ test('GIVEN no large feed WHEN the cells are split THEN all stay in order', () = test('GIVEN the device panel WHEN a change is read THEN each result has its own text', () => { assert.equal(deviceSwitchText(false, false, null), ''); assert.equal(deviceSwitchText(true, true, null), DEVICE_SWITCHING_TEXT); - assert.equal(deviceSwitchText(true, false, null), DEVICE_SWITCHED_TEXT); + assert.equal(deviceSwitchText(true, false, null), DEVICE_SAVED_TEXT); + assert.ok(!/switched/i.test(DEVICE_SAVED_TEXT), 'no claim before the worker answers'); for (const change of ['not_found', 'unsupported', 'kept', 'failed']) { assert.equal(deviceSwitchText(true, false, change), DEVICE_SWITCH_TEXT[change]); // A failure from before the panel opened shows too. diff --git a/src-tauri/AGENTS.md b/src-tauri/AGENTS.md index ade04047..a57f38fe 100644 --- a/src-tauri/AGENTS.md +++ b/src-tauri/AGENTS.md @@ -6,7 +6,7 @@ This area inherits `../AGENTS.md` and implements ADR-0004. - Keep launch and inherited-pipe ownership checks. Start the application through the core binary, `persephone`; `persephone-ui` requires its core channel. - When adding a command, update its Rust handler, `build.rs` registration, `capabilities/main.json`, the frontend bridge, core protocol/handler, and IPC tests together. Review the minimum permission required. - The call window (ADR-0060) is the `call` window with `call.html` and its own `capabilities/call.json`: call commands only, plus `call_devices` and `set_call_devices` (ADR-0065); the `ipc` test pins the list. Grant it nothing else without an ADR change. `Subscriptions` keeps each window's channels under its label; room channels belong to `main`. Both windows get capture protection through `CaptureState::set_window_applier`, and the call window goes when the main window goes. -- Call statistics (ADR-0066): the call window alone may call `call_stats { on, page, onStats }` (`allow-call-stats` in `capabilities/call.json`, not in `main.json`). `Subscriptions::stats` holds its channel only after the core accepted the start, and `reset_subscriptions` drops it and tells the core to stop when the window reloads or goes. Every change of the core's switch takes `Subscriptions::stats_order` and leaves it as the kept channels want; a start that a reload or close overtook (the window's page count changed) keeps no channel and turns the switch off again. The page load and `watch_session` (a page's first request) both count a page, and `watch_session` gives the page its count. `call_stats` carries it, and the host refuses a request with any other count, because Tauri may start a command's task after the reload or close. `dispatch` checks `CallStats::within_limits` again and sends only to channels in that map. +- Call statistics (ADR-0066): the call window alone may call `call_stats { on, page, onStats }` and `call_stats_read { page }` (`allow-call-stats` and `allow-call-stats-read` in `capabilities/call.json`, not in `main.json`). The host sends a page one reading at a time: `Subscriptions::stats` holds each channel with `unread` and the one newest `waiting` reading, and `call_stats_read` (never relayed to the core) sends the waiting one or frees the page. `Subscriptions::stats` holds its channel only after the core accepted the start, and `reset_subscriptions` drops it and tells the core to stop when the window reloads or goes. Every change of the core's switch takes `Subscriptions::stats_order` and leaves it as the kept channels want; a start that a reload or close overtook (the window's page count changed) keeps no channel and turns the switch off again. The page load and `watch_session` (a page's first request) both count a page, and `watch_session` gives the page its count. `call_stats` carries it, and the host refuses a request with any other count, because Tauri may start a command's task after the reload or close. `dispatch` checks `CallStats::within_limits` again and sends only to channels in that map. - `permissions/autogenerated/` and ignored `gen/` schemas come from `tauri-build`. Change command registration and rebuild rather than hand-editing generated permissions. - Preserve local-origin checks, invoke-key checks, the explicit command allowlist, restrictive CSP, disabled new windows, and blocked external navigation. Do not enable generic plugins, dynamic permissions, payload tracing, or broader dependency features without review. - Treat page arguments as untrusted. Check bounds before relaying, and keep validation at the core boundary too. Tauri handler checks cannot bound allocations made before the handler runs. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 9d18c631..b21d1fbf 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -61,6 +61,7 @@ fn main() { "call_camera", "call_screen", "call_stats", + "call_stats_read", "call_video_frame", "call_status", "call_rings", diff --git a/src-tauri/capabilities/call.json b/src-tauri/capabilities/call.json index 2b4244c6..c8080d71 100644 --- a/src-tauri/capabilities/call.json +++ b/src-tauri/capabilities/call.json @@ -15,6 +15,7 @@ "allow-call-devices", "allow-set-call-devices", "allow-call-stats", + "allow-call-stats-read", "allow-close-call-window" ] } diff --git a/src-tauri/permissions/autogenerated/call_stats_read.toml b/src-tauri/permissions/autogenerated/call_stats_read.toml new file mode 100644 index 00000000..3e21fcd9 --- /dev/null +++ b/src-tauri/permissions/autogenerated/call_stats_read.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-call-stats-read" +description = "Enables the call_stats_read command without any pre-configured scope." +commands.allow = ["call_stats_read"] + +[[permission]] +identifier = "deny-call-stats-read" +description = "Denies the call_stats_read command without any pre-configured scope." +commands.deny = ["call_stats_read"] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9f2f4723..8e1d1731 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -372,6 +372,18 @@ struct Toasts { waiting: Option<(String, String, bool)>, } +/// A page's statistics channel with its backlog. Tauri queues a channel +/// message over 8 KiB on the host until the web view fetches it, so a stalled +/// page would let readings pile up. The host sends one reading at a time: +/// only the newest waits, until the page says it handled the last one. +struct StatsChannel { + channel: Channel, + /// A reading went to the page and `call_stats_read` has not come yet. + unread: bool, + /// The newest reading that came while `unread`. + waiting: Option, +} + /// The page's channel for each room it subscribed to, and its one session /// channel. The core accepts at most `MAX_SUBSCRIPTIONS` rooms, and a room /// channel is kept only after the core accepted the room, so this map is @@ -393,7 +405,7 @@ pub struct Subscriptions { /// Each page's channel for the call statistics (ADR-0066). A window has /// one only while its page has the technical details open, so a reading /// goes only to a page that asked for it. - stats: Mutex>>, + stats: Mutex>, /// How many pages each window has loaded (ADR-0066). A page gets its /// count from `watch_session` and sends it with each statistics request, /// so a request of a page that is gone changes nothing, and a start that a @@ -433,7 +445,7 @@ impl Subscriptions { .unwrap_or_else(|poisoned| poisoned.into_inner()) } - fn stats(&self) -> MutexGuard<'_, HashMap>> { + fn stats(&self) -> MutexGuard<'_, HashMap> { self.stats .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) @@ -474,7 +486,32 @@ impl Subscriptions { if pages.get(&label).copied().unwrap_or(0) != page { return false; } - self.stats().insert(label, channel); + self.stats().insert( + label, + StatsChannel { + channel, + unread: false, + waiting: None, + }, + ); + true + } + + /// The page `page` of the window `label` handled its last reading. Sends + /// the waiting reading, if any, and keeps the page unread, or clears + /// `unread`. False when the window shows another page. + fn stats_read(&self, label: &str, page: u64) -> bool { + if self.page(label) != page { + return false; + } + if let Some(entry) = self.stats().get_mut(label) { + match entry.waiting.take() { + Some(stats) => { + let _ = entry.channel.send(stats); + } + None => entry.unread = false, + } + } true } @@ -569,8 +606,13 @@ impl Subscriptions { if !stats.within_limits() { return; } - for channel in self.stats().values() { - let _ = channel.send(stats.clone()); + for entry in self.stats().values_mut() { + if entry.unread { + entry.waiting = Some(stats.clone()); + } else { + let _ = entry.channel.send(stats.clone()); + entry.unread = true; + } } } Event::RingsChanged {} => self.tell_sessions("rings"), @@ -716,6 +758,25 @@ async fn call_stats( Ok(()) } +/// Says that the calling window's page handled its last statistics reading +/// (ADR-0066), so the host sends the next one. Only the call window may call +/// it, with the count its page got from `watch_session`. It never reaches the +/// core. A request with another count comes from a page the window no longer +/// shows, and it fails and changes nothing. With no statistics channel it +/// does nothing. +#[tauri::command] +fn call_stats_read( + webview: Webview, + subscriptions: State<'_, Arc>, + page: u64, +) -> Result<(), String> { + if subscriptions.stats_read(webview.label(), page) { + Ok(()) + } else { + Err(INVALID_ARGUMENT.to_owned()) + } +} + /// Locks the core's session. Replies with the resulting state; `locking` /// means admitted work is still finishing, and calling again resumes the wait. #[tauri::command] @@ -2341,6 +2402,7 @@ pub fn configure( call_camera, call_screen, call_stats, + call_stats_read, call_video_frame, call_status, call_rings, diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index 59ad1153..bc3963ff 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -1159,6 +1159,7 @@ fn given_shell_config_then_security_settings_are_restrictive() { "allow-call-devices", "allow-set-call-devices", "allow-call-stats", + "allow-call-stats-read", "allow-close-call-window" ]) ); @@ -1323,6 +1324,32 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ .filter(|(channel, body)| *channel == 9 && *body == text) .count() }; + // Every delivery on the statistics channel, whatever it holds: a clamped + // or repaired reading would count here, but not in `sent`. + let total = || { + delivered + .lock() + .unwrap() + .iter() + .filter(|(channel, _)| *channel == 9) + .count() + }; + // A reading that the host refuses or that has no channel to go to must + // add no delivery at all. + let none_delivered = |stats: CallStats| { + let before = total(); + subscriptions.dispatch(Event::CallStats { stats }); + assert_eq!(total(), before, "no delivery"); + }; + // The page handled its last reading (ADR-0066). + let read = |from: u64| { + invoke_on( + &call, + "call_stats_read", + app_origin(), + serde_json::json!({"page": from}), + ) + }; // A stop of the host goes on a task of its own, so wait for it, but not // forever: the mock runtime sends no page or window events, so nothing // else would end the wait. A switch that never comes fails here, by name. @@ -1353,8 +1380,7 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ assert!(switches().is_empty()); // Not asked for: no channel, nothing is delivered. - subscriptions.dispatch(Event::CallStats { stats: reading(1) }); - assert_eq!(sent(1), 0); + none_delivered(reading(1)); // A bad argument, or no page count, never reaches the core. for bad in [ @@ -1373,8 +1399,7 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ assert!(invoke_on(&call, "call_stats", app_origin(), stats_on(true, page)).is_err()); core.refuse_stats.store(false, Ordering::SeqCst); assert_eq!(switches(), [true], "the start was tried"); - subscriptions.dispatch(Event::CallStats { stats: reading(1) }); - assert_eq!(sent(1), 0); + none_delivered(reading(1)); assert!(!subscriptions.forget_stats(CALL_WINDOW), "no channel kept"); core.stats_switches.lock().unwrap().clear(); @@ -1387,11 +1412,10 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ subscriptions.dispatch(Event::CallStats { stats: reading(2) }); assert_eq!(sent(2), 1); - // A reading outside its limits is dropped whole. - subscriptions.dispatch(Event::CallStats { - stats: reading(101), - }); - assert_eq!(sent(101), 0); + // A reading outside its limits is dropped whole. The page read the + // first reading, so a held-back delivery cannot hide a clamped one. + assert_eq!(read(page), Ok(serde_json::Value::Null)); + none_delivered(reading(101)); // Off: the channel goes and the core is told. assert_eq!( @@ -1399,8 +1423,7 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ Ok(serde_json::Value::Null) ); assert_eq!(switches(), [true, false]); - subscriptions.dispatch(Event::CallStats { stats: reading(3) }); - assert_eq!(sent(3), 0); + none_delivered(reading(3)); // A window that is reloaded or closed drops its channel and tells the // core to stop, through the handler its page load and its close use. @@ -1412,8 +1435,7 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ assert_eq!(switches(), [true, false, true, false]); // The channel went with it, so another reset has nothing to stop. assert!(!subscriptions.forget_stats(CALL_WINDOW), "once"); - subscriptions.dispatch(Event::CallStats { stats: reading(4) }); - assert_eq!(sent(4), 0); + none_delivered(reading(4)); // A request of a page that is gone carries its old count, so it fails // and changes nothing, however late Tauri starts its task: after the @@ -1427,8 +1449,7 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ let page = new_page(); assert!(invoke_on(&call, "call_stats", app_origin(), stats_on(true, old)).is_err()); assert!(switches().is_empty(), "a stale start reaches no core"); - subscriptions.dispatch(Event::CallStats { stats: reading(5) }); - assert_eq!(sent(5), 0); + none_delivered(reading(5)); // The new page's own start stands, and a stale stop does not end it. invoke_on(&call, "call_stats", app_origin(), stats_on(true, page)).unwrap(); assert!(invoke_on(&call, "call_stats", app_origin(), stats_on(false, old)).is_err()); @@ -1469,8 +1490,7 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ [true, false], "reload by watch: {reload_by_watch}" ); - subscriptions.dispatch(Event::CallStats { stats: reading(7) }); - assert_eq!(sent(7), 0); + none_delivered(reading(7)); core.stats_switches.lock().unwrap().clear(); } @@ -1481,8 +1501,44 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ new_page(); wait_for(2); assert_eq!(switches(), [true, false]); - subscriptions.dispatch(Event::CallStats { stats: reading(8) }); - assert_eq!(sent(8), 0); + none_delivered(reading(8)); + + // One reading in flight per page, and only the newest waits. + let page = new_page(); + invoke_on(&call, "call_stats", app_origin(), stats_on(true, page)).unwrap(); + let base = total(); + for level in [10, 11, 12] { + subscriptions.dispatch(Event::CallStats { + stats: reading(level), + }); + } + assert_eq!((sent(10), sent(11), sent(12)), (1, 0, 0), "one in flight"); + assert_eq!(total() - base, 1); + assert_eq!(read(page), Ok(serde_json::Value::Null)); + assert_eq!((sent(11), sent(12)), (0, 1), "the newest waited"); + assert_eq!(total() - base, 2); + // Nothing waits now, so a read only frees the page and the next reading + // goes at once. + assert_eq!(read(page), Ok(serde_json::Value::Null)); + assert_eq!(total() - base, 2); + subscriptions.dispatch(Event::CallStats { stats: reading(13) }); + assert_eq!(sent(13), 1); + // A read of a page that is gone, or from the main window, changes nothing. + assert_eq!(read(page - 1), Err(serde_json::json!("invalid_argument"))); + assert!( + invoke_on( + &main, + "call_stats_read", + app_origin(), + serde_json::json!({"page": page}) + ) + .is_err() + ); + subscriptions.dispatch(Event::CallStats { stats: reading(14) }); + assert_eq!(sent(14), 0, "the stale read did not free the page"); + // With no statistics channel a read is fine and does nothing. + assert!(subscriptions.forget_stats(CALL_WINDOW)); + assert_eq!(read(page), Ok(serde_json::Value::Null)); } /// GIVEN device test commands THEN bounded IDs cross, a bad one never From 7bb5a4fdac7ac58c8de10c3907df9bdc1834803b Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 22:27:26 +0000 Subject: [PATCH 40/51] Wait for the call page to say it is ready, and keep Leave A shown call window does not prove that its page works. If the page failed to start, neither window offered mute or leave. The call page now calls `call_window_ready` after its first status read. Only the call window may call it, and the host forgets it when a new call window is made or the page loads again. `open_call_window` returns only when the page is ready, and fails after 10 seconds, so the main window then shows the call's controls. At most four opens wait at once. The short call bar also keeps a "Leave" button, which covers the wait and a call page that stops working later. The owner asked for both. Co-Authored-By: Claude Opus 5.5 --- ...60-show-calls-in-a-separate-call-window.md | 28 +-- frontend/src/App.svelte | 7 +- frontend/src/CallBar.svelte | 16 +- frontend/src/CallWindow.svelte | 13 +- frontend/src/bridge/index.ts | 15 +- frontend/src/callWindow.ts | 3 +- frontend/tests/bridge-calls.test.mjs | 1 + frontend/tests/render.test.mjs | 6 +- src-tauri/build.rs | 1 + src-tauri/capabilities/call.json | 5 +- .../autogenerated/call_window_ready.toml | 11 ++ src-tauri/src/lib.rs | 164 ++++++++++++++++-- src-tauri/tests/ipc.rs | 45 ++++- 13 files changed, 274 insertions(+), 41 deletions(-) create mode 100644 src-tauri/permissions/autogenerated/call_window_ready.toml diff --git a/docs/adr/0060-show-calls-in-a-separate-call-window.md b/docs/adr/0060-show-calls-in-a-separate-call-window.md index f1c3b83d..6f4abce3 100644 --- a/docs/adr/0060-show-calls-in-a-separate-call-window.md +++ b/docs/adr/0060-show-calls-in-a-separate-call-window.md @@ -45,8 +45,8 @@ commands. uses the main window's navigation rule and refuses new windows. * The capability `call` lets that window call `watch_session`, `call_status`, `call_video_frame`, `call_leave`, `call_mute`, - `call_deafen`, `call_volume`, `call_camera`, `call_screen` and - `close_call_window`, and nothing else. It cannot read rooms, members, + `call_deafen`, `call_volume`, `call_camera`, `call_screen`, + `close_call_window` and `call_window_ready`, and nothing else. It cannot read rooms, members, messages, account settings or files, start a call or start a device test. * The main window opens it with `open_call_window` when a call starts to join, once for each call. The call bar has a "Call window" button that @@ -55,8 +55,9 @@ commands. * On 25 November 2026 the owner asked to show the call's controls, video, volume, level meter and participants in the call window only. While the call window opens, the main window's call bar shows only the phone icon, - the room, the phase, the "Call window" button and, after a declined ring - (ADR-0052), the "Declined" note, which the call window does not show. It + the room, the phase, the "Call window" button, a "Leave" button and, + after a declined ring (ADR-0052), the "Declined" note, which the call + window does not show. It also shows the camera, screen share and device change notes, so a camera that did not start, a running or refused screen share and a failed microphone or speaker are seen while the call window is closed. The @@ -67,6 +68,16 @@ commands. reason and "Dismiss". This replaces the driver above for an open call window: the bar keeps the controls only when the call window cannot open, and its "Call window" button reopens a closed call window. +* Also on 25 November 2026 the owner asked for both the "Leave" button in + the short bar and a ready signal. A shown window does not prove that its + page works, so after its first `call_status` read the call page calls + `call_window_ready`. The host accepts it from the `call` window only, and + forgets it when a new call window is made or the call page loads again. + `open_call_window` returns only when the page is ready. When the page + does not say so within 10 seconds, the open fails with `unavailable`, and + the main window shows the call's controls. At most four opens wait at + once; another one fails at once. "Leave" in the short bar covers the + wait, and a call page that stops working later. * The host keeps each window's session, sound level and level channels under the window's label. Room subscriptions belong to the main window only. A call window that closes or reloads drops only its own channels. @@ -110,9 +121,6 @@ commands. * A second web view uses more memory during a call. * Names and the chosen theme are not shown in the call window. * The page code for the grid repeats some of `CallVideo.svelte`. -* Known limitation (25 November 2026): the main window counts the call - window as open when the host shows it, not when its page works. If the - call page fails to start after the window shows, neither window offers - mute or leave for that call. A ready signal from the call page, or a - Leave button in the short bar, would close this gap; the owner has not - chosen one yet. +* A call page that stops working after it said it is ready leaves the main + window with "Leave" only, not mute, until the call window is opened again + and fails its ready wait. diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte index 447b2f5a..45df6390 100644 --- a/frontend/src/App.svelte +++ b/frontend/src/App.svelte @@ -775,9 +775,10 @@ // once per call: closing it during the call keeps it closed until the call // bar's "Call window" button. let callWindowFor = false; - // The call window could not open for this call. The main window then shows - // the call's controls and video itself; otherwise only the call window - // does. A later open that works hides them again. + // The call window could not open for this call, or its page did not say + // in time that it is ready. The main window then shows the call's controls + // and video itself; otherwise only the call window does, and the short bar + // keeps Leave. A later open that works hides them again. let callWindowFailed = $state(false); // Which open replies count is decided in callWindow.ts. const callWindowOpener = new CallWindowOpener( diff --git a/frontend/src/CallBar.svelte b/frontend/src/CallBar.svelte index fb1baf3d..6552ac49 100644 --- a/frontend/src/CallBar.svelte +++ b/frontend/src/CallBar.svelte @@ -35,12 +35,13 @@ // the page so that a change in it is announced. Speaking changes are not // announced: each participant's mark is read in place only. // - // The call window holds the call's controls (ADR-0060). While it can open, - // the bar shows only the room, the phase, a "Call window" button, the + // The call window holds the call's controls (ADR-0060). Unless it failed + // to open or its page did not say it is ready, the bar shows only the room, the phase, a "Call window" button, a "Leave" + // button, which works even when the call page stops working, the // "Declined" note, which the call window does not show, and the camera, // screen share and device change notes, which must be seen while the call - // window is closed. When it could not open (`full`), the bar shows every - // control, so the call can still be muted or left here. + // window is closed. When it failed (`full`), the bar shows every control, + // so the call can still be muted or left here. let { status, dismissed, @@ -106,6 +107,10 @@ {/snippet} +{#snippet leaveButton()} + +{/snippet} +
{callAnnouncement(status, dismissed)}
@@ -120,6 +125,7 @@ {:else if !full} {@render callWindowButton()} + {@render leaveButton()} {:else} + {@render leaveButton()} {/if} diff --git a/frontend/src/CallWindow.svelte b/frontend/src/CallWindow.svelte index 392549ee..3168d3d0 100644 --- a/frontend/src/CallWindow.svelte +++ b/frontend/src/CallWindow.svelte @@ -17,6 +17,7 @@ callScreen, callStatus, callVolume, + callWindowReady, closeCallWindow, watchSession } from './bridge'; @@ -125,6 +126,16 @@ } } + // The first status read: when it works, the page can show and run the + // call, so it tells the host it is ready (ADR-0060). A failure leaves it + // unready, and the main window then shows the call's controls itself. + async function start() { + const mine = ++request; + const next = await callStatus(); + if (mine === request) take(next); + await callWindowReady(); + } + function takeLevels(next: CallParticipantLevel[]) { levels = status.phase === 'active' ? levelMap(next) : new Map(); } @@ -143,7 +154,7 @@ (level) => (ownLevel = status.phase === 'active' ? level : 0), takeLevels ) - .then(refresh) + .then(start) .catch(() => (failure = 'The call window could not reach Persephone.')); }); diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts index 9758707e..7a3f4235 100644 --- a/frontend/src/bridge/index.ts +++ b/frontend/src/bridge/index.ts @@ -432,9 +432,10 @@ export function minimiseToTray(): Promise { } /** - * Opens the call window (ADR-0060), or brings it to the front. It shows the - * call's video grid, participants and controls. The main window keeps a - * short call bar, with the full controls only when this fails. + * Opens the call window (ADR-0060), or brings it to the front, and resolves + * when its page says it is ready. It shows the call's video grid, + * participants and controls. The main window keeps a short call bar, with + * the full controls only when this fails. */ export function openCallWindow(): Promise { return invoke('open_call_window'); @@ -445,6 +446,14 @@ export function closeCallWindow(): Promise { return invoke('close_call_window'); } +/** + * The call page says that it reaches the core and shows the call + * (ADR-0060). Until it does, the main window's open waits, then fails. + */ +export function callWindowReady(): Promise { + return invoke('call_window_ready'); +} + /** Locks the session; `locking` means work is still finishing (call again). */ export function lockSession(): Promise { return invoke('lock_session'); diff --git a/frontend/src/callWindow.ts b/frontend/src/callWindow.ts index d578eeb7..1effab25 100644 --- a/frontend/src/callWindow.ts +++ b/frontend/src/callWindow.ts @@ -75,7 +75,8 @@ export const CALL_WINDOW_UNAVAILABLE_TEXT = 'The call window could not open. The * after one that worked. Opens can overlap, as the automatic open and a * "Call window" click do, and their replies can come in any order: * - * - An open that worked always counts, because the window is then open. + * - An open that worked always counts, because the call page then works: + * the host replies only when the page has said it is ready. * - A failure counts only for the newest open, and only when no open has * worked since it started. * - `forget()` ends the call: no reply from before it counts. diff --git a/frontend/tests/bridge-calls.test.mjs b/frontend/tests/bridge-calls.test.mjs index 8388cf44..85aea912 100644 --- a/frontend/tests/bridge-calls.test.mjs +++ b/frontend/tests/bridge-calls.test.mjs @@ -114,6 +114,7 @@ test('GIVEN the room, account, settings and profile calls WHEN made THEN each ma [() => bridge.minimiseToTray(), 'minimise_to_tray', {}], [() => bridge.openCallWindow(), 'open_call_window', {}], [() => bridge.closeCallWindow(), 'close_call_window', {}], + [() => bridge.callWindowReady(), 'call_window_ready', {}], [() => bridge.callDeviceTest('microphone', null), 'call_device_test', { test: 'microphone', device: null }], [() => bridge.callDeviceTest('camera', 'cam-1'), 'call_device_test', { test: 'camera', device: 'cam-1' }], [() => bridge.callDeviceTestStop(), 'call_device_test_stop', { id: null }], diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs index a694f6ee..2f0c50db 100644 --- a/frontend/tests/render.test.mjs +++ b/frontend/tests/render.test.mjs @@ -246,7 +246,7 @@ test('GIVEN a call whose ring was declined WHEN the call bar renders THEN it say assert.doesNotMatch(plain, /Declined/); }); -test('GIVEN a call window that opens WHEN the call bar renders THEN it shows the room, the phase and the call window button only', async () => { +test('GIVEN a call window that opens WHEN the call bar renders THEN it shows the room, the phase, the call window button and Leave only', async () => { const { default: CallBar } = await vite.ssrLoadModule('/src/CallBar.svelte'); const status = { phase: 'active', roomId: '!r:s', muted: true, deafened: false, volume: 100, ended: null, joinError: null, @@ -262,7 +262,9 @@ test('GIVEN a call window that opens WHEN the call bar renders THEN it shows the // The camera and screen share notes still show: the call window may be closed. assert.match(short, /class="call-camera-note note"[^>]*>The chosen camera is not connected]*>You are sharing your screen]*>Leave(app: AppHandle) -> Result<(), String> { +/// How long `open_call_window` waits for the call page to say it is ready. +const CALL_WINDOW_READY_WAIT: Duration = Duration::from_secs(10); +/// At most this many `open_call_window` calls wait at once; each holds a +/// blocking thread until the page is ready or the wait ends. +const MAX_CALL_WINDOW_WAITS: usize = 4; + +/// Whether the call page has said that it reaches the core and shows the +/// call (ADR-0060). A new call window or a call page that loads again is not +/// ready until it says so again. +struct CallWindowReady { + state: Mutex, + changed: Condvar, + wait: Duration, +} + +#[derive(Default)] +struct ReadyState { + ready: bool, + waiting: usize, +} + +impl Default for CallWindowReady { + fn default() -> Self { + Self::waiting_for(CALL_WINDOW_READY_WAIT) + } +} + +impl CallWindowReady { + /// A state whose waits end after `wait`. + fn waiting_for(wait: Duration) -> Self { + Self { + state: Mutex::default(), + changed: Condvar::new(), + wait, + } + } + + fn state(&self) -> MutexGuard<'_, ReadyState> { + self.state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn set(&self, ready: bool) { + self.state().ready = ready; + self.changed.notify_all(); + } + + /// Waits until the page is ready, for at most the set time. False when + /// the wait ends first, or when too many calls wait already. + fn wait(&self) -> bool { + let mut state = self.state(); + if state.ready { + return true; + } + if state.waiting >= MAX_CALL_WINDOW_WAITS { + return false; + } + state.waiting += 1; + let (mut state, _) = self + .changed + .wait_timeout_while(state, self.wait, |state| !state.ready) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state.waiting -= 1; + state.ready + } +} + +/// Opens the call window (ADR-0060), or brings it to the front, and returns +/// when its page says it is ready. It shows the bundled call page only. A +/// window that cannot be shown, or whose page does not say it is ready in +/// time, is an error, because the main window then shows the call's +/// controls itself. Focus is only a request, as is unminimise: the desktop +/// may refuse either while the window shows. +#[tauri::command] +async fn open_call_window( + app: AppHandle, + ready: State<'_, Arc>, +) -> Result<(), String> { if let Some(window) = app.get_webview_window(CALL_WINDOW) { let _ = window.unminimize(); window.show().map_err(|error| { @@ -1767,11 +1840,32 @@ async fn open_call_window(app: AppHandle) -> Result<(), String> { UNAVAILABLE.to_string() })?; let _ = window.set_focus(); - return Ok(()); + } else { + ready.set(false); + create_call_window(&app).map_err(|_| UNAVAILABLE.to_string())?; + } + let ready = Arc::clone(ready.inner()); + match tauri::async_runtime::spawn_blocking(move || ready.wait()).await { + Ok(true) => Ok(()), + _ => { + eprintln!("persephone-ui: the call page did not say it is ready"); + Err(UNAVAILABLE.to_string()) + } + } +} + +/// The call page reaches the core and shows the call (ADR-0060). Only the +/// call window may say so. +#[tauri::command] +async fn call_window_ready( + webview: Webview, + ready: State<'_, Arc>, +) -> Result<(), String> { + if webview.label() != CALL_WINDOW { + return Err(UNAVAILABLE.to_string()); } - create_call_window(&app) - .map(drop) - .map_err(|_| UNAVAILABLE.to_string()) + ready.set(true); + Ok(()) } /// Closes the call window, if it is open (ADR-0060). @@ -2143,6 +2237,7 @@ pub fn configure( .manage(BandsInFlight::default()) .manage(VideoInFlight::default()) .manage(PasteInFlight::default()) + .manage(Arc::new(CallWindowReady::default())) // One handler for the tray menu, for the life of the app: a handler // given to each new tray icon would stay after the icon goes. .on_menu_event(|app, event| { @@ -2282,10 +2377,16 @@ pub fn configure( call_device_test_stop, call_device_test_status, open_call_window, - close_call_window + close_call_window, + call_window_ready ]) .on_page_load(|webview, payload| { if payload.event() == PageLoadEvent::Started { + // A call page that loads again must say again that it is + // ready (ADR-0060). + if webview.label() == CALL_WINDOW { + webview.state::>().set(false); + } reset_subscriptions( webview.state::().inner(), webview.state::>().inner(), @@ -2491,6 +2592,43 @@ pub fn run() { mod tests { use super::*; + /// GIVEN a call page that has not said it is ready WHEN an open waits + /// THEN the wait ends false; WHEN the page says so THEN it is true; + /// WHEN the page loads again THEN it is false again. + #[test] + fn given_a_call_page_then_an_open_waits_until_it_is_ready() { + let ready = CallWindowReady::waiting_for(Duration::from_millis(20)); + assert!(!ready.wait()); + ready.set(true); + assert!(ready.wait()); + ready.set(false); + assert!(!ready.wait()); + } + + /// GIVEN `MAX_CALL_WINDOW_WAITS` opens that wait WHEN another starts + /// THEN it fails at once; WHEN the page says it is ready THEN every + /// waiting open returns true. + #[test] + fn given_waiting_opens_then_only_a_bounded_number_wait() { + let ready = Arc::new(CallWindowReady::waiting_for(Duration::from_secs(30))); + let waits: Vec<_> = (0..MAX_CALL_WINDOW_WAITS) + .map(|_| { + let ready = Arc::clone(&ready); + std::thread::spawn(move || ready.wait()) + }) + .collect(); + while ready.state().waiting < MAX_CALL_WINDOW_WAITS { + std::thread::yield_now(); + } + let started = std::time::Instant::now(); + assert!(!ready.wait()); + assert!(started.elapsed() < Duration::from_secs(5)); + ready.set(true); + for wait in waits { + assert!(wait.join().unwrap()); + } + } + /// GIVEN `MAX_BANDS_IN_FLIGHT` running band calls WHEN another starts /// THEN it gets no slot; WHEN exactly one running call ends THEN exactly /// one new call gets a slot. diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index 7c0d55ae..de512df3 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -1116,7 +1116,8 @@ fn given_shell_config_then_security_settings_are_restrictive() { "allow-call-volume", "allow-call-camera", "allow-call-screen", - "allow-close-call-window" + "allow-close-call-window", + "allow-call-window-ready" ]) ); assert!(call.get("remote").is_none(), "no remote origins"); @@ -1174,6 +1175,48 @@ fn given_the_call_window_then_only_call_commands_are_allowed() { ); } +/// GIVEN a call window WHEN the main window says its page is ready THEN it +/// is refused; WHEN the call page says so THEN the main window's open +/// returns without waiting. +#[test] +fn given_a_ready_call_page_then_the_open_returns() { + let app = app(); + let main = create_main_window(&app).unwrap(); + let call = create_call_window(&app).unwrap(); + assert!( + invoke_on( + &main, + "call_window_ready", + app_origin(), + serde_json::json!({}) + ) + .is_err() + ); + assert_eq!( + invoke_on( + &call, + "call_window_ready", + app_origin(), + serde_json::json!({}) + ), + Ok(serde_json::Value::Null) + ); + let started = std::time::Instant::now(); + assert_eq!( + invoke_on( + &main, + "open_call_window", + app_origin(), + serde_json::json!({}) + ), + Ok(serde_json::Value::Null) + ); + assert!( + started.elapsed() < std::time::Duration::from_secs(5), + "no wait" + ); +} + /// GIVEN device test commands THEN bounded IDs cross, a bad one never /// reaches the core, and a reply outside the contract is refused. #[test] From f282926a1baf84ba07f67c3f3366cb53e3d8fa4a Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 22:29:53 +0000 Subject: [PATCH 41/51] Hold the page count across a statistics read The read check and the change of the window's statistics channel now hold the page count, as keep_stats does, so a reload cannot give the new page's channel the old page's read. Co-Authored-By: Claude Opus 5.5 --- frontend/src/calls.ts | 3 ++- src-tauri/src/lib.rs | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/frontend/src/calls.ts b/frontend/src/calls.ts index b2a6530a..766273a8 100644 --- a/frontend/src/calls.ts +++ b/frontend/src/calls.ts @@ -763,7 +763,8 @@ export const DEVICE_SAVE_FAILURE_TEXT = 'The call devices could not be saved.'; * call (ADR-0065). A failure is the call status's `deviceChange` (ADR-0059). * The status has no mark for a change that worked, so `null` cannot tell * "worked" from "not answered yet". After a save the panel says only that - * the choice is saved, and a failure shows when the worker answers. A speaker that is lost needs a rejoin (`failed`). + * the choice is saved, and a failure shows when the worker answers. A + * speaker that is lost needs a rejoin (`failed`). */ export const DEVICE_SWITCH_TEXT: Record = { not_found: 'The chosen microphone or speaker is not connected. The call keeps the one it had.', diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8e1d1731..004380ba 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -499,9 +499,12 @@ impl Subscriptions { /// The page `page` of the window `label` handled its last reading. Sends /// the waiting reading, if any, and keeps the page unread, or clears - /// `unread`. False when the window shows another page. + /// `unread`. False when the window shows another page. The check and the + /// change hold the page count, as `keep_stats` does, so a reload cannot + /// come between them and give the new page's channel the old page's read. fn stats_read(&self, label: &str, page: u64) -> bool { - if self.page(label) != page { + let pages = self.pages(); + if pages.get(label).copied().unwrap_or(0) != page { return false; } if let Some(entry) = self.stats().get_mut(label) { From b3bf4af76206d1931443e5b20e4125ba8288a183 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 22:41:52 +0000 Subject: [PATCH 42/51] Show the call window open while it waits, and test the ready guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "Call window" button reads "Opening the call window…" and takes no clicks while an open waits for the call page, so repeated clicks no longer fill the waits and bring the full bar back. The ready label check is its own function and refuses another window with invalid_argument, and a unit test covers it. ADR-0060 now says that the button does not recover a call page that stopped working: the call window must be closed and opened again, or its page loaded again. Co-Authored-By: Claude Opus 5.5 --- ...60-show-calls-in-a-separate-call-window.md | 11 +++++--- frontend/src/App.svelte | 7 ++++++ frontend/src/CallBar.svelte | 7 ++++-- frontend/tests/render.test.mjs | 5 ++++ src-tauri/src/lib.rs | 25 +++++++++++++++++-- 5 files changed, 47 insertions(+), 8 deletions(-) diff --git a/docs/adr/0060-show-calls-in-a-separate-call-window.md b/docs/adr/0060-show-calls-in-a-separate-call-window.md index 6f4abce3..2ee5f1f5 100644 --- a/docs/adr/0060-show-calls-in-a-separate-call-window.md +++ b/docs/adr/0060-show-calls-in-a-separate-call-window.md @@ -76,8 +76,9 @@ commands. `open_call_window` returns only when the page is ready. When the page does not say so within 10 seconds, the open fails with `unavailable`, and the main window shows the call's controls. At most four opens wait at - once; another one fails at once. "Leave" in the short bar covers the - wait, and a call page that stops working later. + once; another one fails at once. While an open waits, the "Call window" + button reads "Opening the call window…" and takes no clicks. "Leave" in + the short bar covers the wait, and a call page that stops working later. * The host keeps each window's session, sound level and level channels under the window's label. Room subscriptions belong to the main window only. A call window that closes or reloads drops only its own channels. @@ -122,5 +123,7 @@ commands. * Names and the chosen theme are not shown in the call window. * The page code for the grid repeats some of `CallVideo.svelte`. * A call page that stops working after it said it is ready leaves the main - window with "Leave" only, not mute, until the call window is opened again - and fails its ready wait. + window with "Leave" only, not mute. The "Call window" button only shows the + same window, which still counts as ready, so it does not bring the full bar + back. That needs the call window closed and opened again, or its page + loaded again. diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte index 45df6390..7731a4f5 100644 --- a/frontend/src/App.svelte +++ b/frontend/src/App.svelte @@ -784,6 +784,7 @@ const callWindowOpener = new CallWindowOpener( () => openCallWindow(), (failed) => { + callWindowOpening = false; callWindowFailed = failed; // A window that cannot open leaves the call here; say so, so no // window is missed without a reason. @@ -791,13 +792,18 @@ else if (error === CALL_WINDOW_UNAVAILABLE_TEXT) error = null; } ); + // An open waits for the call page, up to ten seconds; the button says so + // and takes no more clicks meanwhile. + let callWindowOpening = $state(false); function showCallWindow() { + callWindowOpening = true; callWindowOpener.open(); } // Ends the call window state of a call that is over: no fallback, no // "could not open" message, and no reply from an open still waiting. function forgetCallWindow() { callWindowOpener.forget(); + callWindowOpening = false; callWindowFailed = false; if (error === CALL_WINDOW_UNAVAILABLE_TEXT) error = null; } @@ -3208,6 +3214,7 @@ status={callState} dismissed={callDismissed} full={callWindowFailed} + opening={callWindowOpening} roomName={callRoomName} names={callNames} busy={callBusy} diff --git a/frontend/src/CallBar.svelte b/frontend/src/CallBar.svelte index 6552ac49..d832dad7 100644 --- a/frontend/src/CallBar.svelte +++ b/frontend/src/CallBar.svelte @@ -46,6 +46,7 @@ status, dismissed, full, + opening = false, roomName, names, busy, @@ -66,6 +67,8 @@ dismissed: boolean; // The call window could not open: show the controls here. full: boolean; + // An open waits for the call page: the button is off meanwhile. + opening?: boolean; roomName: string; // Display names from the call room's members, by user ID. names: ReadonlyMap; @@ -101,9 +104,9 @@ {#snippet callWindowButton()} - {/snippet} diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs index 2f0c50db..ffd65139 100644 --- a/frontend/tests/render.test.mjs +++ b/frontend/tests/render.test.mjs @@ -272,6 +272,11 @@ test('GIVEN a call window that opens WHEN the call bar renders THEN it shows the assert.match(changed, /class="call-device-note note"/); assert.match(changed, /rejoin/); assert.doesNotMatch(changed, controls); + assert.doesNotMatch(short, /call-window-open"[^>]*disabled/); + // While an open waits for the call page, the button says so and is off. + const { body: opening } = render(CallBar, { props: { ...props, status, opening: true } }); + assert.match(opening, /class="secondary call-window-open"[^>]*disabled[^>]*>[\s\S]*?Opening the call window…/); + assert.match(opening, /class="secondary call-leave"/); // An ended call still says why, and can be dismissed. const { body: ended } = render(CallBar, { props: { ...props, status: { ...status, phase: 'ended', ended: 'internal' } } }); assert.match(ended, /call-dismiss/); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index da03a8aa..722bdee2 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1861,8 +1861,14 @@ async fn call_window_ready( webview: Webview, ready: State<'_, Arc>, ) -> Result<(), String> { - if webview.label() != CALL_WINDOW { - return Err(UNAVAILABLE.to_string()); + take_ready(webview.label(), &ready) +} + +/// Marks the call page ready when the call window said so. The capability +/// already limits the command to that window; this checks again. +fn take_ready(label: &str, ready: &CallWindowReady) -> Result<(), String> { + if label != CALL_WINDOW { + return Err(INVALID_ARGUMENT.to_string()); } ready.set(true); Ok(()) @@ -2605,6 +2611,21 @@ mod tests { assert!(!ready.wait()); } + /// GIVEN a ready signal WHEN it comes from a window other than the call + /// window THEN it is refused and the page stays unready; WHEN it comes + /// from the call window THEN the page is ready. + #[test] + fn given_a_ready_signal_then_only_the_call_window_counts() { + let ready = CallWindowReady::waiting_for(Duration::from_millis(20)); + assert_eq!( + take_ready(MAIN_WINDOW, &ready), + Err(INVALID_ARGUMENT.to_string()) + ); + assert!(!ready.wait()); + assert_eq!(take_ready(CALL_WINDOW, &ready), Ok(())); + assert!(ready.wait()); + } + /// GIVEN `MAX_CALL_WINDOW_WAITS` opens that wait WHEN another starts /// THEN it fails at once; WHEN the page says it is ready THEN every /// waiting open returns true. From 5cf7a79a2f876b62a9cf33cc08aef1e4f6a69f6b Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 23:04:07 +0000 Subject: [PATCH 43/51] Isolate the device ID in a statistics caption, and refuse a page with no count - A device's table caption is `CallStatsCaption.svelte`. The device ID has its own `` beside the isolated user ID, with a hidden "device" for screen readers. A render test covers a device, a hostile device ID and a title. - A window whose page was not counted has no count, so a statistics start, stop or read with page 0 is refused. The bridge takes counts of 1 or more. - The positional statistics tests use complete records that the derived readers take, so only the map-only reader refuses them. - The worker comment says that a reading the writer took already can still follow the off, and that the core drops it. Co-Authored-By: Claude Opus 5.5 --- crates/call-worker/src/session.rs | 4 +++- crates/core-protocol/src/lib.rs | 22 +++++++++++++++++++--- frontend/AGENTS.md | 2 +- frontend/src/CallStats.svelte | 7 ++----- frontend/src/CallStatsCaption.svelte | 14 ++++++++++++++ frontend/src/bridge/index.ts | 3 ++- frontend/tests/bridge-calls.test.mjs | 2 +- frontend/tests/render.test.mjs | 19 +++++++++++++++++++ src-tauri/src/lib.rs | 14 ++++++++------ src-tauri/tests/ipc.rs | 8 ++++++++ 10 files changed, 77 insertions(+), 18 deletions(-) create mode 100644 frontend/src/CallStatsCaption.svelte diff --git a/crates/call-worker/src/session.rs b/crates/call-worker/src/session.rs index 6dfcc438..96f09ee6 100644 --- a/crates/call-worker/src/session.rs +++ b/crates/call-worker/src/session.rs @@ -3276,7 +3276,9 @@ async fn event_loop( } Some(Input::Message(message)) => { // The off also drops a reading that waits in the output - // slot, so none is written after the off (ADR-0066). + // slot. A reading that the writer took already can still + // be written after the off; the core drops it, because + // its switch is off then (ADR-0066). let stats_off = matches!(message, ToWorker::SetStats { on: false }); match call.handle_command(message).await { Ok(reply) => outgoing.extend(reply), diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index 75b43703..97380ba5 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -4579,12 +4579,28 @@ mod timeline_events_wire_tests { reading(microphone, participants, connections) )) }; - assert!(read(&with("[1,null,null,null]", "[]", "[]")).is_err()); - assert!(read(&with("null", "[]", "[[0,null,null,null,null]]")).is_err()); + // Each array is a complete record that the derived reader of the + // contract type takes, so only the map-only reader refuses it here. + let microphone = "[1,null,0,null,null,null]"; + let heard = "[1,null,0,0,0,null]"; + let connection = "[0,null,null,null,null]"; + assert!( + serde_json::from_str::(microphone).is_ok() + ); + assert!( + serde_json::from_str::(heard).is_ok() + ); + assert!( + serde_json::from_str::(connection).is_ok() + ); + assert!(read(&with(microphone, "[]", "[]")).is_err()); + assert!(read(&with("null", "[]", &format!("[{connection}]"))).is_err()); assert!( read(&with( "null", - r#"[{"userId":"@a:example.org","deviceId":"D","audio":[1,null,null,null,null],"video":null}]"#, + &format!( + r#"[{{"userId":"@a:example.org","deviceId":"D","audio":{heard},"video":null}}]"# + ), "[]" )) .is_err() diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md index 853e9772..495e9c31 100644 --- a/frontend/AGENTS.md +++ b/frontend/AGENTS.md @@ -4,7 +4,7 @@ This area inherits `../AGENTS.md`. - Build a locally bundled Svelte UI. Keep `vite.config.js` output in `../.local/build/frontend`, relative asset URLs, no inline assets, and no production source maps unless a reviewed requirement changes them. - There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. That includes `call_devices` and `set_call_devices` (ADR-0065) for `CallWindowDevices.svelte`, but no device tests. Its load and save order (saves one at a time, none dropped, the newest sets the result) is in `src/callDevicePanel.ts`, which takes the bridge calls as arguments. The choice of the large video is pure logic in `src/callView.ts`: a pick of the viewer wins, a shared screen is large only when nothing is picked, and a feed that goes away drops its pick. Scale pictures with CSS only; never ask the core for a larger one. -- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. After each reading, handled or dropped, the bridge calls `call_stats_read` with the page count, so the host sends the next (it holds one in flight per page). The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs as escaped text. The details and the device panel are open one at a time (`openDevices`, `openStats`). +- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. After each reading, handled or dropped, the bridge calls `call_stats_read` with the page count, so the host sends the next (it holds one in flight per page). The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs and device IDs as escaped text. A table's caption is `CallStatsCaption.svelte`, which puts the user ID and the device ID each in its own ``. The details and the device panel are open one at a time (`openDevices`, `openStats`). - Put all Tauri API access in `src/bridge/index.ts` or another module under `src/bridge/`. Components use the typed bridge. Do not call `invoke`, Tauri globals, or host APIs directly from components. - Import public DTOs from `../crates/contracts/generated/contracts.ts`. Change Rust definitions and run the exporter when the DTO contract changes. TypeScript types do not validate runtime input or authorize commands. - Render names and message bodies as escaped text. Preserve bidirectional isolation in `src/Message.svelte`, `src/RoomList.svelte`, and `src/Timeline.svelte`. Do not use `{@html}`, HTML insertion APIs, automatic previews, or arbitrary remote images. diff --git a/frontend/src/CallStats.svelte b/frontend/src/CallStats.svelte index 342f1e88..6c23fd84 100644 --- a/frontend/src/CallStats.svelte +++ b/frontend/src/CallStats.svelte @@ -3,8 +3,8 @@ import type { CallStats } from '../../crates/contracts/generated/contracts'; import { startCallStats, stopCallStats } from './bridge'; import { STATS_FAILED_TEXT, STATS_LABEL, statsNote, statsSections } from './callStats'; + import CallStatsCaption from './CallStatsCaption.svelte'; import Icon from './Icon.svelte'; - import PersonName from './PersonName.svelte'; // The call's technical details (ADR-0066), shown while this panel exists: // mounting it turns the readings on, and destroying it turns them off, so a @@ -53,10 +53,7 @@ {:else} {#each sections as section (section.key)}
- + {#each section.rows as row (row.label)} diff --git a/frontend/src/CallStatsCaption.svelte b/frontend/src/CallStatsCaption.svelte new file mode 100644 index 00000000..9e037ef0 --- /dev/null +++ b/frontend/src/CallStatsCaption.svelte @@ -0,0 +1,14 @@ + + +{#if section.userId !== null}{#if section.deviceId !== null} + ({'device '}{section.deviceId}){/if}{:else}{section.title}{/if} diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts index 0766dc17..22f46b37 100644 --- a/frontend/src/bridge/index.ts +++ b/frontend/src/bridge/index.ts @@ -394,7 +394,8 @@ export async function watchSession( if (parsed !== null) onLevels(parsed); }); const page = await invoke('watch_session', { onChange: channel, onSoundLevel: soundLevel, onLevels: levels }); - statsPage = typeof page === 'number' && Number.isSafeInteger(page) && page >= 0 ? page : null; + // The host counts pages from 1, so 0 is no count. + statsPage = typeof page === 'number' && Number.isSafeInteger(page) && page >= 1 ? page : null; // The log may already be on (a reloaded page): follow it from now. await followDiagnostics(); } diff --git a/frontend/tests/bridge-calls.test.mjs b/frontend/tests/bridge-calls.test.mjs index b22ca3f8..6bb723ec 100644 --- a/frontend/tests/bridge-calls.test.mjs +++ b/frontend/tests/bridge-calls.test.mjs @@ -566,7 +566,7 @@ test('GIVEN a stale page count WHEN the host refuses the read of a reading THEN }); test('GIVEN no usable page count from the host WHEN the technical details are turned on THEN the start fails and asks nothing, and a stop asks nothing', async () => { - for (const reply of [null, -1, 1.5, '3', Number.MAX_SAFE_INTEGER + 2]) { + for (const reply of [null, 0, -1, 1.5, '3', Number.MAX_SAFE_INTEGER + 2]) { await watchAs(reply); const asked = []; mockIPC((command) => { diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs index 338754a0..9dd1880b 100644 --- a/frontend/tests/render.test.mjs +++ b/frontend/tests/render.test.mjs @@ -351,3 +351,22 @@ test('GIVEN the technical details panel WHEN it renders before a reading THEN it assert.match(body, /Waiting for the first reading\./); assert.doesNotMatch(body, /
- {#if section.userId !== null}{#if section.deviceId !== null} - ({section.deviceId}){/if}{:else}{section.title}{/if} -
{row.label}{row.value}
{ + const { default: CallStatsCaption } = await vite.ssrLoadModule('/src/CallStatsCaption.svelte'); + const section = (more) => ({ key: 'k', title: '', userId: null, deviceId: null, rows: [], ...more }); + const caption = (more) => render(CallStatsCaption, { props: { section: section(more) } }).body; + + const device = caption({ userId: '@bob:s', deviceId: 'PHONE' }); + assert.match(device, /@bob:s<\/bdi>/); + assert.match(device, /class="call-stats-device">\(device <\/span>PHONE<\/bdi>\)<\/span>/); + + // A right-to-left override in a device ID stays inside its own isolate. + const hostile = caption({ userId: '@eve:s', deviceId: '‮' }); + assert.match(hostile, /‮<img src=x onerror=alert\(1\)>?(>)?<\/bdi>\)<\/span>/); + assert.doesNotMatch(hostile, /|call-stats-device/); +}); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d2957eca..c5d15232 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -464,9 +464,11 @@ impl Subscriptions { self.stats().remove(label).is_some() } - /// The count of the page that the window `label` shows now. - fn page(&self, label: &str) -> u64 { - self.pages().get(label).copied().unwrap_or(0) + /// The count of the page that the window `label` shows now. `None` when + /// no page of the window was counted: counts start at 1, so no request + /// can match it. + fn page(&self, label: &str) -> Option { + self.pages().get(label).copied() } /// Counts a new page for the window `label` and drops its statistics @@ -484,7 +486,7 @@ impl Subscriptions { /// cannot come between them. fn keep_stats(&self, label: String, page: u64, channel: Channel) -> bool { let pages = self.pages(); - if pages.get(&label).copied().unwrap_or(0) != page { + if pages.get(&label).copied() != Some(page) { return false; } self.stats().insert( @@ -505,7 +507,7 @@ impl Subscriptions { /// come between them and give the new page's channel the old page's read. fn stats_read(&self, label: &str, page: u64) -> bool { let pages = self.pages(); - if pages.get(label).copied().unwrap_or(0) != page { + if pages.get(label).copied() != Some(page) { return false; } if let Some(entry) = self.stats().get_mut(label) { @@ -740,7 +742,7 @@ async fn call_stats( ) -> Result<(), String> { let label = webview.label().to_owned(); let _order = subscriptions.stats_order.lock().await; - if subscriptions.page(&label) != page { + if subscriptions.page(&label) != Some(page) { return Err(INVALID_ARGUMENT.to_owned()); } if !on { diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index 3cf28cc7..424c6d39 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -1393,6 +1393,14 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ } assert!(switches().is_empty()); + // Before its page is counted, the window has no count: page 0, which + // the map's default would give, is not one, so a start, a stop and a + // read are all refused and nothing reaches the core. + assert!(invoke_on(&call, "call_stats", app_origin(), stats_on(true, 0)).is_err()); + assert!(invoke_on(&call, "call_stats", app_origin(), stats_on(false, 0)).is_err()); + assert!(read(0).is_err()); + assert!(switches().is_empty()); + let page = new_page(); // A start that the core refuses keeps no channel. From f2649ea5e5888cda06b55de0b17a800e86e3adf1 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Wed, 25 Nov 2026 23:42:33 +0000 Subject: [PATCH 44/51] Escape the hostile device ID in its test, and drop a try that caught nothing The caption test writes the right-to-left override as an escape, not as the character, and requires the end of the escaped ID. Its comment now says that it checks the escaping and the wrapper only. The bridge's read note drops a try around an async call, which cannot throw before it returns. The stats start keeps its code string failure, the form that every bridge failure has, and says so for the analyser. Co-Authored-By: Claude Opus 5.5 --- frontend/src/bridge/index.ts | 14 +++++++------- frontend/tests/render.test.mjs | 8 +++++--- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts index 22f46b37..a3f86ef1 100644 --- a/frontend/src/bridge/index.ts +++ b/frontend/src/bridge/index.ts @@ -580,9 +580,11 @@ export async function startCallStats(onStats: (stats: CallStats) => void): Promi statsHandled(page); } }); + // The bridge fails with the host's code strings, as `invoke` does, and the + // page maps each code to its text, so this failure is a code too. await inStatsTurn(() => statsPage === null - ? Promise.reject('core_unavailable') + ? Promise.reject('core_unavailable') // NOSONAR: a host code string, not an Error : invoke('call_stats', { on: true, page: statsPage, onStats: channel }) ); } @@ -602,14 +604,12 @@ export async function stopCallStats(): Promise { // Tells the host that the page handled a statistics reading, so it sends the // next. Nothing waits for the answer: a reload makes the count stale, and the -// host refuses it, which is expected. +// host refuses it, which is expected. `invoke` is async, so every failure, +// also a bridge that is gone with the page, is a rejection that the catch +// takes. function statsHandled(page: number | null): void { if (page === null) return; - try { - invoke('call_stats_read', { page }).catch(() => undefined); - } catch { - // The bridge is gone with the page. - } + invoke('call_stats_read', { page }).catch(() => undefined); } // The page's count from `watch_session` (ADR-0066). The host takes a diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs index 9dd1880b..0b8b6df8 100644 --- a/frontend/tests/render.test.mjs +++ b/frontend/tests/render.test.mjs @@ -361,9 +361,11 @@ test('GIVEN statistics tables WHEN their captions render THEN a device shows its assert.match(device, /@bob:s<\/bdi>/); assert.match(device, /class="call-stats-device">\(device <\/span>PHONE<\/bdi>\)<\/span>/); - // A right-to-left override in a device ID stays inside its own isolate. - const hostile = caption({ userId: '@eve:s', deviceId: '‮' }); - assert.match(hostile, /‮<img src=x onerror=alert\(1\)>?(>)?<\/bdi>\)<\/span>/); + // A device ID with a right-to-left override and markup is escaped text in + // its own . The markup shows the escaping and the wrapper only, not how + // a browser draws the override. + const hostile = caption({ userId: '@eve:s', deviceId: '\u202e' }); + assert.match(hostile, /\u202e<img src=x onerror=alert\(1\)(?:>|>)<\/bdi>\)<\/span>/); assert.doesNotMatch(hostile, / Date: Thu, 26 Nov 2026 00:01:49 +0000 Subject: [PATCH 45/51] Read the statistics page count once, when the start's turn comes A start that waited for its turn read the page count twice: before the wait for its readings' acknowledgements, and after it for the host. A reload in between gave the host the new count and the acknowledgements the old one, which the host refuses, so no second reading came. The start now reads the count once in its turn and makes its channel there. Co-Authored-By: Claude Opus 5.5 --- frontend/src/bridge/index.ts | 35 +++++++++++++----------- frontend/tests/bridge-calls.test.mjs | 40 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 16 deletions(-) diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts index a3f86ef1..1e45fcf0 100644 --- a/frontend/src/bridge/index.ts +++ b/frontend/src/bridge/index.ts @@ -571,22 +571,26 @@ export function callCamera(on: boolean): Promise { * {@link stopCallStats}. */ export async function startCallStats(onStats: (stats: CallStats) => void): Promise { - const page = statsPage; - const channel = new Channel((value) => { - try { - const stats = parseCallStats(value); - if (stats !== null) onStats(stats); - } finally { - statsHandled(page); + await inStatsTurn(() => { + // Read when the turn comes, once: the host keeps the channel under the + // count of the start, so each reading is acknowledged with that count, + // also when a reload changed it while the start waited. + const page = statsPage; + if (page === null) { + // The bridge fails with the host's code strings, as `invoke` does, and + // the page maps each code to its text, so this failure is a code too. + return Promise.reject('core_unavailable'); // NOSONAR: a host code string, not an Error } + const channel = new Channel((value) => { + try { + const stats = parseCallStats(value); + if (stats !== null) onStats(stats); + } finally { + statsHandled(page); + } + }); + return invoke('call_stats', { on: true, page, onStats: channel }); }); - // The bridge fails with the host's code strings, as `invoke` does, and the - // page maps each code to its text, so this failure is a code too. - await inStatsTurn(() => - statsPage === null - ? Promise.reject('core_unavailable') // NOSONAR: a host code string, not an Error - : invoke('call_stats', { on: true, page: statsPage, onStats: channel }) - ); } /** @@ -607,8 +611,7 @@ export async function stopCallStats(): Promise { // host refuses it, which is expected. `invoke` is async, so every failure, // also a bridge that is gone with the page, is a rejection that the catch // takes. -function statsHandled(page: number | null): void { - if (page === null) return; +function statsHandled(page: number): void { invoke('call_stats_read', { page }).catch(() => undefined); } diff --git a/frontend/tests/bridge-calls.test.mjs b/frontend/tests/bridge-calls.test.mjs index 6bb723ec..36c978c9 100644 --- a/frontend/tests/bridge-calls.test.mjs +++ b/frontend/tests/bridge-calls.test.mjs @@ -600,6 +600,46 @@ test('GIVEN a statistics start still at the host WHEN the panel closes and opens assert.deepEqual(sent, [true, false, true]); }); +test('GIVEN a statistics start that waits for its turn WHEN a reload changes the page count meanwhile THEN the start and the reads of its readings both use the new count', async () => { + await watchAs(5); + let page = 5; + const calls = []; + let release; + const first = new Promise((resolve) => (release = resolve)); + mockIPC((command, args) => { + if (command === 'diagnostics_status') return { on: false, full: false, failed: false, available: true, path: null }; + if (command === 'watch_session') return page; + calls.push({ command, args }); + return calls.length === 1 ? first.then(() => null) : null; + }); + const startA = bridge.startCallStats(() => {}); + const startB = bridge.startCallStats(() => {}); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual( + calls.map((call) => call.args.page), + [5], + 'the first start is at the host, the second waits for its turn' + ); + page = 9; + const nothing = () => {}; + await bridge.watchSession(nothing, nothing, nothing, nothing, nothing, nothing, nothing, nothing); + release(); + await Promise.all([startA, startB]); + const starts = calls.filter((call) => call.command === 'call_stats'); + assert.deepEqual( + starts.map((call) => call.args.page), + [5, 9] + ); + const reading = { microphone: null, camera: null, screen: null, participants: [], connections: [] }; + starts[1].args.onStats.onmessage(reading); + const reads = calls.filter((call) => call.command === 'call_stats_read'); + assert.deepEqual( + reads.map((call) => call.args.page), + [9], + 'the reading is acknowledged with the count its channel is kept under' + ); +}); + test('GIVEN a statistics start that fails WHEN a stop follows THEN the stop is still sent', async () => { await watchAs(6); const sent = []; From 25c64c679b417b98d208e31f1a9d0a27f554c7f0 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 00:29:52 +0000 Subject: [PATCH 46/51] Close the details for another room's call, and refuse repeated stats keys first - The call window closes the technical details unless the next status is a call in the same room (`statsStayOpen`), so the panel never shows a reading of an earlier call. - The statistics readers refuse a repeated key before they read its value; a key seen as null still counts as seen. - The switch test reads the fake worker's queue, and the IPC permission tests count a page for the main window, so only the capability can refuse its start and read. - ADR-0066 states the writer order per round, both call window grants, the reading that a quick reopen can show once, the room rule, and that the participant limit applies after LiveKit's roster copy. Co-Authored-By: Claude Opus 5.5 --- crates/core-protocol/src/lib.rs | 131 +++++++++++++----- crates/core/src/calls/controller.rs | 23 ++- .../0066-show-call-statistics-on-request.md | 40 +++++- frontend/AGENTS.md | 2 +- frontend/src/CallWindow.svelte | 4 +- frontend/src/callWindow.ts | 12 +- frontend/tests/call-window.test.mjs | 20 ++- src-tauri/tests/ipc.rs | 35 +++-- 8 files changed, 210 insertions(+), 57 deletions(-) diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index 97380ba5..615b1453 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -1202,9 +1202,11 @@ fn call_stats_content<'de, D: serde::Deserializer<'de>>( } let mut stats = None; while let Some(Field::Stats) = map.next_key::()? { - if stats.replace(map.next_value::()?).is_some() { + // The key alone refuses a repeat: its value is not read. + if stats.is_some() { return Err(A::Error::duplicate_field("stats")); } + stats = Some(map.next_value::()?); } stats .map(|stats| stats.0) @@ -1293,38 +1295,47 @@ impl<'de> serde::de::Visitor<'de> for WireStats { } let (mut microphone, mut camera, mut screen) = (None, None, None); let (mut participants, mut connections) = (None, None); + // A repeated key is refused before its value is read. A key seen with + // the value `null` still counts as seen, so `Option>`. while let Some(field) = map.next_key::()? { - let fresh = match field { - Field::Microphone => microphone - .replace( + let seen = match field { + Field::Microphone => microphone.is_some(), + Field::Camera => camera.is_some(), + Field::Screen => screen.is_some(), + Field::Participants => participants.is_some(), + Field::Connections => connections.is_some(), + }; + if seen { + return Err(A::Error::custom("duplicate call statistics field")); + } + match field { + Field::Microphone => { + microphone = Some( map.next_value::>>()?, - ) - .is_none(), - Field::Camera => camera - .replace( + ); + } + Field::Camera => { + camera = Some( map.next_value::>>()?, - ) - .is_none(), - Field::Screen => screen - .replace( + ); + } + Field::Screen => { + screen = Some( map.next_value::>>()?, - ) - .is_none(), - Field::Participants => participants - .replace(map.next_value:: { + participants = Some(map.next_value::>()?) - .is_none(), - Field::Connections => connections - .replace(map.next_value::>()?); + } + Field::Connections => { + connections = Some(map.next_value::, { persephone_contracts::CALL_STATS_CONNECTIONS_MAX }, - >>()?) - .is_none(), - }; - if !fresh { - return Err(A::Error::custom("duplicate call statistics field")); + >>()?); + } } } let participants = participants.ok_or_else(|| A::Error::missing_field("participants"))?; @@ -1392,15 +1403,22 @@ impl<'de> Deserialize<'de> for WireParticipant { use serde::de::Error; let (mut user_id, mut device_id, mut audio, mut video) = (None, None, None, None); while let Some(field) = map.next_key::()? { - let fresh = match field { - Field::UserId => user_id.replace(map.next_value()?).is_none(), - Field::DeviceId => device_id.replace(map.next_value()?).is_none(), - Field::Audio => audio.replace(map.next_value()?).is_none(), - Field::Video => video.replace(map.next_value()?).is_none(), + // A repeated key is refused before its value is read. + let seen = match field { + Field::UserId => user_id.is_some(), + Field::DeviceId => device_id.is_some(), + Field::Audio => audio.is_some(), + Field::Video => video.is_some(), }; - if !fresh { + if seen { return Err(A::Error::custom("duplicate call statistics field")); } + match field { + Field::UserId => user_id = Some(map.next_value()?), + Field::DeviceId => device_id = Some(map.next_value()?), + Field::Audio => audio = Some(map.next_value()?), + Field::Video => video = Some(map.next_value()?), + } } Ok(WireParticipant { user_id: user_id.ok_or_else(|| A::Error::missing_field("userId"))?, @@ -4616,6 +4634,57 @@ mod timeline_events_wire_tests { ); } + /// GIVEN a repeated key whose second value is invalid WHEN read THEN the + /// repeat is refused by the key, not by the value: the error names the + /// duplicate, so the second value was never decoded. + #[test] + fn given_a_repeated_call_stats_key_with_a_bad_second_value_then_the_key_is_refused() { + let read = |json: &str| { + serde_json::from_str::(json) + .unwrap_err() + .to_string() + }; + let content = |stats: &str| format!(r#"{{"event":{{"call_stats":{stats}}}}}"#); + let valid = + r#"{"microphone":null,"camera":null,"screen":null,"participants":[],"connections":[]}"#; + // The content key `stats`. + let error = read(&content(&format!(r#"{{"stats":{valid},"stats":"bad"}}"#))); + assert!(error.contains("duplicate field `stats`"), "{error}"); + // An aggregate key. + let error = read(&content( + r#"{"stats":{"microphone":null,"microphone":"bad","camera":null,"screen":null,"participants":[],"connections":[]}}"#, + )); + assert!(error.contains("duplicate call statistics field"), "{error}"); + // A participant key. + let error = read(&content( + r#"{"stats":{"microphone":null,"camera":null,"screen":null,"connections":[], + "participants":[{"userId":"@a:example.org","userId":5,"deviceId":"D","audio":null,"video":null}]}}"#, + )); + assert!(error.contains("duplicate call statistics field"), "{error}"); + } + + /// GIVEN a key first read as `null` and then repeated WHEN read THEN it is + /// refused as a repeat: `null` is a value, not an unseen key. + #[test] + fn given_a_repeated_call_stats_key_after_null_then_it_is_refused_as_a_repeat() { + let read = |json: &str| { + serde_json::from_str::(json) + .unwrap_err() + .to_string() + }; + let error = read( + r#"{"event":{"call_stats":{"stats":{"microphone":null,"microphone":null,"camera":null, + "screen":null,"participants":[],"connections":[]}}}}"#, + ); + assert!(error.contains("duplicate call statistics field"), "{error}"); + let error = read( + r#"{"event":{"call_stats":{"stats":{"microphone":null,"camera":null,"screen":null, + "connections":[],"participants":[{"userId":"@a:example.org","deviceId":"D", + "audio":null,"audio":null,"video":null}]}}}}"#, + ); + assert!(error.contains("duplicate call statistics field"), "{error}"); + } + /// GIVEN call level events WHEN read THEN bounded ones are kept, and a /// level over the top, too many devices or an overlong ID is refused. #[test] diff --git a/crates/core/src/calls/controller.rs b/crates/core/src/calls/controller.rs index cb822fe4..49b4b457 100644 --- a/crates/core/src/calls/controller.rs +++ b/crates/core/src/calls/controller.rs @@ -7100,7 +7100,8 @@ mod tests { } /// GIVEN a running call WHEN its task runs THEN a switch of the statistics - /// reaches the worker once, and the same value is not sent again. + /// reaches the worker once, and the same value is not sent again. The + /// test reads what the worker gets, not only the `sent` flag. #[test] fn given_the_statistics_switch_when_applied_then_the_worker_gets_each_change_once() { let mut fixture = test_call( @@ -7108,17 +7109,31 @@ mod tests { Arc::new(Flags::default()), Arc::new(AtomicBool::new(false)), ); - let call = &mut fixture.call; + let (call, to_worker) = (&mut fixture.call, &mut fixture.to_worker); let mut sent = false; let mut pending = Some((Instant::now(), false)); assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); - assert!(pending.is_none() && !sent, "off to off is not sent"); + assert!(pending.is_none() && !sent); + assert!(to_worker.try_recv().is_err(), "off to off is not sent"); pending = Some((Instant::now(), true)); assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); assert!(pending.is_none() && sent); + assert!(matches!( + to_worker.try_recv(), + Ok(ToWorker::SetStats { on: true }) + )); pending = Some((Instant::now(), true)); assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); - assert!(sent, "on to on is not sent again"); + assert!(pending.is_none() && sent); + assert!(to_worker.try_recv().is_err(), "on to on is not sent again"); + pending = Some((Instant::now(), false)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(pending.is_none() && !sent); + assert!(matches!( + to_worker.try_recv(), + Ok(ToWorker::SetStats { on: false }) + )); + assert!(to_worker.try_recv().is_err(), "the off goes once"); } /// GIVEN a call alone for 30 seconds with a join that waits unread diff --git a/docs/adr/0066-show-call-statistics-on-request.md b/docs/adr/0066-show-call-statistics-on-request.md index f221b428..55d97bbb 100644 --- a/docs/adr/0066-show-call-statistics-on-request.md +++ b/docs/adr/0066-show-call-statistics-on-request.md @@ -37,9 +37,13 @@ Facts from the source on 25 November 2026: * The worker sends numbers only, with bounds that the receiver checks (ADR-0043). No free text, address or identifier beyond those that other messages already carry. -* Statistics never delay a control message or a picture, and never run in - the worker's event loop. -* The call window gets one new command and nothing else (ADR-0060). +* In each round of the worker's writer, statistics go after the control + messages and the waiting picture, and they never run in the worker's event + loop. A control message that comes while a reading is being written waits + for that one bounded write. +* The call window gets two new commands and nothing else (ADR-0060): + `call_stats`, the switch that reaches the core, and `call_stats_read`, + which only tells the host that the page handled a reading. ## Considered Options @@ -70,6 +74,15 @@ for the answer, and a reading is old when the page asks for it. * The core sends `ToWorker::SetStats { on }` to the worker on each change. The worker starts with them off. A full worker queue keeps the newest value for a retry, like the diagnostic switch (ADR-0058). +* The core sends a change only. When the page turns the details off and on + again while the call task is busy, the task can see only the newest value, + "on", and sends nothing: the worker never stopped, so its series and its + rates go on. When both changes reach the worker, it starts a new series, + whose first reading has no rates. A reading that the worker's writer took + before the off can still arrive after the on, and the core then shows it + once. It is a reading of the same call, taken before the off, and the next + reading replaces it. A series number in `SetStats` and `Stats` would let + the core drop it; this record does not add one. ### Worker @@ -109,7 +122,8 @@ for the answer, and a reading is old when the page asks for it. * The reading goes to `Output::offer_stats`. It never waits, it replaces a reading that has not gone out, and the writer writes it after the control messages and the waiting picture of its round. So at most one reading - waits, and it delays no control message. + waits. A control message that comes while the reading is being written + waits for that write, which the message limits bound. ### Message @@ -154,14 +168,20 @@ candidate type, SSRC, codec or other text. count. The page sends the count with each `call_stats`, and the host takes a start or stop only with the count of the page the window shows now. A request of a page that is gone fails and changes nothing. -* The capability `call` gains `allow-call-stats`, and nothing else. The - main window does not have it. +* The capability `call` gains `allow-call-stats` (the switch, which reaches + the core) and `allow-call-stats-read` (the page's acknowledgment, which + stays in the host and reaches no core), and nothing else. The main + window has neither. ### Page * A button "Technical details" (an icon button) in the call window controls opens a panel. The panel turns the details on when it opens and off when it closes, so closing, a closed window and an ended call all stop them. + The window closes the panel when the call ends and when a call in another + room replaces it (`statsStayOpen`), so the panel never shows a reading of + an earlier call. The call status has no call ID, so a new call in the + same room is told apart only by the end status between the two. Escape closes it. The bridge keeps the page's count from `watch_session` and sends it with each start and stop; with none, a start fails and a stop asks nothing. It sends the starts and stops one at a time, in the order @@ -178,12 +198,18 @@ candidate type, SSRC, codec or other text. * No cost while the panel is closed: no read, no message, no timer work. * The numbers cannot carry anything but numbers, and the page never sees an address. -* Control messages and pictures are not delayed. +* A reading goes after the control messages and the waiting picture of each + writer round, so it delays a control message by at most one bounded write. ### Negative Consequences * The reading takes up to a second to appear, and rates show as unknown until the second reading. +* Each read starts from LiveKit's copy of each room's participant map + (`Room::remote_participants`, one identity and two shared handles per + participant), and the limit of 32 applies after that copy. The level + meters take the same copy ten times a second. A bounded participant index + kept from room events would bound both; it is not part of this record. * An entry whose track has no statistics (a slow or failed read) is missing for that second. * A connection that has no track shows no numbers, because the worker reads diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md index 495e9c31..720af3dc 100644 --- a/frontend/AGENTS.md +++ b/frontend/AGENTS.md @@ -4,7 +4,7 @@ This area inherits `../AGENTS.md`. - Build a locally bundled Svelte UI. Keep `vite.config.js` output in `../.local/build/frontend`, relative asset URLs, no inline assets, and no production source maps unless a reviewed requirement changes them. - There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. That includes `call_devices` and `set_call_devices` (ADR-0065) for `CallWindowDevices.svelte`, but no device tests. Its load and save order (saves one at a time, none dropped, the newest sets the result) is in `src/callDevicePanel.ts`, which takes the bridge calls as arguments. The choice of the large video is pure logic in `src/callView.ts`: a pick of the viewer wins, a shared screen is large only when nothing is picked, and a feed that goes away drops its pick. Scale pictures with CSS only; never ask the core for a larger one. -- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. After each reading, handled or dropped, the bridge calls `call_stats_read` with the page count, so the host sends the next (it holds one in flight per page). The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs and device IDs as escaped text. A table's caption is `CallStatsCaption.svelte`, which puts the user ID and the device ID each in its own ``. The details and the device panel are open one at a time (`openDevices`, `openStats`). +- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. After each reading, handled or dropped, the bridge calls `call_stats_read` with the page count, so the host sends the next (it holds one in flight per page). The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs and device IDs as escaped text. A table's caption is `CallStatsCaption.svelte`, which puts the user ID and the device ID each in its own ``. The details and the device panel are open one at a time (`openDevices`, `openStats`). The call window closes the details when the call ends or a call in another room replaces it (`statsStayOpen` in `callWindow.ts`); keep that rule, because the panel starts its readings only when it mounts. - Put all Tauri API access in `src/bridge/index.ts` or another module under `src/bridge/`. Components use the typed bridge. Do not call `invoke`, Tauri globals, or host APIs directly from components. - Import public DTOs from `../crates/contracts/generated/contracts.ts`. Change Rust definitions and run the exporter when the DTO contract changes. TypeScript types do not validate runtime input or authorize commands. - Render names and message bodies as escaped text. Preserve bidirectional isolation in `src/Message.svelte`, `src/RoomList.svelte`, and `src/Timeline.svelte`. Do not use `{@html}`, HTML insertion APIs, automatic previews, or arbitrary remote images. diff --git a/frontend/src/CallWindow.svelte b/frontend/src/CallWindow.svelte index 5c4255fe..bc6a47ba 100644 --- a/frontend/src/CallWindow.svelte +++ b/frontend/src/CallWindow.svelte @@ -53,7 +53,7 @@ volumeText, volumeValue } from './calls'; - import { callGrid, ROSTER_LABEL, SelfClose, type CallCell } from './callWindow'; + import { callGrid, ROSTER_LABEL, SelfClose, statsStayOpen, type CallCell } from './callWindow'; import { AUTO_PICK, feedKeys, keepPick, largeKey, selectFeed, showAll, splitFeeds, type ViewPick } from './callView'; import CallWindowDevices from './CallWindowDevices.svelte'; import CallStatsPanel from './CallStats.svelte'; @@ -93,9 +93,9 @@ const selfClose = new SelfClose(() => void closeCallWindow().catch(() => {})); function take(next: CallStatus) { + if (!statsStayOpen(status, next)) statsOpen = false; status = next; selfClose.status(inCall(next), next.phase === 'ended'); - if (!inCall(next)) statsOpen = false; if (next.phase !== 'active') { ownLevel = 0; levels = new Map(); diff --git a/frontend/src/callWindow.ts b/frontend/src/callWindow.ts index 1effab25..0b3daa84 100644 --- a/frontend/src/callWindow.ts +++ b/frontend/src/callWindow.ts @@ -3,7 +3,7 @@ // names the video tile that shows its camera, or none, and then the window // shows a placeholder. User IDs are untrusted text for text rendering only. import type { CallStatus } from '../../crates/contracts/generated/contracts'; -import { deviceKey } from './calls.ts'; +import { deviceKey, inCall } from './calls.ts'; import { SCREEN_TILE } from './video.ts'; /** The heading of the participant list. */ @@ -66,6 +66,16 @@ export class SelfClose { } } +/** + * Whether the technical details panel stays open when `next` replaces + * `previous` (ADR-0066). It stays only while the same room's call goes on. + * The panel reads once, when it opens, so a call in another room must close + * it: it would keep the old call's last reading. + */ +export function statsStayOpen(previous: CallStatus, next: CallStatus): boolean { + return inCall(next) && next.roomId === previous.roomId; +} + /** Shown in the main window when the call window cannot open. */ export const CALL_WINDOW_UNAVAILABLE_TEXT = 'The call window could not open. The call goes on in this window.'; diff --git a/frontend/tests/call-window.test.mjs b/frontend/tests/call-window.test.mjs index cfa47970..16e3ac72 100644 --- a/frontend/tests/call-window.test.mjs +++ b/frontend/tests/call-window.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { CallWindowOpener, callGrid, SelfClose } from '../src/callWindow.ts'; +import { CallWindowOpener, callGrid, SelfClose, statsStayOpen } from '../src/callWindow.ts'; import { DEVICE_CHANGE_TEXT, DEVICE_TEST_LABEL, @@ -288,3 +288,21 @@ test('GIVEN an open that throws at once WHEN it is asked THEN that is a failed o await settled(); assert.deepEqual(reports, [true]); }); + +const inRoom = (roomId, phase) => ({ ...IDLE_CALL, phase, roomId }); + +for (const phase of ['joining', 'active']) { + test(`GIVEN details open for a call in room A WHEN a ${phase} status for room B comes THEN the panel closes`, () => { + assert.equal(statsStayOpen(inRoom('!a:s', 'active'), inRoom('!b:s', phase)), false); + }); +} + +test('GIVEN details open for a call in room A WHEN its status changes within the same call THEN the panel stays open', () => { + assert.equal(statsStayOpen(inRoom('!a:s', 'joining'), inRoom('!a:s', 'active')), true); + assert.equal(statsStayOpen(inRoom('!a:s', 'active'), inRoom('!a:s', 'active')), true); +}); + +test('GIVEN details open WHEN the call ends or goes idle THEN the panel closes', () => { + assert.equal(statsStayOpen(inRoom('!a:s', 'active'), { ...inRoom('!a:s', 'ended') }), false); + assert.equal(statsStayOpen(inRoom('!a:s', 'active'), IDLE_CALL), false); +}); diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs index 424c6d39..c5994000 100644 --- a/src-tauri/tests/ipc.rs +++ b/src-tauri/tests/ipc.rs @@ -1376,8 +1376,22 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ (at_core, release) }; - // The main window has no permission, so nothing reaches the core. - assert!(invoke_on(&main, "call_stats", app_origin(), stats_on(true, 0)).is_err()); + // The main window has no permission, so nothing reaches the core. Its + // page is counted first, so the request is valid apart from the window: + // only the capability can refuse it. + let main_page = invoke_on( + &main, + "watch_session", + app_origin(), + serde_json::json!({"onChange": "__CHANNEL__:13", "onSoundLevel": "__CHANNEL__:14", + "onLevels": "__CHANNEL__:15"}), + ) + .unwrap() + .as_u64() + .expect("watch_session gives the main page its count"); + let refused = invoke_on(&main, "call_stats", app_origin(), stats_on(true, main_page)); + assert!(refused.is_err()); + assert_ne!(refused, Err(serde_json::json!("invalid_argument"))); assert!(switches().is_empty()); // Not asked for: no channel, nothing is delivered. @@ -1533,16 +1547,17 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_ subscriptions.dispatch(Event::CallStats { stats: reading(13) }); assert_eq!(sent(13), 1); // A read of a page that is gone, or from the main window, changes nothing. + // The main window's read names its own counted page, so only the + // capability can refuse it. assert_eq!(read(page - 1), Err(serde_json::json!("invalid_argument"))); - assert!( - invoke_on( - &main, - "call_stats_read", - app_origin(), - serde_json::json!({"page": page}) - ) - .is_err() + let refused = invoke_on( + &main, + "call_stats_read", + app_origin(), + serde_json::json!({"page": main_page}), ); + assert!(refused.is_err()); + assert_ne!(refused, Err(serde_json::json!("invalid_argument"))); subscriptions.dispatch(Event::CallStats { stats: reading(14) }); assert_eq!(sent(14), 0, "the stale read did not free the page"); // With no statistics channel a read is fine and does nothing. From 7f90883fe4e2885572c3bcecad9c18b54fc977df Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 00:49:22 +0000 Subject: [PATCH 47/51] Count the call statistics commands and stale readings correctly The record said the option adds one command and that at most one stale reading reaches the page after a quick reopen. It adds two commands, and only the switch reaches the core. Readings can also wait in the core's queue of worker messages (64) while the call task is busy, so the page can show more than one. Co-Authored-By: Claude Opus 5.5 --- .../0066-show-call-statistics-on-request.md | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/docs/adr/0066-show-call-statistics-on-request.md b/docs/adr/0066-show-call-statistics-on-request.md index 55d97bbb..a4c85179 100644 --- a/docs/adr/0066-show-call-statistics-on-request.md +++ b/docs/adr/0066-show-call-statistics-on-request.md @@ -55,9 +55,11 @@ Facts from the source on 25 November 2026: ## Decision Outcome -Chosen option: "On request", because it costs nothing while closed, and one -switch is the smallest command surface. A pull command needs a second command -for the answer, and a reading is old when the page asks for it. +Chosen option: "On request", because it costs nothing while closed, and only +one of its two commands, the switch, reaches the core. The other, +`call_stats_read`, stays in the UI host and only paces the page. With a pull +command, each reading is a request that reaches the core and the worker, and +the worker must read for each request or keep the newest reading always. ### Switch @@ -78,11 +80,16 @@ for the answer, and a reading is old when the page asks for it. again while the call task is busy, the task can see only the newest value, "on", and sends nothing: the worker never stopped, so its series and its rates go on. When both changes reach the worker, it starts a new series, - whose first reading has no rates. A reading that the worker's writer took - before the off can still arrive after the on, and the core then shows it - once. It is a reading of the same call, taken before the off, and the next - reading replaces it. A series number in `SetStats` and `Stats` would let - the core drop it; this record does not add one. + whose first reading has no rates. Readings taken before the off can still + arrive after the on: the one that the worker's writer holds, and those that + wait in the core's queue of worker messages (`EVENT_QUEUE`, 64 messages of + every kind) while the call task is busy. The worker reads at most once a + second, so at most one reading waits for each second that the task is + busy. The core passes them on. The core and the UI host keep only the + newest waiting reading, but the page can still show more than one of them, + one after the other. Each is a reading of the same call, taken before the + off, and the next new reading replaces it. A series number in `SetStats` + and `Stats` would let the core drop them; this record does not add one. ### Worker @@ -223,7 +230,8 @@ candidate type, SSRC, codec or other text. ### On request * Good, because it costs nothing while closed. -* Good, because one command and one event are all it adds. +* Good, because it adds one event and two commands, and only one of the + commands (the switch) reaches the core. * Bad, because the first reading takes a second. ### Always on @@ -235,8 +243,9 @@ candidate type, SSRC, codec or other text. ### Pull command * Good, because the page paces itself. -* Bad, because it needs a second command in the call window, and the worker - has to read for each request or keep the newest reading always. +* Bad, because each reading is a request that reaches the core and the + worker, and the worker has to read for each request or keep the newest + reading always. ## Links From ba0388b5684b1ca0dfdd1a455ae3fec8fbafce0e Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 00:55:25 +0000 Subject: [PATCH 48/51] Refuse call protocol version 12 after the merge The old-version test still expected version 12, which the merge raised to 13. It now expects 13 and refuses 6 to 12, so a worker or core of PR 102's version 12 is refused. Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/call-protocol/src/lib.rs b/crates/call-protocol/src/lib.rs index fa07148b..8c98b8d8 100644 --- a/crates/call-protocol/src/lib.rs +++ b/crates/call-protocol/src/lib.rs @@ -3680,13 +3680,13 @@ mod tests { ); } - /// GIVEN a message of the previous wire versions (6 to 11) + /// GIVEN a message of the previous wire versions (6 to 12) /// WHEN it is decoded in either direction /// THEN the version is refused. #[test] fn given_older_wire_versions_when_decoded_then_they_are_refused() { - assert_eq!(VERSION, 12); - for old in [6, 7, 8, 9, 10, 11] { + assert_eq!(VERSION, 13); + for old in [6, 7, 8, 9, 10, 11, 12] { assert_eq!( ToWorker::decode(&[old, TO_LEAVE]), Err(DecodeError::UnknownVersion) From 1c425cf0ca4f8e75cf5a38e0cd2ee1d127c759b7 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 00:57:02 +0000 Subject: [PATCH 49/51] Expect call protocol version 13 in the tile limit test Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/call-protocol/src/lib.rs b/crates/call-protocol/src/lib.rs index 8c98b8d8..28e703c6 100644 --- a/crates/call-protocol/src/lib.rs +++ b/crates/call-protocol/src/lib.rs @@ -3202,7 +3202,7 @@ mod tests { /// 640x360 at 15 per second. #[test] fn given_tiles_when_limits_asked_then_screen_differs_from_camera() { - assert_eq!((VIDEO_TILES, SCREEN_TILE, VERSION), (6, 5, 12)); + assert_eq!((VIDEO_TILES, SCREEN_TILE, VERSION), (6, 5, 13)); assert_eq!(MAX_SCREEN_BYTES, 3_686_400); assert_eq!(MAX_SCREEN_PIXELS, 921_600); for tile in 0..SCREEN_TILE { From cfa1b80b110369667ceed59dd8c234af068e1161 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 01:16:13 +0000 Subject: [PATCH 50/51] Close the details when a new call follows an ended one in the same room `statsStayOpen` checked only that the next status was in a call in the same room. An ended call followed by a new call in that room then kept the panel and the old call's reading. Both statuses must now be in a call. `take()` already closed the panel on the ended status, so this was latent, but the helper's rule was wrong and untested. Co-Authored-By: Claude Opus 5.5 --- frontend/src/callWindow.ts | 9 +++++---- frontend/tests/call-window.test.mjs | 7 +++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/frontend/src/callWindow.ts b/frontend/src/callWindow.ts index 0b3daa84..691d50dd 100644 --- a/frontend/src/callWindow.ts +++ b/frontend/src/callWindow.ts @@ -68,12 +68,13 @@ export class SelfClose { /** * Whether the technical details panel stays open when `next` replaces - * `previous` (ADR-0066). It stays only while the same room's call goes on. - * The panel reads once, when it opens, so a call in another room must close - * it: it would keep the old call's last reading. + * `previous` (ADR-0066). It stays only while the same room's call goes on: + * both statuses are in a call, in the same room. The panel reads once, when + * it opens, so a call in another room, or a new call after an ended one in + * the same room, must close it: it would keep the old call's last reading. */ export function statsStayOpen(previous: CallStatus, next: CallStatus): boolean { - return inCall(next) && next.roomId === previous.roomId; + return inCall(previous) && inCall(next) && next.roomId === previous.roomId; } /** Shown in the main window when the call window cannot open. */ diff --git a/frontend/tests/call-window.test.mjs b/frontend/tests/call-window.test.mjs index 16e3ac72..5b6e618c 100644 --- a/frontend/tests/call-window.test.mjs +++ b/frontend/tests/call-window.test.mjs @@ -306,3 +306,10 @@ test('GIVEN details open WHEN the call ends or goes idle THEN the panel closes', assert.equal(statsStayOpen(inRoom('!a:s', 'active'), { ...inRoom('!a:s', 'ended') }), false); assert.equal(statsStayOpen(inRoom('!a:s', 'active'), IDLE_CALL), false); }); + +test('GIVEN an ended call in room A WHEN a new call in room A comes THEN the panel closes', () => { + for (const phase of ['joining', 'active']) { + assert.equal(statsStayOpen(inRoom('!a:s', 'ended'), inRoom('!a:s', phase)), false); + } + assert.equal(statsStayOpen(IDLE_CALL, inRoom('!a:s', 'joining')), false); +}); From 5b41701721cb997a7658416ddbaff421c473ffa2 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 01:36:18 +0000 Subject: [PATCH 51/51] Say that the caller, not the stats writer, leaves out bad entries Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/call-protocol/AGENTS.md b/crates/call-protocol/AGENTS.md index a8c60561..76ace3e7 100644 --- a/crates/call-protocol/AGENTS.md +++ b/crates/call-protocol/AGENTS.md @@ -16,7 +16,7 @@ This crate defines the bounded binary messages between the key-holding core and - Devices and levels (ADR-0059): wire version 10 added `ToWorker::TestDevice { test, device }` (a first message only, like `ListDevices`; `DeviceTest` is a closed set), `ToWorker::SetDevices { recording, playout, camera }` (the camera choice applies from the next camera start; `DevicesSet` answers for the microphone and speaker only), `FromWorker::ParticipantLevel { connection, identity, level }`, `FromWorker::ParticipantMuted { connection, identity, muted }` and `FromWorker::DevicesSet { failure }` (0 for none, else a `FailureCode`). `SoundLevel` is now the own microphone's level. - Microphone settings (ADR-0062): wire version 11 added `ToWorker::SetMicrophone { auto_level, mic_gain }` (tag 16, no answer), and `Join` ends with `auto_level` and `mic_gain` (two bytes). `Reader::mic_gain` refuses a gain over `MAX_MIC_GAIN_PERCENT` (400) or off the step of `MIC_GAIN_STEP_PERCENT` (5); use `valid_mic_gain` wherever a gain is used. - Screen targets (ADR-0053 amendment of 25 November 2026, ADR-0064): wire version 12 changed `SetScreen`'s `ScreenTarget::Monitor` (tag 2) from a list index to the Windows GDI device name (`MonitorName`: a length byte, then 1 to `MAX_MONITOR_NAME` (32) printable ASCII bytes other than space: 0x21 to 0x7E, `u8::is_ascii_graphic`; a name with a space is an invalid value), the width and height, and the monitor's rectangle (`DesktopRect`: four big-endian `i32` edges, each side 1 to `MAX_MONITOR_SIDE`, each edge within `MAX_DESKTOP_COORDINATE` of 0), and added `ScreenTarget::Display { id, width, height }` (tag 3, the macOS CoreGraphics display ID, never 0). `Reader::monitor_size` refuses a side outside 1 to `MAX_MONITOR_SIDE`. Tag 1 (`Portal { node }`) is unchanged. -- Call statistics (ADR-0066): wire version 13 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer leaves out entries past the limits. Tag 16 and wire version 11 are the microphone settings above (ADR-0062). The next wire change takes tag 18 and the next free version. The `MAX_STATS_*` bounds are repeated as `CALL_STATS_*` in `crates/contracts`; `crates/core/src/calls/stats.rs` checks at compile time that they match. +- Call statistics (ADR-0066): wire version 13 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer cuts each list to its limit and writes every entry as given; the caller (`mapping::stats` in the worker) leaves out an entry that the reader would refuse and clamps the numbers, because the reader refuses the whole message for one such entry. Tag 16 and wire version 11 are the microphone settings above (ADR-0062). The next wire change takes tag 18 and the next free version. The `MAX_STATS_*` bounds are repeated as `CALL_STATS_*` in `crates/contracts`; `crates/core/src/calls/stats.rs` checks at compile time that they match. - Coordinate wire changes with `crates/core` and `crates/call-worker` (planned), and bump the version byte. ## Checks