Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(native): fail closed on sender gate evidence (#75)
AAAf35f08d44d34
diff --git a/docs/adr/0006-fixed-high-native-sender-canary.md b/docs/adr/0006-fixed-high-native-sender-canary.mdindex ac5a4bf4..58935b16 100644--- a/docs/adr/0006-fixed-high-native-sender-canary.md+++ b/docs/adr/0006-fixed-high-native-sender-canary.md@@ -89,10 +89,11 @@ One separately authorized second run then used that frozen gate with the samebounded local topology. Its retained ledger proves `getDisplayMedia` request andresolution, Host admission and room creation, Host WSS authentication, localbridge readiness and fixed-`HIGH` config acceptance, exactly one encoder object,-and entry into the first WebCodecs output callback. It retained zero Go-`framesWritten`, source-RTP packets, and source-RTP bytes, so it stopped at-`sender-start` and never created a Viewer. No retry or threshold adjustment-followed. Cleanup completed before final failure: Chrome and Native exited, the+and entry into the first WebCodecs output callback. It serialized zero media+counters without retaining whether any diagnostics arrived, so those values do+not prove that Go reported zero. It stopped at `sender-start` and never created+a Viewer. No retry or threshold adjustment followed. Cleanup completed before+final failure: Chrome and Native exited, theNode server and all three loopback ports closed, and the exact task Chromeprofile passed the non-reparse audit and was removed.@@ -110,28 +111,22 @@ while the app context is active, any close other than normal or going-away emitsone `fatal` with the fixed sanitized message `local media bridge read failed`.Focused tests prove the abnormal classification without its underlying closereason and prove normal close and app shutdown do not misreport. This is a real-P1 bridge-read failure fix, but it does not classify the retained zero counters+P1 bridge-read failure fix, but it does not classify the missing diagnosticsor prove a framing defect.-One authorized post-fix revalidation then ran the frozen gate exactly once on-exact source `86386b75d01919b213f5725467e495cdd0aa9a54`, fixed VP8 `HIGH`,-Chrome 151, one in-memory local room, and peer assistance disabled. Its flushed-ledger reached sequence 6 and retained capture request/resolution, Host-admission/create/WSS, local bridge readiness and config acceptance, first-encoded output, one encoder object, bridge generation 1, and one binary send-attempt that returned synchronously without a throw. Go retained zero frames,-source-RTP packets, and source-RTP bytes, so the first failed stage was-`sender-start` and no Viewer was created. Chrome, Native, Node, all task ports,-and the exact task profile then cleaned up before the result was finalized. No-retry, threshold change, H.264, second Viewer, FIFO, or production run followed.+One authorized evidence-clarification revalidation then ran the corrected gate+exactly once with the same fixed VP8 `HIGH`, Chrome 151, one in-memory local room,+and peer assistance disabled. It retained the same start sequence through one+generation-1 binary send return, then observed no diagnostics or post-send+diagnostics, zero encoder errors, and at least one sanitized fatal marker. Its+media-counter zeros are initial ledger values, not Go reports. The first failed stage remained+`sender-start`, no Viewer was created, and cleanup passed 5/5. No retry,+threshold change, H.264, second Viewer, FIFO, or production run followed.The result remains `no-go-unclassified`. It proves the first product binary-send returned, narrowing the retained interval to after that return and before-Go frame accounting. It does not prove Go read or decode, and the fixed bridge-fatal is not part of this failure ledger, so no raw cause may be inferred. A-separate minimal diagnostic or fix slice must classify this interval before any-further Chrome run. There is still no Viewer, two-viewer, FIFO, or physical or-hardware-encoder proof.+send returned, but the retained fatal marker and missing diagnostics do not prove+where or why the product path stopped. No raw cause may be inferred. There is+still no Viewer, two-viewer, FIFO, or physical or hardware-encoder proof.## Staged Revalidationdiff --git a/docs/project-memory.md b/docs/project-memory.mdindex 9b21f626..6093c01c 100644--- a/docs/project-memory.md+++ b/docs/project-memory.md@@ -23,7 +23,7 @@ Last updated: 2026-08-20- Use direct host P2P for one or two viewers. Keep ADR-0004 off broadly; use an isolated exact-room candidate until resource, quality, recovery, SFU/UDP, bounded-failure, and browser/mobile gates pass.- Browser relays resend remote `MediaStreamTrack` values and re-encode at each hop; WebRTC does not guarantee a shared encoder across peer connections, so measure the cost.- Keep experiments bounded: the standard representation sequence is below; native RTP relay, encoded-object striping, and FEC remain separate.-- ADR-0006 stays no-go: one post-fix run retained VP8 output and one first-generation binary `send()` return, but Go frame/RTP stayed zero, so no Viewer was created; cleanup passed and no retry followed. The fixed bridge fatal was not retained, so the break after browser send return and before Go accounting remains unclassified. A separate MF fixture proved RTX H.264 hardware over 360/360 frames, but `42c01f` misses Pion's default fmtp; Viewer interop remains unproven. Native v2 stays memory-only and leaves SQLite/Web unchanged.+- ADR-0006 stays no-go: one evidence-clarification run retained VP8 output and one first-generation binary `send()` return, then no post-send diagnostics and at least one sanitized fatal marker. The media-counter zeros are initial values, not Go reports; no Viewer was created, cleanup passed 5/5, and no product root cause is proven. A separate MF fixture proved RTX H.264 hardware over 360/360 frames, but `42c01f` misses Pion's default fmtp; Viewer interop remains unproven. Native v2 stays memory-only and leaves SQLite/Web unchanged.- Mobile Web Host is unsupported; feature-detect and fail clearly. Mobile Viewer stays leaf-only. After Windows native, gate Android 14+; iOS waits for stable iOS 27 ScreenCaptureKit.- ADR-0005 accepts direct/peer UDP, bounded SFU roots, then optional selected-edge TURN. The built-in participant-wide candidate failed its real direct acceptance before forced relay and rolled back completely; it is rejected as the product path. Production advertises STUN-only ICE.- Keep the controller exact-room only: room `1` is the STUN/SFU smoke. Preserve sticky progressing P2P, mobile leaves and break-before-make. Recovery spends one attempt per layer (ICE restart, same-parent rebuild, alternate peer, then SFU), never three identical retries; active SFU gets one fresh grant before Peer failback.diff --git a/docs/research/native-shared-encode-sender.md b/docs/research/native-shared-encode-sender.mdindex 08d713f2..f116bbdc 100644--- a/docs/research/native-shared-encode-sender.md+++ b/docs/research/native-shared-encode-sender.md@@ -266,9 +266,10 @@ did not retry or adjust a threshold. Its append-and-flush ledger reached sequenc7 and retained positive booleans for capture request/resolution, Host admission,private room creation, Host WSS authentication, bridge readiness, fixed VP81280x720@30/3 Mbps config acceptance, one encoder object, and entry into the-first WebCodecs output callback. Go diagnostics remained at zero-`framesWritten`, source-RTP packets, and source-RTP bytes. The runner therefore-failed closed at `sender-start`; it never created the Viewer page and did not+first WebCodecs output callback. The ledger serialized zero media counters but+did not retain whether diagnostics arrived, so those values do not prove that+Go reported zero. The runner failed closed at `sender-start`; it never created+the Viewer page and did notexercise Viewer auth, SDP/ICE, Pion bound-edge output, decode/render, a secondViewer, or FIFO. Cleanup was complete before the report was finalized: Chromeand Native exited, the isolated Node listener and all three random loopback@@ -296,32 +297,19 @@ post-config close, normal close, and app shutdown. All Go tests, vet, Windowsamd64 no-CGO build, TypeScript typecheck, and the relevant bridge probe/ledgertests pass.-One authorized post-fix run then used exact source-`86386b75d01919b213f5725467e495cdd0aa9a54` and the unchanged tracked gate-exactly once. Its fixed VP8 1280x720@30, 3 Mbps, one-Viewer boundary used Chrome-151, one in-memory loopback room, and no peer assistance. Preflight had passed-the 411-test Node suite, typecheck, both builds, all Go tests, vet, a Windows-gate build, and the 11 focused ledger/generation/cleanup tests.--The append-and-flush ledger reached sequence 6. It retained capture request and-resolution, Host admission, private room creation, Host WSS authentication,-bridge readiness, fixed-`HIGH` config acceptance, first WebCodecs output, one-encoder object, bridge generation 1, and the first observed binary `super.send()`-returning synchronously; it retained no observed synchronous throw. The ledger-does not count later sends. Go still reported-zero frames, source-RTP packets, and source-RTP bytes. The gate therefore failed-at `sender-start` and did not create a Viewer. It did not run Viewer signaling,-SDP/ICE, Pion bound-edge output, decode/render, H.264, a second Viewer, FIFO, or-production. No retry or threshold change followed.--Cleanup completed before final failure: Chrome and Native exited, Node and all-task ports closed, and the exact task profile was audited and removed. The-pre-existing historical task-profile count did not increase. The result remains-`no-go-unclassified`: it narrows the retained interval to after the first-product binary `send()` returned and before Go frame accounting, but does not-prove Go read or decode. The fixed bridge fatal is not retained by this failure-ledger, so no underlying close or raw cause may be inferred. A separate minimal-diagnostic or fix slice must classify this interval before another Chrome run.+One authorized evidence-clarification run then used the corrected tracked gate+exactly once with the same fixed VP8 1280x720@30, 3 Mbps, one-Viewer boundary,+Chrome 151, one in-memory loopback room, and no peer assistance. It retained the+start sequence through one generation-1 binary `super.send()` return, then+observed no diagnostics or post-send diagnostics, zero encoder errors, and at+least one sanitized fatal marker. The media-counter zeros are initial ledger+values, not Go reports. The gate failed at `sender-start` and did not create a Viewer.++Cleanup passed 5/5 before final failure. No retry, threshold change, H.264,+second Viewer, FIFO, or production run followed. The result remains+`no-go-unclassified`: the fatal marker and missing diagnostics do not prove where+or why the product path stopped, so no underlying close or raw cause may be+inferred.The frozen probe continues to bind the first actual local media WebSocket asgate-local generation 1. A second bridge generation saturates at 2, stopsdiff --git a/docs/status.md b/docs/status.mdindex 98922ad2..6290963c 100644--- a/docs/status.md+++ b/docs/status.md@@ -35,7 +35,7 @@ and is not part of production.- Host A+B and authenticated P2P Viewer C are sanitized, generation-bound, read-only, and fail closed for stale, ambiguous, or SFU-fed evidence; no raw media metadata is retained.- SVC is `no-go-web-svc-cross-path-hardware-contract`: no direct/peer selection, cross-PC shared encode, or portable hardware proof; pinned screen share is `L1T3`. No browser run was warranted.- The `a11a73d` built-in TURN canary is rejected: local allocation passed, but direct Host/Pion Viewer failed before forced relay. Full rollback restored STUN-only client ICE and zero allocations.-- Native remains no-go after one post-fix gate: fixed VP8, one encoder and one generation-1 binary send returned, but Go frame/RTP stayed zero; no Viewer was created. Cleanup passed; no retry followed. The fixed bridge fatal was not retained, so the send-to-Go interval and MF H.264 Viewer interop remain unproven.+- Native remains no-go: fixed VP8, one encoder and a generation-1 binary send returned; no later diagnostics arrived, a sanitized fatal marker was retained, and the media zeros are initial values rather than Go reports. No Viewer was created, cleanup passed 5/5, and no product root cause is proven.- Access protocol/config/HTTP/storage/SQLite/signaling focused tests pass, including commit-first teardown and v1 rollback.## Unverified Boundaries@@ -60,8 +60,9 @@ The recovery target uses one ICE restart, one same-parent rebuild, one alternateSFU; it never runs three identical retries or abandons progressing P2P early.Next gate exactly-two/Dynacast-off BWE on a zero-child SFU leaf, then root-evacuation. Native is stopped after browser send return but zero Go frame/RTP;-classify that interval in a separate fix slice before any new run.+evacuation. Native stopped after one binary send return: no later diagnostics,+a retained fatal marker, and uninterpretable media zeros. Classify this boundary+before any new run.Audio A/B/C may proceed without displacing P0.Ordinary Peer ICE stays STUN-only. Participant-wide TURN source and wire areremoved; stale `PEER_ICE_TURN_*` keys fail startup even blank. Selected-edge TURNdiff --git a/scripts/native-one-viewer-gate-core.ts b/scripts/native-one-viewer-gate-core.tsindex da6a7c11..3e38c2d9 100644--- a/scripts/native-one-viewer-gate-core.ts+++ b/scripts/native-one-viewer-gate-core.ts@@ -27,6 +27,11 @@ export interface BridgeSendEvidence {binarySendFailed: number;}+export interface CriticalSenderEvidence {+ encoderErrors: number;+ fatalEvents: number;+}+export interface OneViewerIdentity {socketOrdinal: number;authGeneration: number;@@ -87,6 +92,23 @@ export function retainsFirstBridgeSend(evidence: BridgeSendEvidence): boolean {evidence.binarySendSucceeded > 0 && evidence.binarySendFailed === 0;}+export function hasNoCriticalSenderErrors(evidence: CriticalSenderEvidence): boolean {+ return evidence.encoderErrors === 0 && evidence.fatalEvents === 0;+}++export async function verifyFinalSenderEvidence<T extends CriticalSenderEvidence>(+ sample: () => Promise<T>,+ retain: (evidence: T) => CriticalSenderEvidence,+): Promise<boolean> {+ try {+ const evidence = await sample();+ const retained = retain(evidence);+ return hasNoCriticalSenderErrors(evidence) && hasNoCriticalSenderErrors(retained);+ } catch {+ return false;+ }+}+export function withDeadline<T>(operation: () => Promise<T>,deadline: number,diff --git a/scripts/native-one-viewer-gate.ts b/scripts/native-one-viewer-gate.tsindex 0535b50b..8f9183af 100644--- a/scripts/native-one-viewer-gate.ts+++ b/scripts/native-one-viewer-gate.ts@@ -25,10 +25,12 @@ import {captureOneViewerIdentity,fetchJsonBefore,finalizeGate,+ hasNoCriticalSenderErrors,isExactGateProfile,retainsFirstBridgeSend,retainsOneViewerIdentity,waitForSample,+ verifyFinalSenderEvidence,withDeadline,type CleanupResult,type OneViewerIdentity,@@ -68,6 +70,9 @@ interface SenderSnapshot {binarySendAttempts: number;binarySendSucceeded: number;binarySendFailed: number;+ diagnosticsObserved: boolean;+ postSendDiagnosticsObserved: boolean;+ postSendDiagnosticsSequence: number;activeViewers: number;maxPeers: number;config: {@@ -236,9 +241,16 @@ function senderStartObservation(snapshot: SenderSnapshot): Partial<SenderStartObbinarySendSucceeded: snapshot.binarySendSucceeded,binarySendFailed: snapshot.binarySendFailed,encoderInstances: snapshot.encoderInstances,- framesWritten: snapshot.media?.framesWritten ?? 0,- sourceRtpPacketsWritten: snapshot.media?.sourceRtpPacketsWritten ?? 0,- sourceRtpBytesWritten: snapshot.media?.sourceRtpBytesWritten ?? 0,+ diagnosticsObserved: snapshot.diagnosticsObserved,+ postSendDiagnosticsObserved: snapshot.postSendDiagnosticsObserved,+ postSendDiagnosticsSequence: snapshot.postSendDiagnosticsSequence,+ encoderErrors: snapshot.encoderErrors,+ fatalEvents: snapshot.fatalEvents,+ ...(snapshot.media === null ? {} : {+ framesWritten: snapshot.media.framesWritten,+ sourceRtpPacketsWritten: snapshot.media.sourceRtpPacketsWritten,+ sourceRtpBytesWritten: snapshot.media.sourceRtpBytesWritten,+ }),};}@@ -282,6 +294,7 @@ async function main(): Promise<void> {let appPort: number | null = null;let debugPort: number | null = null;let nativePort: number | null = null;+ let senderPage: PageHandle | null = null;let gateSucceeded = false;const senderLedger = new SenderStartLedger((record) => {if (!ledgerPath) return;@@ -351,18 +364,19 @@ async function main(): Promise<void> {report.failedStage = "sender-start";await createPage(cdp, animatedSourceUrl());- const senderPage = await createPage(cdp, launchUrl, senderProbe());- await evaluate<void>(cdp, senderPage, `(() => {+ const activeSenderPage = await createPage(cdp, launchUrl, senderProbe());+ senderPage = activeSenderPage;+ await evaluate<void>(cdp, activeSenderPage, `(() => {document.querySelector('#server-url').value = ${JSON.stringify(baseUrl)};document.querySelector('#password').value = ${JSON.stringify(accessKey)};document.querySelector('#start').click();})()`, Date.now() + 5_000);await waitForSenderStart(- async (deadline) => senderStartObservation(await senderSnapshot(cdp!, senderPage, deadline)),+ async (deadline) => senderStartObservation(await senderSnapshot(cdp!, activeSenderPage, deadline)),senderLedger,{ timeoutMs: 20_000 },);- const senderReady = await senderSnapshot(cdp, senderPage, Date.now() + 3_000);+ const senderReady = await senderSnapshot(cdp, activeSenderPage, Date.now() + 3_000);const senderStartChecks = {oneEncoderObject: senderReady.encoderInstances === 1,currentBridge: retainsFirstBridgeSend(senderReady),@@ -371,7 +385,7 @@ async function main(): Promise<void> {report.stages["sender-start"] = { ...senderLedger.snapshot(), ...senderStartChecks };requireChecks(senderStartChecks);report.failedStage = "node-host";- const inviteUrl = await evaluate<string>(cdp, senderPage,+ const inviteUrl = await evaluate<string>(cdp, activeSenderPage,`document.querySelector('#invite-link').href`, Date.now() + 3_000);const invite = new URL(inviteUrl);const roomId = invite.pathname.match(/^\/r\/([1-9][0-9]{0,11})$/)?.[1] ?? "";@@ -388,7 +402,7 @@ async function main(): Promise<void> {let identity: OneViewerIdentity | null = null;await waitForSample(async (deadline) => ({viewer: await viewerSnapshot(cdp!, viewerPage, deadline),- sender: await senderSnapshot(cdp!, senderPage, deadline),+ sender: await senderSnapshot(cdp!, activeSenderPage, deadline),}), ({ viewer, sender }) => {identity = captureOneViewerIdentity(viewer.identity, senderIdentity(sender));const checks = {@@ -427,14 +441,14 @@ async function main(): Promise<void> {const mediaBaselineDeadline = Date.now() + 3_000;const [beforeViewer, beforeSender] = await Promise.all([viewerSnapshot(cdp, viewerPage, mediaBaselineDeadline),- senderSnapshot(cdp, senderPage, mediaBaselineDeadline),+ senderSnapshot(cdp, activeSenderPage, mediaBaselineDeadline),]);if (!retainsOneViewerIdentity(identity, beforeViewer.identity, senderIdentity(beforeSender))) {throw new Error("Viewer generation changed before media sampling");}await waitForSample(async (deadline) => ({viewer: await viewerSnapshot(cdp!, viewerPage, deadline),- sender: await senderSnapshot(cdp!, senderPage, deadline),+ sender: await senderSnapshot(cdp!, activeSenderPage, deadline),}), ({ viewer, sender }) => {const checks = {inboundPackets: viewer.packetsReceived > beforeViewer.packetsReceived,@@ -466,18 +480,34 @@ async function main(): Promise<void> {};return Object.values(checks).every(Boolean);}, 10_000);- const finalSender = await senderSnapshot(cdp, senderPage, Date.now() + 3_000);- const finalChecks = { finalBridge: retainsFirstBridgeSend(finalSender) };+ const finalSender = await senderSnapshot(cdp, activeSenderPage, Date.now() + 3_000);+ const finalChecks = {+ finalBridge: retainsFirstBridgeSend(finalSender),+ finalCriticalErrors: hasNoCriticalSenderErrors(finalSender),+ };report.stages["viewer-media"] = { ...report.stages["viewer-media"], ...finalChecks };requireChecks(finalChecks);gateSucceeded = true;} catch {// The bounded report retains only the first stage and sanitized counters.} finally {+ let finalSenderEvidence = false;+ const finalCdp = cdp;+ const finalSenderPage = senderPage;+ if (finalCdp && finalSenderPage) {+ finalSenderEvidence = await verifyFinalSenderEvidence(+ () => senderSnapshot(finalCdp, finalSenderPage, Date.now() + 1_000),+ (snapshot) => {+ senderLedger.record(senderStartObservation(snapshot));+ return senderLedger.snapshot();+ },+ );+ }report.stages["sender-start"] = {...report.stages["sender-start"],...senderLedger.snapshot(),};+ gateSucceeded = gateSucceeded && finalSenderEvidence;await finalizeGate(report, gateSucceeded, () => cleanupRun({cdp, native, chrome, server, profile,ports: [appPort, debugPort, nativePort].filter((port): port is number => port !== null),@@ -493,6 +523,8 @@ export function senderProbe(): string {ready: 0, configAccepted: 0,encoderInstances: 0, encoderOutputs: 0, encoderErrors: 0, fatalEvents: 0,bridgeGeneration: 0, binarySendAttempts: 0, binarySendSucceeded: 0, binarySendFailed: 0,+ diagnosticsObserved: false, postSendDiagnosticsObserved: false,+ postSendDiagnosticsSequence: 0,activeViewers: 0, maxPeers: 0, edgeGeneration: 0, activeEdgeSlot: null,config: null, media: null, peers: [] };const finite = (value) => Number.isFinite(value) ? value : 0;@@ -523,11 +555,16 @@ export function senderProbe(): string {let message; try { message = JSON.parse(event.data); } catch { return; }if (message.kind === 'ready') state.ready += 1;if (message.kind === 'config-accepted') state.configAccepted += 1;- if (message.kind === 'fatal') state.fatalEvents += 1;+ if (message.kind === 'fatal') mark('fatalEvents');if (message.kind === 'ready' || message.kind === 'viewer-count') {state.activeViewers = finite(message.activeViewers);}if (message.kind === 'diagnostics') {+ state.diagnosticsObserved = true;+ if (state.binarySendSucceeded > 0) {+ state.postSendDiagnosticsObserved = true;+ state.postSendDiagnosticsSequence = Math.min(2, state.postSendDiagnosticsSequence + 1);+ }state.media = message.media ? {framesWritten: finite(message.media.framesWritten),sourceRtpPacketsWritten: finite(message.media.sourceRtpPacketsWritten),@@ -581,7 +618,7 @@ export function senderProbe(): string {const init = args[0] || {};const wrapped = { ...init,output: (...values) => { state.encoderOutputs += 1; return init.output(...values); },- error: (...values) => { state.encoderErrors += 1; return init.error(...values); },+ error: (...values) => { mark('encoderErrors'); return init.error(...values); },};const encoder = Reflect.construct(Target, [wrapped], Target);state.encoderInstances += 1;diff --git a/scripts/native-one-viewer-ledger.ts b/scripts/native-one-viewer-ledger.tsindex e6210040..c25b511b 100644--- a/scripts/native-one-viewer-ledger.ts+++ b/scripts/native-one-viewer-ledger.ts@@ -12,6 +12,11 @@ export interface SenderStartObservation {binarySendSucceeded: number;binarySendFailed: number;encoderInstances: number;+ diagnosticsObserved: boolean;+ postSendDiagnosticsObserved: boolean;+ postSendDiagnosticsSequence: number;+ encoderErrors: number;+ fatalEvents: number;framesWritten: number;sourceRtpPacketsWritten: number;sourceRtpBytesWritten: number;@@ -38,6 +43,11 @@ const initialObservation: SenderStartObservation = {binarySendSucceeded: 0,binarySendFailed: 0,encoderInstances: 0,+ diagnosticsObserved: false,+ postSendDiagnosticsObserved: false,+ postSendDiagnosticsSequence: 0,+ encoderErrors: 0,+ fatalEvents: 0,framesWritten: 0,sourceRtpPacketsWritten: 0,sourceRtpBytesWritten: 0,@@ -52,6 +62,8 @@ const booleanKeys = ["bridgeConnected","fixedHighConfigured","firstEncodedChunk",+ "diagnosticsObserved",+ "postSendDiagnosticsObserved",] as const;const counterKeys = [@@ -67,6 +79,7 @@ const counterKeys = [// The first positive value is enough for this stage and bounds the append-only// ledger to at most one record per field transition.const counterLimit = 1_000_000_000;+const singleEventCounterKeys = ["encoderErrors", "fatalEvents"] as const;export class SenderStartLedger {private observation = { ...initialObservation };@@ -85,6 +98,14 @@ export class SenderStartLedger {next[key] = Math.min(Math.floor(value), counterLimit);}}+ for (const key of singleEventCounterKeys) {+ if (typeof patch[key] === "number" && patch[key] > 0) next[key] = 1;+ }+ const diagnosticsSequence = patch.postSendDiagnosticsSequence;+ if (typeof diagnosticsSequence === "number" && Number.isFinite(diagnosticsSequence) &&+ diagnosticsSequence > next.postSendDiagnosticsSequence) {+ next.postSendDiagnosticsSequence = Math.min(Math.floor(diagnosticsSequence), 2);+ }const bridgeGeneration = patch.bridgeGeneration;if (typeof bridgeGeneration === "number" && Number.isFinite(bridgeGeneration) &&bridgeGeneration > next.bridgeGeneration) {@@ -109,6 +130,7 @@ export function senderStartComplete(record: SenderStartObservation): boolean {return booleanKeys.every((key) => record[key]) && record.encoderInstances === 1 &&record.bridgeGeneration === 1 && record.binarySendAttempts > 0 &&record.binarySendSucceeded > 0 && record.binarySendFailed === 0 &&+ record.postSendDiagnosticsSequence > 0 &&record.framesWritten > 0 && record.sourceRtpPacketsWritten > 0;}diff --git a/tests/native-one-viewer-gate-core.test.ts b/tests/native-one-viewer-gate-core.test.tsindex 1d502e85..d7cb16fb 100644--- a/tests/native-one-viewer-gate-core.test.ts+++ b/tests/native-one-viewer-gate-core.test.ts@@ -7,10 +7,12 @@ import {captureOneViewerIdentity,fetchJsonBefore,finalizeGate,+ hasNoCriticalSenderErrors,isExactGateProfile,retainsFirstBridgeSend,retainsOneViewerIdentity,waitForSample,+ verifyFinalSenderEvidence,type CleanupResult,type SenderIdentityEvidence,type ViewerIdentityEvidence,@@ -35,13 +37,23 @@ interface BridgeProbeSnapshot {binarySendAttempts: number;binarySendSucceeded: number;binarySendFailed: number;+ diagnosticsObserved: boolean;+ postSendDiagnosticsObserved: boolean;+ postSendDiagnosticsSequence: number;+ fatalEvents: number;}class ProbeWebSocket {failBinary = false;+ private readonly listeners = new Map<string, Array<(event: { data: unknown }) => void>>();constructor(..._args: unknown[]) {}- addEventListener(..._args: unknown[]): void {}+ addEventListener(type: string, listener: (event: { data: unknown }) => void): void {+ this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]);+ }+ emitMessage(data: unknown): void {+ for (const listener of this.listeners.get("message") ?? []) listener({ data });+ }send(value: unknown): void {if (this.failBinary && value instanceof ArrayBuffer) throw new Error("not retained");}@@ -84,11 +96,21 @@ describe("native one-viewer gate invariants", () => {const first = new successful.WebSocket("ws://127.0.0.1/media");first.send("config");first.send(new ArrayBuffer(1));+ first.emitMessage(JSON.stringify({ kind: "diagnostics", media: {+ framesWritten: 0, sourceRtpPacketsWritten: 0, sourceRtpBytesWritten: 0,+ } }));+ first.emitMessage(JSON.stringify({ kind: "diagnostics", media: null }));+ first.emitMessage(JSON.stringify({ kind: "fatal" }));+ first.emitMessage(JSON.stringify({ kind: "fatal" }));expect(successful.snapshot()).toMatchObject({bridgeGeneration: 1,binarySendAttempts: 1,binarySendSucceeded: 1,binarySendFailed: 0,+ diagnosticsObserved: true,+ postSendDiagnosticsObserved: true,+ postSendDiagnosticsSequence: 2,+ fatalEvents: 1,});const replacement = new successful.WebSocket("ws://127.0.0.1/media");@@ -129,6 +151,27 @@ describe("native one-viewer gate invariants", () => {}).toEqual({ viewerSignal: false, viewerMedia: false, finalSuccess: false });});+ it("fails final sender evidence closed on late critical markers or sample failure", async () => {+ const cleanSender = { fatalEvents: 0, encoderErrors: 0 };+ expect(hasNoCriticalSenderErrors(cleanSender)).toBe(true);+ await expect(verifyFinalSenderEvidence(+ async () => ({ ...cleanSender, fatalEvents: 1 }),+ (evidence) => evidence,+ )).resolves.toBe(false);+ await expect(verifyFinalSenderEvidence(+ async () => cleanSender,+ () => ({ ...cleanSender, encoderErrors: 1 }),+ )).resolves.toBe(false);+ await expect(verifyFinalSenderEvidence(+ async () => { throw new Error("snapshot unavailable"); },+ (evidence) => evidence,+ )).resolves.toBe(false);+ await expect(verifyFinalSenderEvidence(+ async () => cleanSender,+ (evidence) => evidence,+ )).resolves.toBe(true);+ });+it("bounds Chrome version headers and body with one abort deadline", async () => {vi.useFakeTimers();try {diff --git a/tests/native-one-viewer-ledger.test.ts b/tests/native-one-viewer-ledger.test.tsindex 77c535ca..e4f28aba 100644--- a/tests/native-one-viewer-ledger.test.ts+++ b/tests/native-one-viewer-ledger.test.ts@@ -27,6 +27,9 @@ describe("native one-viewer sender-start ledger", () => {binarySendAttempts: 1,binarySendSucceeded: 1,encoderInstances: 1,+ diagnosticsObserved: true,+ postSendDiagnosticsObserved: true,+ postSendDiagnosticsSequence: 1,framesWritten: 4,},];@@ -61,11 +64,17 @@ describe("native one-viewer sender-start ledger", () => {binarySendSucceeded: 1,binarySendFailed: 0,encoderInstances: 1,+ diagnosticsObserved: true,+ postSendDiagnosticsObserved: true,+ postSendDiagnosticsSequence: 1,+ encoderErrors: 0,+ fatalEvents: 0,framesWritten: 4,sourceRtpPacketsWritten: 0,sourceRtpBytesWritten: 0,});- expect(JSON.stringify(committed)).not.toMatch(/token|url|ip|sdp|error/i);+ expect(JSON.stringify(committed)).not.toMatch(/token|url|ip|sdp/i);+ expect(committed.flatMap(Object.values).every((value) => typeof value !== "string")).toBe(true);});it("fails closed and bounds evidence when the bridge generation changes", () => {@@ -83,6 +92,11 @@ describe("native one-viewer sender-start ledger", () => {binarySendAttempts: Number.MAX_SAFE_INTEGER,binarySendSucceeded: Number.MAX_SAFE_INTEGER,encoderInstances: 1,+ diagnosticsObserved: true,+ postSendDiagnosticsObserved: true,+ postSendDiagnosticsSequence: 99,+ encoderErrors: 99,+ fatalEvents: 99,framesWritten: 1,sourceRtpPacketsWritten: 1,});@@ -94,6 +108,9 @@ describe("native one-viewer sender-start ledger", () => {binarySendAttempts: 1_000_000_000,binarySendSucceeded: 1_000_000_000,binarySendFailed: 1,+ postSendDiagnosticsSequence: 2,+ encoderErrors: 1,+ fatalEvents: 1,});expect(senderStartComplete({ ...snapshot, binarySendFailed: 0 })).toBe(false);expect(senderStartComplete({ ...snapshot, bridgeGeneration: 1 })).toBe(false);