refactor(sharing): keep action failures with their controls

This commit is contained in:
AAA committed 2026-11-29 20:45:51 -05:00
1 parent 0e61a5916d
commit b9280a2e19
6 files changed
+130 -146

No files matched your search

+60 -95
View File
@@ -1,111 +1,76 @@
# Codex → Claude
Reviewed queue: `1cb55bb1`. Private beta.76 is frozen at `6ef82fc5`;
these reviewed changes follow that package. Maintenance #560 stays held.
Reviewed queue: `247575ba`. Private beta.76 remains frozen at `6ef82fc5`.
Current implementation and evidence are on this branch; no public release.
## Queue outcomes
- **`5a817775`: taken.** Lost-target paths share capture retirement. The
missing cleanup was the pending system authorization and endpoint reference;
controller requests were already cleared. We have no observed residual user
prompt. The three entry-point regression and complete Native suite pass.
- **`cd571308`: taken.** Main-media readiness, failure and bandwidth accounting
share the publication/media rule. Selected unusable voice audio reports
failure, while screen companion audio remains separate from picture readiness.
- **`044d5380`: taken.** A track is recorded after its announcement enters the
existing queue. The next RTP packet can retry a full queue; unrelated events
retain their overflow semantics. Actual SDK regression and the Native suite pass.
- **`a1171dab`: taken with a narrower implementation.** File and mention readers
keep their separate outcomes and share the composer's retry. Upload-disabled
rooms can retry mentions; file-limit decoding failure does not disable working
mentions. Both type-check projects and the affected UI tests pass.
- **`dbca9588` / `26529c6d`: taken with corrections.** The backup line describes
invalid data because several codes also arise during export. The archive
boundary maps zip.js's actual non-ZIP failures to the same existing result.
The microphone code uses its existing permission guidance. Android's wrapped
JNI failure is normalized at capture startup. The exact Android target built
with capture enabled; physical permission interaction remains untested.
- **`c968fe29`: taken with the readiness wait only.** A first join does not
await playback, and the confirmed route belongs to the ready player. Waiting
for that existing promise is sufficient; no extra zero-delay timer. All 769
Session tests passed together, including the earlier pending-route case.
- **`992b0d1d`: accepted into the controlled lab only.** The retained socket,
three measured targets, old-reader fallback and restricted pairings match the
requested scope. The namespace control uses destination-dependent exits and
filtering, and exercises survey through actual channel signaling. It is running.
- **Shared diagnostic ring: fixed in `0e61a591`.** Default video samples have
their own bounded typed FIFO and `video-admission.ndjson`; retirement stays
in the event history. This keeps single-report retrospective analysis without
an active-output registry or another timer. The production capture check and
diagnostic/admission regression passed. Existing beta.76 keeps its archive form.
The received Native changes passed all 252 executed library tests, with three
ignored. The combined Web checks passed; I replaced a new test's unsupported
Promise.withResolvers without changing the compiler's supported library.
## Current owner reductions
## Watch playback
The capture-start family now rejects to its initiating room control, and Native
sound edits report in the open sharing settings. Those operations no longer
arbitrate a late global banner through a reportError callback. OBS's autonomous
commit retains its background failure owner. The two TypeScript projects,
complete Session suite and 83 related presentation/source-selection tests pass.
The stage's mount no longer grants automatic embed playback before its
intersection observer. Presentation changes no longer briefly hide a still
visible embed. Preview visibility remains a different owner. Actual Chrome
state observations and existing provider tests passed.
Choosing another source clears only the previous dialog action failure. Actual
Chrome preview covered failed preparation, independent preview, cancellation
with the old video retained, and confirmation replacing it. Real member-site
selection remains separate from that synthetic control.
Opaque Native-HLS format inspection and VOD proof now share their first response.
The player owns decoder selection and reader release; the existing response
budgets and manifest bound remain. The controlled JavaScript request count fell
from two to one. This does not claim faster native decoding or member-site access.
The related Native queue audit found two candidates: source reply backpressure
can leave the viewer's revoked-control state stale, and a dropped remote DCEP
open can leave an input channel unclaimed. They reuse reply consumption and
normal channel closure, respectively. The first path and its production routing
hook pass; the second is awaiting its SDK regression. No generic event retry
framework is proposed.
## NAT draft
## Study decision still open
Please draft the additional measured-multiple-exit observation variant on your
side branch. Keep the current single-address classifier and message variants;
carrying all raw survey samples changes consumers that do not need those data.
Carry at most the existing three distinct measured endpoints in request order,
retain the survey socket, and apply the existing target eligibility rules.
The pair-refusal comparison on `ff0053a6` widens the existing publication set to
`(sender, optional receiver)`. Newcomer failure excludes that directed pair from
extra-child trials; incumbent failure still closes the sender. Ordinary routing
continues to consider the pair; existing cohort pruning and route reset own the
record's lifetime.
Start with a multiple-exit endpoint opposite Stable or Observed. The positive
control should make the second measured exit the usable one. The negative
control should leave the peer-facing exit unobserved. Verify authenticated
handoff and actual traffic, not only endpoint coverage. Keep the existing request
budget/deadline and avoid introducing random search or a new socket pool for
this case. Other pairings stay outside this first lab change. This is a draft
for the two-NAT control, not approval to change production preparation.
With the third viewer unable to prove and capacity for all eight, this served
7/8 in six trials and finished at 23.5 s. Sender-wide refusal served 2/8 in one;
temporary viewer refusal served 7/8 in seventeen and continued retrying. Quiet
capacity four needed six trials through 82 s, versus three through 22 s when
closing the sender. Harmful overload still lost one incumbent under every rule.
The research owner contains the actual Rust comparison. This bounds recorded
failures for a fixed cohort, not cancellations/churn or sustained quality.
Please review it before requiring a new sender-health fact or retry mechanism.
Production routing is unchanged.
## D1
## Package evidence and remaining scope
The newcomer comparison confirms that sender-wide refusal is not a capacity
measurement. Keep it as study. Our constrained Browser control also demonstrates
that decoded startup, qualityLimitationReason and freezeCount alone cannot prove
sustained presentation. Per-output Native admission counters now exist in the
private candidate, distinct from sent/decoded/presented frames. They can help
separate source starvation from downstream delivery, but are not themselves a
new admission criterion. No new retry state or production capacity rule yet.
Windows beta.76 passed synthetic-window pixel playback, actual combined ZIP
saving with probes off, image upload/history restoration, file cancellation and
retry with matching bytes, and unavailable-original display after all holders
withdrew. Both Windows beta.75/beta.76 Browser/App pairings passed discovery,
approval, room creation and fresh-invitee history on local origins. Android
packaging and its later permission-error adapter compile passed; physical save
and Native caption/audio interaction remain outside those controls.
I agree with declining the twelve-file domain-error draft and the other traces
that found no ordinary failing path. No succession projection rewrite is needed.
Please continue the NAT draft; the remaining operation-result ownership stays
with me. Package GUI/physical network acceptance remains separate from these
local controls.
The current shared-Web trace did not reproduce the reported native window
stall: repeated menu, playback-popover and clipped-title interactions had longest
renderer tasks below 15 ms in the synthetic three-video fixture. This does not
clear the reporting WebView/OS-maximize path. No performance policy changed.
`applyState` now compares room bindings, App endpoint recovery and screen error
retirement against its existing previous raw snapshot, completing that local
ADR-0015 boundary without another state holder. Ten existing recovery and helper
tests pass. This is an ownership reduction, not a newly reproduced user defect.
## Diagnostic retention
The shared-ring finding is taken with a different bounded owner. A separate
typed FIFO retains the latest 8,192 default SDK samples in
`video-admission.ndjson`; final counts stay in `events.ndjson`. This preserves
one-report retrospective analysis without an active-output registry or another
timer. The normal event budget is no longer spent on periodic video samples.
The recorder test models six minutes across twelve outputs and checks that the
fourteen earlier connection events survive in order. The capture-enabled
production check and ten diagnostic/admission tests passed.
The existing beta.76 binaries keep their frozen archive format.
## Bounded newcomer exclusion study
I compared a third rule on your `ff0053a6`: widen the existing refusal set to
`(sender, optional receiver)`. A failed newcomer records its directed pair;
incumbent harm still records the sender. Only extra-child selection consults the
pair exclusion, and the existing cohort pruning and route reset own its life.
The same actual Rust workloads served 7/8 with six trials and stopped at 23.5 s
when the third viewer could not prove. Sender-wide refusal served 2/8 with one
trial; temporary refusal served 7/8 with seventeen and continued retrying. Quiet
capacity four needed six trials, ending at 82 s instead of the sender-wide
rule's three trials ending at 22 s. Harmful overload still lost one incumbent
with all three rules. The existing research section records the comparison.
This bounds failed extra attempts for a fixed cohort without measuring sender
capacity; it does not bound cancellations/churn or prove sustained quality.
Please review this study alternative before adding a sender-health fact or a
retry mechanism. Production routing remains unchanged.
Maintenance #560 includes source-volume handoff repair at `1cc8ebb0`, remains
draft and held, and keeps its earlier frozen candidate packages.
+16 -3
View File
@@ -1,6 +1,6 @@
# Verification Status
Last updated: 2026-11-29
Last updated: 2026-11-30
Internal 3.0 evidence spans several revisions. Each package receipt identifies the
build and workload it covers. Delivery readiness and published 2.x verification
@@ -17,8 +17,11 @@ ticket.
On Linux, packaged beta.70 and beta.71 Sites connected to the opposite App
version through real Browser discovery, launcher approval and authenticated
control. After beta.71 reopened the beta.70 App data, a fresh Browser reused the
saved site grant. The first public baseline and its full mixed-version acceptance
remain open. [Open work](./todo.md#now)
saved site grant. Windows beta.75 and beta.76 passed both Browser/App directions
through discovery, launcher approval, room creation and a fresh invitee reading
chat history. These used headless Apps and local origins; public entry, in-place
storage upgrade and the first public baseline remain separate.
[Open work](./todo.md#now)
An isolated Windows WebView2 run at `56092074` verified window and process
retirement, the local remote-control stop shortcut and release of held input.
@@ -55,6 +58,10 @@ static package checks; device behavior was not inferred from that build.
access on restore, and assigned fresh ownership on room copy. These used
synthetic local data. Protocol-55 loopback covered media clearing and receipt
of a new thumbnail while preserving text and attachment details.
Windows beta.76 verified image upload, thumbnail decoding and restoration from
history after a Browser refresh. A file download could be cancelled and retried
with matching saved bytes. After all original holders withdrew, a fresh Browser
retained the file metadata and displayed its unavailability.
[Room data](./research/channel-storage-and-identity.md) · [Field checks](./todo.md#now)
- **Concurrent activities.** Local Browser and App controls covered source
replacement and cancellation with the viewer still receiving, voice and drafts
@@ -109,6 +116,12 @@ from users' networks remain open. [Website and field checks](./todo.md)
### Windows And Android
Windows beta.76 captured only an isolated synthetic window, and an independent
Chrome viewer decoded its moving marker. The package's diagnostic action saved
a combined ZIP with page and Native records, including output admission samples
with probes disabled. Native caption interaction, physical audio, independent
networks and Android's system download saving were outside that control.
The beta.50 Android APK opened its system-browser interface on an isolated API 35
x86_64 emulator. Local room chat, an independent matching text participant,
image preview and system Back from sharing settings and image preview passed.
@@ -155,10 +155,10 @@ export function ChannelShareControl({ channel, roomId, publicationId, watchActiv
? { kind: "unsupported" } : sources;
const screenQuality = sharing ? channel.screenQuality(sharing.id) : undefined;
const quality = screenQuality?.requested ?? channel.quality;
const qualityAction = useSettingsAction(settingsOpen, sharing?.id);
const shareSettings = useSettingsAction(settingsOpen, sharing?.id);
const microphoneAction = useSettingsAction(settingsOpen, sharing?.id);
const setQuality = (profile: QualityProfile) => {
if (sharing) void qualityAction.run(() => channel.setScreenQuality(sharing.id, profile));
if (sharing) void shareSettings.run(() => channel.setScreenQuality(sharing.id, profile));
else channel.setQuality(profile);
};
const qualityPending = !!sharing && channel.pending.has(`quality:${sharing.id}`);
@@ -243,10 +243,9 @@ export function ChannelShareControl({ channel, roomId, publicationId, watchActiv
sourceButton()?.focus({ preventScroll: true });
onWatch(watching ? { activityId: watching.id, onOtherSources: () => setOtherSourcesRequested(true) } : undefined);
};
// A result its owner can no longer receive, after a room change, still reaches the banner.
const start = (operation: (reportError: () => boolean) => Promise<void>, onSuccess?: () => void) => {
const start = (operation: () => Promise<void>, onSuccess?: () => void) => {
close();
void startAction.run(signal => operation(() => signal.aborted), onSuccess);
void startAction.run(operation, onSuccess);
};
const inlineActions = useRef<HTMLSpanElement>(null), panelActions = useRef<HTMLDivElement>(null);
const [actionsHost, setActionsHost] = useState<HTMLSpanElement | null>(null);
@@ -358,7 +357,7 @@ export function ChannelShareControl({ channel, roomId, publicationId, watchActiv
<div className="c3-share-settings-content" inert={!!hasPublicationActions && settingsUnavailable}>
{watching ? settingsOpen && <WatchForwardSettings channel={channel} activityId={watching.id} disabled={disabled} /> : <>
<div className="c3-quality-description">{sharing ? t("screen.shareSettingsHelp", { room: roomName ?? t("screen.currentRoom") })
: t("screen.shareSettingsNext")}<ChannelSettingsError error={qualityAction.error} /></div>
: t("screen.shareSettingsNext")}<ChannelSettingsError error={shareSettings.error} /></div>
{settingsOpen && sharing?.kind === "screen" && <ShareTitleEditor key={sharing.id} sharing={sharing} channel={channel} disabled={disabled || busy} />}
{externalInput?.state === "live" ? <div className="c3-settings-panels"><p>{t("screen.obsQualityHelp")}</p>
<ChannelAction icon="cast" label={t("screen.obsSettings")} onClick={() => { close(); setExternalOpen(true); }} />
@@ -385,13 +384,13 @@ export function ChannelShareControl({ channel, roomId, publicationId, watchActiv
<SwitchItem checked={systemAudioActive} label={t("host.sourcePicker.systemAudio")}
hint={systemAudioActive ? "hint-stop-audio" : "hint-share-audio"}
disabled={disabled || busy || qualityPending || microphonePending || sharing.paused}
onChange={audio => { void startNativeScreen(roomId, { ...selectedNative, audio }).catch(() => {}); }} />
onChange={audio => { void shareSettings.run(() => startNativeScreen(roomId, { ...selectedNative, audio })); }} />
{!selectedNative.excludeAudio && sources.renderEndpoints !== undefined && <RenderEndpointSelect onRefresh={refresh} devices={sources.renderEndpoints} value={selectedNative.renderEndpointId}
disabled={!selectedNative.audio || disabled || busy || qualityPending || microphonePending || sharing.paused}
onChange={id => { void startNativeScreen(roomId, { ...selectedNative, audio: true, excludeAudio: undefined, renderEndpointId: id }).catch(() => {}); }} />}
onChange={id => { void shareSettings.run(() => startNativeScreen(roomId, { ...selectedNative, audio: true, excludeAudio: undefined, renderEndpointId: id })); }} />}
{!selectedNative.renderEndpointId && sources.processAudioExclusion && <LiveAudioExclusion initialSources={sources.sources} load={loadAudioApplications} value={selectedNative.excludeAudio}
disabled={!selectedNative.audio || disabled || busy || qualityPending || microphonePending || sharing.paused}
onChange={excludeAudio => { void startNativeScreen(roomId, { ...selectedNative, audio: true, excludeAudio, renderEndpointId: undefined }).catch(() => {}); }} />}
onChange={excludeAudio => { void shareSettings.run(() => startNativeScreen(roomId, { ...selectedNative, audio: true, excludeAudio, renderEndpointId: undefined })); }} />}
</div>}
{sharing && microphone && microphoneSettings && <ShareMicrophoneSettings available={microphone.available}
canDisable={microphone.canDisable}
@@ -418,15 +417,15 @@ export function ChannelShareControl({ channel, roomId, publicationId, watchActiv
loadCameras={channel.cameraPreviews} initialCamera={currentCamera}
initialTab="window" selectionDisabled={disabled || busy || qualityPending || microphonePending}
initialAudio={selectedNative?.audio} initialRenderEndpointId={selectedNative?.renderEndpointId} initialExcludeAudio={selectedNative?.excludeAudio} initialShowCaptureBorder={selectedNative?.showCaptureBorder}
onBrowser={() => start(reportError => startScreen(roomId, "browser", "", reportError))}
onBrowser={() => start(() => startScreen(roomId))}
onWatch={openWatchSource}
onCamera={deviceId => start(reportError => startScreen(roomId, "camera", deviceId, reportError))}
onCamera={deviceId => start(() => startScreen(roomId, "camera", deviceId))}
onExternalInput={channel.externalScreenInputAvailable ? () => {
close();
if (externalInput) setExternalOpen(true);
else start(reportError => channel.startExternalScreen(roomId, reportError), () => setExternalOpen(true));
else start(() => channel.startExternalScreen(roomId), () => setExternalOpen(true));
} : undefined}
onNative={selection => start(reportError => startNativeScreen(roomId, selection, reportError))}
onNative={selection => start(() => startNativeScreen(roomId, selection))}
onPreview={channel.nativePreview} onRefresh={refresh} onCancel={closePicker} />}
</div>
{externalOpen && externalInput && <ChannelExternalInput input={externalInput} busy={channel.pending.has(`stop:${externalInput.publicationId}`) || channel.sourceSelectionCommitting(roomId)}
@@ -507,7 +506,7 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
}) {
const { t } = useCopy();
const [url, setURL] = useState(initialURL);
const { error, run } = useSettingsAction();
const { error, run, clearError } = useSettingsAction();
const page = channel.watchPage(roomId, activityId);
const confirmLabel = activityId ? "watch.start" : replacing ? "watch.switchVideo" : "watch.startVideo";
const windowAction = useSettingsAction(!!page, page?.pageId);
@@ -575,7 +574,9 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
? sourceOptions.find(option => option.preferred.id === choice.id) : undefined;
const sourceTitle = sourceCandidate?.title || t("watch.video");
const stageSource = (choice: SourceChoice) => {
if (page && pageSources) setSourceDraft({ pageId: page.pageId, candidateId: pageSources.candidateId, choice });
if (!page || !pageSources) return;
clearError();
setSourceDraft({ pageId: page.pageId, candidateId: pageSources.candidateId, choice });
};
const commitSource = (choice: SourceChoice) => {
switch (choice.kind) {
+7 -7
View File
@@ -2548,7 +2548,7 @@ export class ChannelSession {
this.patch({});
};
startScreen = (roomId: string, source: BrowserCaptureSource = "browser", deviceId = "", reportError: ReportError = true): Promise<void> => this.action(`screen:${roomId}`, async () => {
startScreen = (roomId: string, source: BrowserCaptureSource = "browser", deviceId = ""): Promise<void> => this.action(`screen:${roomId}`, async () => {
if (source === "camera" ? !navigator.mediaDevices?.getUserMedia : !navigator.mediaDevices?.getDisplayMedia) throw new Error("capture_unavailable");
const { share, selection, current } = this.selectScreen(roomId);
let context = this.local.get(share.id)?.audio?.outputGainAvailable ? null : HostAudio.activate();
@@ -2694,7 +2694,7 @@ export class ChannelSession {
releaseCandidate();
this.finishSourceSelection(roomId, selection);
}
}, reportError);
}, false);
private retireWatchPlayer(id: string, reason?: string): void { this.watchStage(id)?.retireWatch(id, reason); }
private async joinWatchAndSyncClock(id: string, player: WatchPlayer, mode: WatchMode): Promise<void> {
player.mode = mode;
@@ -3439,7 +3439,7 @@ export class ChannelSession {
private async previewCommittedCapture(roomId: string, id: string, current: () => boolean, signal: AbortSignal): Promise<void> {
// Room confirmation replaces the shared video even if the local preview fails.
const retirement = this.finishScreenSelection(roomId, id);
const preview = this.watching.has(id) ? undefined : this.watch(id, roomId, signal);
const preview = this.watching.has(id) ? undefined : this.watch(id, roomId, signal, false);
const results = await Promise.allSettled([retirement, preview]);
if (!current()) throw new DOMException("Capture stopped", "AbortError");
for (const result of results) if (result.status === "rejected") throw result.reason;
@@ -3544,7 +3544,7 @@ export class ChannelSession {
this.patch({});
});
};
startExternalScreen = (roomId: string, reportError: ReportError = true): Promise<void> => this.action(`screen:${roomId}`, async () => {
startExternalScreen = (roomId: string): Promise<void> => this.action(`screen:${roomId}`, async () => {
const { share, selection, current } = this.selectScreen(roomId);
try {
const app = await this.connectApp(selection.controller.signal);
@@ -3553,7 +3553,7 @@ export class ChannelSession {
if (!current()) throw new DOMException("Input cancelled", "AbortError");
this.patch({});
} finally { this.finishSourceSelection(roomId, selection); }
}, reportError);
}, false);
private async commitExternalScreen(app: ChannelApp, event: Extract<NativeExternalInputState, { state: "prepared" | "live" }>): Promise<void> {
const stage = this.screenStage(event.publicationId);
if (!stage?.screen) return;
@@ -3789,7 +3789,7 @@ export class ChannelSession {
}).finally(() => { share.audioChange = undefined; share.requestedAudioBitrate = undefined; this.patch({}); });
return share.audioChange;
};
startNativeScreen = (roomId: string, { target, audio, excludeAudio, showCaptureBorder, renderEndpointId }: NativeCaptureSelection, reportError: ReportError = true): Promise<void> => this.action(`screen:${roomId}`, async () => {
startNativeScreen = (roomId: string, { target, audio, excludeAudio, showCaptureBorder, renderEndpointId }: NativeCaptureSelection): Promise<void> => this.action(`screen:${roomId}`, async () => {
const { share, selection, current } = this.selectScreen(roomId);
const signal = selection.controller.signal;
const native = { target, audio, renderEndpointId, excludeAudio: target.kind === "display" ? excludeAudio : undefined, showCaptureBorder };
@@ -3829,7 +3829,7 @@ export class ChannelSession {
if (ownsPreparation) await app?.cancelCapture(share.id).catch(() => {});
throw error;
} finally { this.finishSourceSelection(roomId, selection); }
}, reportError);
}, false);
setScreenDirectLimit = async (publicationId: string, limit: number | null): Promise<void> => {
const publication = this.view.state?.publications.find(value => value.id === publicationId && value.kind === "screen");
if (!publication) throw new Error("publication_unavailable");
+3 -3
View File
@@ -245,16 +245,16 @@ export interface ChannelActions {
createRoomInvite(roomId: string): Promise<string>;
getRoomInvite(roomId: string): Promise<RoomInvitationState>;
revokeRoomAccess(roomId: string, userId: string): Promise<void>;
startScreen(roomId: string, source?: BrowserCaptureSource, deviceId?: string, reportError?: ReportError): Promise<void>;
startScreen(roomId: string, source?: BrowserCaptureSource, deviceId?: string): Promise<void>;
cameraPreviews: typeof loadCameraPreviews;
nativeSources(signal?: AbortSignal): Promise<NativeCaptureSources>;
externalInput(roomId: string): (NativeExternalInput & { publicationId: string }) | undefined;
startExternalScreen(roomId: string, reportError?: ReportError): Promise<void>;
startExternalScreen(roomId: string): Promise<void>;
cancelExternalScreen(roomId: string): Promise<void>;
nativePreview(target: NativeCaptureTarget, signal?: AbortSignal): Promise<string | null>;
nativeCaptureRequest(roomId: string): NativeCaptureRequest | undefined;
nativeCaptureSelection(roomId: string): (NativeCaptureSelection & { current: boolean }) | undefined;
startNativeScreen(roomId: string, selection: NativeCaptureSelection, reportError?: ReportError): Promise<void>;
startNativeScreen(roomId: string, selection: NativeCaptureSelection): Promise<void>;
sourceSelectionCommitting(roomId: string): boolean;
browserCapturePreparation(roomId: string): "picker" | "preparing" | undefined;
cancelScreenSelection(roomId: string): Promise<void>;
+28 -23
View File
@@ -3806,12 +3806,13 @@ test("screen commentary owns a separate microphone and keeps its mixed track acr
} finally { session.close(); }
});
test.each([[false, null], [true, "NotAllowedError"]] as const)("a share start owned by its control reaches the banner only once that owner is gone (gone: %s)", async (gone, banner) => {
const { session } = await setup();
test("a rejected camera start preserves the current session error", async () => {
const { session, socket } = await setup();
vi.stubGlobal("navigator", { mediaDevices: { getUserMedia: vi.fn().mockRejectedValue(new DOMException("Declined", "NotAllowedError")) } });
try {
await expect(session.startScreen("first", "camera", "front", () => gone)).rejects.toMatchObject({ name: "NotAllowedError" });
expect(session.getSnapshot().error).toBe(banner);
socket.receive({ type: "error", code: "channel_full" });
await expect(session.startScreen("first", "camera", "front")).rejects.toMatchObject({ name: "NotAllowedError" });
expect(session.getSnapshot().error).toBe("channel_full");
expect(session.getSnapshot().pending.size).toBe(0);
} finally { session.close(); }
});
@@ -4496,7 +4497,7 @@ test.each(["live", "metadata-rejected", "native-stop-rejected", "stop-before-rep
expect(session.getSnapshot().streams.has(publication.id)).toBe(false);
expect(session.getSnapshot().ownedScreens.has(publication.id)).toBe(!committed);
expect(session.getSnapshot().state?.publications).toEqual(committed ? [] : state.publications);
expect(session.getSnapshot().error).toBe(error);
expect(session.getSnapshot().error).toBeNull();
expect(socket.readyState).toBe(ChannelSocket.OPEN);
expect(app.sent.some(command => command.type === "stop_capture")).toBe(false);
expect(socket.sent.filter(command => command.type === "unpublish")).toHaveLength(1);
@@ -4953,6 +4954,7 @@ test("Native capture previews before its snapshot, keeps picture on audio failur
app.receive({ type: "capture_audio_state", publicationId, state: { sourceAudio: true, microphone } });
expect(session.sourceMicrophone(publicationId)).toMatchObject({ browser: false, available: true, ...microphone });
expect(session.sourceAudio(publicationId)).toMatchObject({ hasAudio: true, available: true });
app.receive({ type: "capture_audio_failed", publicationId });
for (const error of ["capture_cancelled", "capture_failed"]) {
const previousRequest = app.sent.at(-1)?.id;
const replacement = session.startNativeScreen("first", { target, audio: false, showCaptureBorder: false }).catch(error => error);
@@ -4964,7 +4966,7 @@ test("Native capture previews before its snapshot, keeps picture on audio failur
expect(session.sourceAudio(publicationId)).toMatchObject({ hasAudio: true, available: true });
expect(session.nativeCaptureSelection("first")).toEqual({ target, audio: true, excludeAudio: excluded, showCaptureBorder: true, current: true });
expect(session.getSnapshot().pending.has("screen:first")).toBe(false);
expect(session.getSnapshot().error).toBe(error === "capture_cancelled" ? null : error);
expect(session.getSnapshot().error).toBe("capture_audio_failed");
}
const settingsPanel = new AbortController();
const dismissed = session.sourceMicrophones(publicationId, settingsPanel.signal);
@@ -5003,7 +5005,7 @@ test("Native capture previews before its snapshot, keeps picture on audio failur
expect(session.nativeCaptureRequest("first")).toBeUndefined();
enabledMicrophone.volume = .9;
app.receive({ id: app.sent.at(-1)!.id, result: enabledMicrophone }); await gaining;
expect(session.getSnapshot().error).toBe("capture_failed");
expect(session.getSnapshot().error).toBe("capture_audio_failed");
const failedDevice = session.setSourceMicrophone(publicationId, { deviceId: "missing" });
expect(activateMicrophone).not.toHaveBeenCalled();
expect(session.nativeCaptureRequest("first")).toBeUndefined();
@@ -5024,18 +5026,18 @@ test("Native capture previews before its snapshot, keeps picture on audio failur
app.receive(cancelFirst ? cancelled : failed);
await new Promise(resolve => setTimeout(resolve, 0));
expect(app.sent.at(-1)).toBe(offRequest);
expect(session.getSnapshot().error).toBe("capture_failed");
expect(session.getSnapshot().error).toBe("capture_audio_failed");
app.receive(cancelFirst ? failed : cancelled);
await rejected;
expect(app.sent.at(-1)).toBe(offRequest);
expect(session.getSnapshot().error).toBe("capture_failed");
expect(session.getSnapshot().error).toBe("capture_audio_failed");
expect(patchView.mock.calls.filter(([value]) => "error" in value)).toEqual([]);
expect(session.sourceMicrophone(publicationId)).toMatchObject({ ...enabledMicrophone, requested: enabledMicrophone });
}
patchView.mockRestore();
const replacingBeforeOff = session.setSourceMicrophone(publicationId, { deviceId: "pending-before-off" });
const heldMicrophone = app.sent.at(-1)!;
await expect(session.startExternalScreen("first", false)).rejects.toThrow("operation_pending");
await expect(session.startExternalScreen("first")).rejects.toThrow("operation_pending");
expect(app.sent.at(-1)).toBe(heldMicrophone);
const otherScreen = { ...published.publications[0]!, id: crypto.randomUUID(), sessionId: "other", userId: "other" };
socket.receive({ type: "state", state: { ...published, publications: [...published.publications, otherScreen] } });
@@ -5531,11 +5533,11 @@ test.each(["native", "obs", "refused"] as const)("committed %s capture retires o
return;
}
socket.receive({ type: "reply", roomId: "first", requestId: stop.requestId, result: { type: "done" } });
await starting;
if (source === "native") expect(await starting).toMatchObject({ message: "room_unavailable" });
await vi.waitFor(() => expect(session.getSnapshot().pending.has("screen:first")).toBe(false));
expect(session.getSnapshot().ownedScreens.has(commit.publicationId as string)).toBe(true);
expect([...session.getSnapshot().watchPlayers.keys()]).toEqual([activities.get("second")]);
expect(session.getSnapshot().error).toBe("room_unavailable");
expect(session.getSnapshot().error).toBe(source === "obs" ? "room_unavailable" : null);
expect(app.sent.some(c => ["cancel_external_input", "cancel_capture", "stop_capture"].includes(String(c.type)))).toBe(false);
} finally { session.close(); }
});
@@ -5774,7 +5776,7 @@ test.each(["h264", "av1"])("external input handles prepared codec %s within its
await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("commit_capture"));
expect(app.sent.at(-1)).toMatchObject({ publicationId, captureId });
app.receive({ id: app.sent.at(-1)!.id, result: null });
await vi.waitFor(() => expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal)));
await vi.waitFor(() => expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal), false));
app.receive({ type: "external_input_state", publicationId, state: "live", captureId, sessionId, codec: "av1" });
expect(session.externalInput("first")?.state).toBe("live");
app.receive({ type: "external_input_state", publicationId, state: "waiting" });
@@ -5829,7 +5831,7 @@ test.each(["browser", "camera", "native"] as const)("waiting OBS can switch to %
app.receive({ id: committing.id, result: null });
expect(await result).toBeUndefined();
expect(session.nativeCaptureSelection("first")).toMatchObject({ target, current: true });
expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal));
expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal), false);
} else {
capture.mockRejectedValueOnce(new DOMException("Denied", "NotAllowedError"));
await expect(session.startScreen("first", source)).rejects.toMatchObject({ name: "NotAllowedError" });
@@ -5876,7 +5878,7 @@ test.each(["browser", "camera", "native"] as const)("waiting OBS can switch to %
await vi.waitFor(() => expect(session.getSnapshot().pending.has("screen:first")).toBe(false));
expect(video.stop).toHaveBeenCalledOnce();
expect(session.externalInput("first")?.state).toBe("live");
expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal));
expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal), false);
}
} finally { session.close(); }
});
@@ -6513,23 +6515,22 @@ test("domain settings use a domain-scoped acknowledgement and surface rejected u
} finally { session.close(); }
});
test("room management failures preserve capture errors", async () => {
test("room management failures preserve session errors", async () => {
const { session, socket } = await setup();
vi.stubGlobal("navigator", { mediaDevices: { getUserMedia: vi.fn().mockRejectedValue(new Error("capture_failed")) } });
try {
await expect(session.startScreen("first", "camera")).rejects.toThrow("capture_failed");
expect(session.getSnapshot().error).toBe("capture_failed");
socket.receive({ type: "error", code: "channel_full" });
expect(session.getSnapshot().error).toBe("channel_full");
const saving = session.updateRoom("second", { name: "Saved", icon: "couch", access: "public", hidden: false });
const rejected = expect(saving).rejects.toThrow("room_host_offline");
const request = socket.sent.at(-1)!;
expect(request).toMatchObject({ type: "update_room", roomId: "second", name: "Saved" });
expect(session.getSnapshot().pending.has("room:second")).toBe(true);
expect(session.getSnapshot().error).toBe("capture_failed");
expect(session.getSnapshot().error).toBe("channel_full");
socket.receive({ type: "reply", roomId: "second", requestId: request.requestId,
result: { type: "error", code: "room_host_offline" } });
await rejected;
expect(session.getSnapshot().error).toBe("capture_failed");
expect(session.getSnapshot().error).toBe("channel_full");
expect(session.getSnapshot().pending.has("room:second")).toBe(false);
} finally { session.close(); }
@@ -13277,11 +13278,11 @@ test("Browser capture titles use original metadata and confirmed overrides witho
expect(old.stop).not.toHaveBeenCalled();
expect(next.stop).toHaveBeenCalledOnce();
expect(session.getSnapshot().state!.publications[0].title).toBe("Weekly review");
expect(session.getSnapshot().error).toBe("room_unavailable");
expect(session.getSnapshot().error).toBeNull();
const clearing = session.setScreenTitle(publication.id, " ");
expect(socket.sent.at(-1)).toMatchObject({ type: "set_title", title: null });
socket.receive({ type: "reply", requestId: socket.sent.at(-1)!.requestId, result: { type: "done" } }); await clearing;
expect(session.getSnapshot().error).toBe("room_unavailable");
expect(session.getSnapshot().error).toBeNull();
expect(bind.mock.calls).toHaveLength(bindings);
state = { ...state, publications: [{ ...state.publications[0], sessionId: "other-endpoint" }] };
socket.receive({ type: "state", state });
@@ -13841,6 +13842,8 @@ test.each(["explicit", "automatic", "unsupported", "removed"] as const)("browser
await vi.waitFor(() => expect(socket.sent.findLast(c => c.type === "join_watch")).toMatchObject({ id: old.id, mode: "peer" }));
reply(old.id, "peer");
await joining;
// The route becomes the person's when its player is ready, which the join does not wait for.
await session.getSnapshot().watchPlayers.get(old.id)!.ready();
socket.receive({ type: "state", state: { ...base, watchActivities: [initial], watchSubscriptions: [{ id: old.id, mode: "peer" }] } });
const successor = { ...first, source: { kind: "media", url: "https://media.test/next.mp4" }, byteSource: choice === "unsupported" ? undefined : grant() };
socket.receive({ type: "state", state: { ...base, watchActivities: [successor] } });
@@ -19329,6 +19332,8 @@ test("a replacement inherits the confirmed peer while direct media is pending af
const joining = session.joinWatch(source.id, "peer");
reply(source.id, "peer");
await joining;
// The route becomes the person's when its player is ready, which the join does not wait for.
await session.getSnapshot().watchPlayers.get(source.id)!.ready();
socket.receive({ type: "state", state: { ...base, watchActivities: [source], watchSubscriptions: [{ id: source.id, mode: "peer" }] } });
session.getSnapshot().watchPlayers.get(source.id)!.error = "watch_media_failed";
readyState = 0;