diff --git a/.agents/handoff/to-claude.md b/.agents/handoff/to-claude.md index 8c7d35a28..f4a0e7ee3 100644 --- a/.agents/handoff/to-claude.md +++ b/.agents/handoff/to-claude.md @@ -90,3 +90,27 @@ Current shared-Web interaction tracing did not reproduce the native stall. The reporting WebView/OS-maximize path remains open. Existing beta.76 passed local image/file workflows and Windows beta.75/beta.76 Browser/App pairings; physical audio, Native captions and Android system download saving stay separate. + +## Current lifecycle follow-through + +Manual watch/join/retry results now belong to their keyed UI controls, without +passing banner-policy callbacks through the public actions. Autonomous recovery +keeps its session-owned path. Current Chrome preview verified local errors, +source retirement before a delayed failure, and successful retry. + +Voice participation now cancels its pending room admission and publication on +leave, so an old reply cannot hold the room's action lock against a fresh join. +The same request signal and room-owned leave operation handle the committed +publication; there is no additional retirement protocol. + +SDK stop now refuses a concurrent reconnect before it can close the socket +waiting for the leave reply. A real WebSocket regression covers that ordering. +The restored site-owner bootstrap also keeps its expected site/user through +manual retries, validating Welcome before storing the personal credential. + +Hold `session.ts`, `use-channel.ts` and restore-result UI for ADR-0015 step 7. +The isolated handoff implementation is underway: the hook will own replacement, +and the receiving Session will acquire its own resources. We are preserving the +existing writer commit and provisional room-creator semantics without restarting +a retired Session or adding a restore framework. Ordinary bug fixes can still be +reviewed independently; no storage or wire-format change is planned. diff --git a/prototype/channel-browser/node/text-participant.ts b/prototype/channel-browser/node/text-participant.ts index 1772841f7..d77a117b1 100644 --- a/prototype/channel-browser/node/text-participant.ts +++ b/prototype/channel-browser/node/text-participant.ts @@ -414,6 +414,7 @@ export class TextParticipant extends EventEmitter { } async reconnect() { + if (this.stopped) throw new Error('closed'); const socket = this.socket; if (socket) await new Promise(resolve => { socket.once('close', () => resolve()); socket.close(); }); diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index 144374235..267599754 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -28,7 +28,7 @@ import { userProfile } from "./presentation"; import { HISTORY_INLINE_IMAGES, ChannelEventDecoder, DomainVersionMismatch, checkDomainVersion, createRoomCommand, roomSummarySchema, userSchema, type ChannelUser, type ProfilePage, type ProfileUpdate, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ChannelTopology, type ConversationReply, type ReceivedRecord, type DomainSettings, type MessageReactionSnapshot, type RoomInvitationState, type RoomSettings, type RoomSummary, type ScreenSource } from "./protocol"; import { requestBrowserRoomPersistence } from "./browser-room-persistence"; import { ChannelAttachments, type DraftFile, type PreparedFile } from "./attachments"; -import { messageRemoved, type ChannelActions, type HostMediaTarget, type ReportError, type ChannelView, type ChatAttachmentPreparation, type ChatOptions, type SourceMicrophoneConfiguration, type SourceMicrophoneSettings } from "./types"; +import { messageRemoved, type ChannelActions, type HostMediaTarget, type ChannelView, type ChatAttachmentPreparation, type ChatOptions, type SourceMicrophoneConfiguration, type SourceMicrophoneSettings } from "./types"; import { loadRoomHosting, roomDatabaseName } from "./hosting"; import { BrowserHosting, browserRoomStorage } from "./browser-hosting"; import type { BrowserRoomSnapshot, BrowserRoomStage } from "../../../prototype/channel-browser/src/hosting-contract"; @@ -175,7 +175,7 @@ function stored(key: string, value?: string): string | null { } catch { return null; } } -type OwnerBootstrap = { key: string; parameter?: "launch" | "owner" }; +type OwnerBootstrap = { key: string; parameter?: "launch" | "owner"; restoredOwner?: { domainId: string; userId: string } }; function ownerBootstrapFromLocation(): OwnerBootstrap | undefined { const parameters = new URLSearchParams(location.hash.slice(1)); @@ -286,11 +286,11 @@ export class ChannelSession { snapshot: () => this.roomSnapshot, lifetime: () => this.captureLifetime.signal, action: (key, work, reportError) => this.action(key, work, reportError), - request: command => this.request(command), + request: (command, signal) => this.request(command, undefined, undefined, { signal }), send: command => this.send(command), write: command => this.write(command), unpublishMissing: (state, scope) => this.unpublishMissing(state, scope), - publish: (roomId, stream, microphone, publicationId) => this.publish("voice", roomId, stream, { microphone, publicationId }), + publish: (roomId, stream, microphone, publicationId, signal) => this.publish("voice", roomId, stream, { microphone, publicationId, signal }), retire: id => this.retireCapture(id), refresh: () => this.refreshActivity(), levels: roomId => this.media.voiceActivity(roomId), @@ -570,6 +570,13 @@ export class ChannelSession { const event = decoder.decode(raw, wireBytes); if (!event) return; if (event.type === "welcome") { + const restored = sentBootstrap?.restoredOwner; + if (restored && (event.state.channel.id !== restored.domainId || event.state.channel.ownerId !== restored.userId + || event.state.sessions.find(value => value.id === event.sessionId)?.userId !== restored.userId)) { + this.closeConnection(); + this.patch({ error: "domain_restored_connection_failed" }); + return; + } const skipRoom = acceptWelcome?.(event); const bootstrap = sentBootstrap; acceptWelcome = undefined; @@ -657,7 +664,7 @@ export class ChannelSession { } } for (const id of this.watching.keys()) { - if (!event.state.subscriptions.includes(id) && !this.pendingActions.has(`watch:${id}`)) void this.watch(id).catch(() => {}); + if (!event.state.subscriptions.includes(id) && !this.pendingActions.has(`watch:${id}`)) void this.openScreenWatch(id, undefined, undefined, true).catch(() => {}); } } this.browse(this.roomId); @@ -847,7 +854,7 @@ export class ChannelSession { } if (nextWatches.includes(next) || restoring && !player && (waiting.browser || !joined)) { const socket = this.socket; - const opening = waiting.browser ? this.joinWatch(id, waiting.preference) : this.request({ type: "join_watch", roomId: waiting.roomId, id, mode: "direct" }, undefined, waiting.roomId); + const opening = waiting.browser ? this.openWatchVideo(id, waiting.preference, true) : this.request({ type: "join_watch", roomId: waiting.roomId, id, mode: "direct" }, undefined, waiting.roomId); void opening.catch(error => { // The activity is gone: nothing to decline, and this record keeps the receiving method for the successor the room names next. if (error instanceof Error && error.message === "watch_unavailable") return; @@ -861,7 +868,7 @@ export class ChannelSession { const before = previous?.watchActivities.find(activity => activity.id === id); if (before?.byteSource && previous?.watchSubscriptions.some(sub => sub.id === id)) continue; if (waiting.priorMode === "peer" || !(this.view.pagePlayer && originalWatchURL(next.source)) || next.playback.timeline === "program") { - if (waiting.preference === "peer") void this.joinWatch(id, "peer").catch(() => {}); + if (waiting.preference === "peer") void this.openWatchVideo(id, "peer", true).catch(() => {}); else { this.takeRoute(id, waiting.roomId, "peer"); void this.action(`watch-video:${id}`, () => this.joinWatchRoute(id, "peer")).catch(() => {}); @@ -880,7 +887,7 @@ export class ChannelSession { } for (const next of nextScreens) { const socket = this.socket; - void this.watch(next.id, next.roomId).catch(() => { + void this.openScreenWatch(next.id, next.roomId, undefined, true).catch(() => { if (this.socket === socket && !this.watching.has(next.id)) this.declineSuccessor(next.roomId, { kind: "screen", id: next.id }); }); } @@ -1326,7 +1333,7 @@ export class ChannelSession { return shortcut; }; - private async action(key: string, work: () => Promise, reportError: ReportError = true, options: { clearError?: boolean } = {}): Promise { + private async action(key: string, work: () => Promise, reportError: boolean | (() => boolean) = true, options: { clearError?: boolean } = {}): Promise { if (this.pendingActions.has(key)) throw new Error("operation_pending"); this.pendingActions.add(key); const failed = this.beginActionFeedback(reportError, options.clearError); @@ -1335,7 +1342,7 @@ export class ChannelSession { finally { this.pendingActions.delete(key); this.patch({}); } } - private beginActionFeedback(reportError: ReportError = true, clearError = true): (error: unknown) => void { + private beginActionFeedback(reportError: boolean | (() => boolean), clearError = true): (error: unknown) => void { const socket = this.socket; const ownsError = () => typeof reportError === "function" ? reportError() : reportError; this.patch(ownsError() && clearError ? { error: null } : {}); @@ -1939,7 +1946,7 @@ export class ChannelSession { this.close(); if (skipRoom) this.previousRoomAccount = { credential: this.credential, ownerBootstrap: this.ownerBootstrap, roomId: this.roomId }; this.credential = identity.credential; this.roomId = ""; - this.ownerBootstrap = identity.ownerKey === undefined ? undefined : { key: identity.ownerKey }; + this.ownerBootstrap = identity.ownerKey === undefined ? undefined : { key: identity.ownerKey, restoredOwner: { domainId, userId } }; const generation = this.identityGeneration; const lifetime = this.captureLifetime.signal; let timer: ReturnType | undefined; @@ -1953,8 +1960,7 @@ export class ChannelSession { this.connect(event => { if (!waiting) throw new Error("backup_identity_required"); const actual = event.state.sessions.find(value => value.id === event.sessionId)?.userId; - if (event.state.channel.id !== domainId || actual !== userId - || (identity.ownerKey !== undefined && event.state.channel.ownerId !== userId)) { + if (identity.ownerKey === undefined && (event.state.channel.id !== domainId || actual !== userId)) { reject(new Error("backup_identity_required")); throw new Error("backup_identity_required"); } waiting = false; resolve(); return skipRoom; @@ -2341,7 +2347,9 @@ export class ChannelSession { return this.roomInvitationURL(roomId, key); }; revokeRoomAccess = (roomId: string, userId: string): Promise => this.action(`revoke:${roomId}:${userId}`, () => this.request({ type: "revoke_room_access", roomId, userId }), false); - watch = (publicationId: string, roomId?: string, signal?: AbortSignal, reportError: ReportError = true): Promise => { + watch = (publicationId: string, roomId?: string, signal?: AbortSignal): Promise => + this.openScreenWatch(publicationId, roomId, signal, false); + private openScreenWatch(publicationId: string, roomId: string | undefined, signal: AbortSignal | undefined, reportError: boolean): Promise { const watch: ScreenWatch = { controller: new AbortController() }; const operation = this.action(`watch:${publicationId}`, async () => { const lifetime = AbortSignal.any([watch.controller.signal, this.captureLifetime.signal, ...(signal ? [signal] : [])]); @@ -2376,7 +2384,7 @@ export class ChannelSession { }, reportError); watch.operation = operation; return operation.finally(() => { watch.operation = undefined; }).then(() => { void this.syncAppWatching(); }); - }; + } private retireWatch(publicationId: string): void { this.input.close(publicationId); const watch = this.watching.get(publicationId); @@ -2398,7 +2406,7 @@ export class ChannelSession { if (this.view.connection === "connected") await this.request({ type: "subscribe", publicationId, enabled: false }); }, false); }; - retryPicture = (publicationId: string, reportError: ReportError = true): Promise => this.action(`retry-picture:${publicationId}`, async () => { + retryPicture = (publicationId: string): Promise => this.action(`retry-picture:${publicationId}`, async () => { const current = this.sessionContext(); const publication = this.view.state?.publications.find(value => value.id === publicationId && value.kind === "screen"); const watch = this.watching.get(publicationId); @@ -2434,7 +2442,7 @@ export class ChannelSession { this.browseRooms(); } void this.syncAppWatching(); - }, reportError); + }, false); clearError = (): void => this.patch({ error: null }); async publish(kind: "screen" | "voice", roomId: string, stream: MediaStream, { microphone, audio, profile, codec, camera, source, publicationId, signal }: { signal?: AbortSignal; microphone?: MicrophoneInput; audio?: HostAudio; profile?: QualityProfile; codec?: BrowserVideoCodecPreference; camera?: boolean; source?: ScreenSource; publicationId?: string } = {}): Promise { @@ -3216,7 +3224,8 @@ export class ChannelSession { const successor = this.watchPlayer(id); if (successor && successor !== player) { successor.fallbackFrom = from; this.patch({}); } } - joinWatch = (id: string, mode?: WatchMode, reportError: ReportError = true): Promise => this.action(`watch-video:${id}`, async () => { + joinWatch = (id: string, mode?: WatchMode): Promise => this.openWatchVideo(id, mode, false); + private openWatchVideo = (id: string, mode: WatchMode | undefined, reportError: boolean): Promise => this.action(`watch-video:${id}`, async () => { if (mode) { if (mode === "peer" && this.waitingFor(id)?.browser) { const activity = this.view.state?.watchActivities.find(value => value.id === id); @@ -3438,7 +3447,7 @@ export class ChannelSession { private async previewCommittedCapture(roomId: string, id: string, current: () => boolean, signal: AbortSignal): Promise { // 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, false); + const preview = this.watching.has(id) ? undefined : this.watch(id, roomId, signal); 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; diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index b8b6374b7..cbf4e96f3 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -143,13 +143,6 @@ export interface ChatAttachmentPreparation { progress(percent: number | null): void; } -/** - * Whether the page banner reports an operation's failure. A control that shows - * its own failure passes a function, asked when the failure happens, so a - * result its owner can no longer receive still reaches the banner. - */ -export type ReportError = boolean | (() => boolean); - export type HostMediaTarget = "domain" | "app" | "browser"; export interface ChannelActions { @@ -168,7 +161,7 @@ export interface ChannelActions { selectWatchBrowserSource(roomId: string, choiceId: string | null): Promise; focusWatch(id: string): Promise; focusWatchPage(roomId: string, activityId?: string): Promise; - joinWatch(id: string, mode?: WatchMode, reportError?: ReportError): Promise; + joinWatch(id: string, mode?: WatchMode): Promise; watchMediaChoices(id: string, signal: AbortSignal, onChange?: (sources: WatchMediaSources) => void): Promise; inspectWatchMpdSource(roomId: string, choiceId: string, signal: AbortSignal, activityId?: string): Promise; selectWatchMpdSource(roomId: string, selection: NativePageMpdSelection): Promise; @@ -259,9 +252,9 @@ export interface ChannelActions { browserCapturePreparation(roomId: string): "picker" | "preparing" | undefined; cancelScreenSelection(roomId: string): Promise; stopScreen(publicationId: string, successorWatchId?: string): Promise; - watch(publicationId: string, reportError?: ReportError): Promise; + watch(publicationId: string): Promise; unwatch(publicationId: string): Promise; - retryPicture(publicationId: string, reportError?: ReportError): Promise; + retryPicture(publicationId: string): Promise; screenPresentation(flowId: string, stream: MediaStream, state: ScreenPresentation, playbackError?: ScreenPlaybackError): void; screenPlaybackError(publicationId: string): ScreenPlaybackError | undefined; inputPolicy(publicationId: string, mode: RemoteControlMode, password?: string): Promise; diff --git a/src/client/channel/use-channel.ts b/src/client/channel/use-channel.ts index f15a78f37..40bd4d87c 100644 --- a/src/client/channel/use-channel.ts +++ b/src/client/channel/use-channel.ts @@ -116,7 +116,7 @@ export function useChannel(): ChannelController { sourceSelectionCommitting: session.sourceSelectionCommitting, browserCapturePreparation: session.browserCapturePreparation, cancelScreenSelection: session.cancelScreenSelection, - stopScreen: session.stopScreen, watch: (publicationId, reportError) => session.watch(publicationId, undefined, undefined, reportError), unwatch: session.unwatch, retryPicture: session.retryPicture, screenPresentation: session.screenPresentation, screenPlaybackError: session.screenPlaybackError, + stopScreen: session.stopScreen, watch: session.watch, unwatch: session.unwatch, retryPicture: session.retryPicture, screenPresentation: session.screenPresentation, screenPlaybackError: session.screenPlaybackError, inputPolicy: session.inputPolicy, inputDecide: session.inputDecide, inputSimultaneous: session.inputSimultaneous, inputShortcut: session.inputShortcut, joinVoice: session.joinVoice, leaveVoice: session.leaveVoice, setMuted: session.setMuted, canUnmute: session.canUnmute, toggleVoiceShortcut: session.toggleVoiceShortcut, voiceMicrophonePending: session.voiceMicrophonePending, voiceBusy: session.voiceBusy, diff --git a/src/client/channel/voice-participation.ts b/src/client/channel/voice-participation.ts index 3d5b7568d..39803c54c 100644 --- a/src/client/channel/voice-participation.ts +++ b/src/client/channel/voice-participation.ts @@ -13,6 +13,7 @@ type VoiceTransmission = RoomPreferences["voiceTransmission"]; /** This endpoint's voice in one room: what it asked for, and the publication carrying it. */ interface VoiceIntent { + lifetime: AbortController; cancelInputWait?: () => void; publicationId: string | null; muted: boolean; @@ -37,12 +38,12 @@ export interface VoiceSession { /** Aborts when the session releases its media. */ lifetime(): AbortSignal; action(key: string, work: () => Promise, reportError?: boolean): Promise; - request(command: ChannelCommand): Promise; + request(command: ChannelCommand, signal?: AbortSignal): Promise; send(command: ChannelCommand): void; write(command: ChannelCommand): void; /** Withdraws this endpoint's publications that no local capture carries, only in this room and kind. */ unpublishMissing(state: ChannelSnapshot, scope: { roomId: string; kind: "voice" }): void; - publish(roomId: string, stream: MediaStream, microphone: MicrophoneInput | undefined, publicationId: string): Promise; + publish(roomId: string, stream: MediaStream, microphone: MicrophoneInput | undefined, publicationId: string, signal: AbortSignal): Promise; retire(publicationId: string): void; /** Republishes the local projection of the current snapshot. */ refresh(): void; @@ -105,20 +106,20 @@ export class VoiceParticipation { join = (roomId: string, listenOnly = false, reportError = true, providedStream?: MediaStream): Promise => this.session.action(roomKey(roomId), async () => { if (this.rooms.has(roomId)) return; - const intent: VoiceIntent = { publicationId: null, muted: listenOnly, deafened: false }; + const intent: VoiceIntent = { lifetime: new AbortController(), publicationId: null, muted: listenOnly, deafened: false }; this.rooms.set(roomId, intent); let supplied = listenOnly ? undefined : providedStream; try { const microphone = !listenOnly && !supplied ? await this.waitForMicrophone(intent) : undefined; - if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); - await this.session.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }); - if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); + intent.lifetime.signal.throwIfAborted(); + await this.session.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }, intent.lifetime.signal); + intent.lifetime.signal.throwIfAborted(); if (!intent.muted && (supplied || microphone)) { const capture = supplied ?? microphone!.stream.clone(); supplied = undefined; const id = intent.publicationId = crypto.randomUUID(); - await this.session.publish(roomId, capture, microphone, id); - if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); + await this.session.publish(roomId, capture, microphone, id, intent.lifetime.signal); + intent.lifetime.signal.throwIfAborted(); capture.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); this.refresh(); } else { @@ -151,7 +152,9 @@ export class VoiceParticipation { }; private forgetRoom(roomId: string): void { - this.rooms.get(roomId)?.cancelInputWait?.(); + const intent = this.rooms.get(roomId); + intent?.lifetime.abort(); + intent?.cancelInputWait?.(); this.rooms.delete(roomId); this.lastOn.microphone.delete(roomId); this.lastOn.listening.delete(roomId); @@ -234,11 +237,11 @@ export class VoiceParticipation { if (this.rooms.get(roomId) !== intent || intent.muted) return; const capture = microphone.stream.clone(); const id = intent.publicationId = crypto.randomUUID(); - await this.session.publish(roomId, capture, microphone, id); - if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); + await this.session.publish(roomId, capture, microphone, id, intent.lifetime.signal); + intent.lifetime.signal.throwIfAborted(); capture.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); this.refresh(); - await this.session.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }); + await this.session.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }, intent.lifetime.signal); } catch (error) { const left = this.rooms.get(roomId) !== intent; if (intent.publicationId) this.session.retire(intent.publicationId); @@ -389,9 +392,7 @@ export class VoiceParticipation { close(): void { this.talkPressed = false; - this.rooms.clear(); - this.lastOn.microphone.clear(); - this.lastOn.listening.clear(); + for (const roomId of this.rooms.keys()) this.forgetRoom(roomId); this.release(); } @@ -410,7 +411,7 @@ export class VoiceParticipation { return Promise.resolve(); } return this.session.action(roomKey(roomId), async () => { - try { await this.session.request(command); } + try { await this.session.request(command, intent?.lifetime.signal); } catch (error) { if (!(error instanceof Error) || error.message !== "disconnected") throw error; } }); } diff --git a/src/client/pages/ChannelPage.tsx b/src/client/pages/ChannelPage.tsx index 3e8bda55b..8441a7074 100644 --- a/src/client/pages/ChannelPage.tsx +++ b/src/client/pages/ChannelPage.tsx @@ -442,19 +442,17 @@ export function ChannelRoomPage({ channel, selected, onSelect, restoreRoom, appC document.querySelector(target)?.focus({ preventScroll: true }); }, [mobilePane]); const run = (operation: Promise) => { void operation.catch(() => {}); }; - // A picture's Watch and Retry report here: its offer, tile, help dialog and picture panel can all go first. - // A result this owner can no longer receive still reaches the banner. A lost connection ends both owners, as it - // ends the banner's claim: the session drops a result whose socket has gone, and a reconnect starts clean. + // The page owns viewing results across the source offer, tile, help dialog and detached panel. const sourceAction = useKeyedSettingsAction(JSON.stringify([state?.channel.id, sessionId, connected]), [ ...publications.map(publication => ({ id: `picture:${publication.id}` })), ...watches.map(activity => ({ id: `watch:${activity.id}` })), ...mine.map(publication => ({ id: `microphone:${publication.id}` })), ]); - function watchAction(id: string, operation: (reportError: () => boolean) => Promise) { + function watchAction(id: string, operation: () => Promise) { void sourceAction.run(`watch:${id}`, operation); } // A share start reports here: the picker closes first, and the room's share control moves to the tile once sharing starts. const shareStart = useSettingsAction(true, JSON.stringify([state?.channel.id, sessionId, roomId, connected])); - const attemptPicture = (id: string, operation: (reportError: () => boolean) => Promise) => { + const attemptPicture = (id: string, operation: () => Promise) => { void sourceAction.run(`picture:${id}`, operation); }; const stopped = useKeyedSettingsAction(JSON.stringify([state?.channel.id, sessionId])); @@ -494,15 +492,15 @@ export function ChannelRoomPage({ channel, selected, onSelect, restoreRoom, appC connecting: player?.mode === "peer" && state?.watchBytes.some(plan => plan.roomId === activity.roomId && plan.activityId === activity.id && plan.receiving && plan.upstream === null), browserSource, pending: busy("watch-video", activity.id), disabled: !connected, - onPeer: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, report => channel.joinWatch(activity.id, "peer", report)); }, - onDirect: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, report => channel.joinWatch(activity.id, "direct", report)); } } : undefined, + onPeer: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, () => channel.joinWatch(activity.id, "peer")); }, + onDirect: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, () => channel.joinWatch(activity.id, "direct")); } } : undefined, shareControls: owned && openWatchSource(activity.roomId, replacement)} compact disabled={!available} startAction={shareStart} onStopScreen={stopScreen} />, actionFailure: sourceAction.errors.get(`watch:${activity.id}`)?.code, clearActionFailure: () => sourceAction.clearError(`watch:${activity.id}`), hidden: activity.roomId !== roomId, paused: activity.playback.paused, player, available, pending: busy("watch", activity.id) || busy("watch-video", activity.id) || busy("stop", activity.id), - onRoom: () => openRoomChat(activity.roomId), onJoin: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, report => channel.joinWatch(activity.id, undefined, report)); }, + onRoom: () => openRoomChat(activity.roomId), onJoin: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, () => channel.joinWatch(activity.id)); }, onLeave: () => watchAction(activity.id, () => channel.leaveWatch(activity.id)), onStop: () => stopWatch(activity.roomId, activity.id), onResume: () => channel.resumeWatch(activity.id), onPlayback: patch => channel.setWatchPlayback(activity.id, patch), }; @@ -783,8 +781,8 @@ export function ChannelRoomPage({ channel, selected, onSelect, restoreRoom, appC })(), pending: busy(channel.ownedScreens.has(publication.id) ? "stop" : "watch", publication.id) || busy("retry-picture", publication.id), })), ...watchSources, ...waitingSources.map(source => ({ ...source, hidden: source.roomId !== roomId, onClose: () => closeWaiting(source.id) }))]} focusedId={focusedScreen} onFocus={id => setSourceView({ roomId, focusedId: id })} canSubscribe={connected} - onWatch={id => { showSource(roomId, id); attemptPicture(id, reportError => channel.watch(id, reportError)); }} onUnwatch={id => attemptPicture(id, () => channel.unwatch(id))} - onRetryPicture={id => attemptPicture(id, reportError => channel.retryPicture(id, reportError))} + onWatch={id => { showSource(roomId, id); attemptPicture(id, () => channel.watch(id)); }} onUnwatch={id => attemptPicture(id, () => channel.unwatch(id))} + onRetryPicture={id => attemptPicture(id, () => channel.retryPicture(id))} onPause={channel.setScreenPaused} onStop={id => { void stopScreen(roomId, id); }} onPresentation={channel.screenPresentation} onInputPolicy={channel.inputPolicy} onInputDecide={channel.inputDecide} onInputSimultaneous={channel.inputSimultaneous} onInputShortcut={channel.inputShortcut} /> diff --git a/src/client/pages/ChannelRoomPreview.tsx b/src/client/pages/ChannelRoomPreview.tsx index 540e59260..1854f5d94 100644 --- a/src/client/pages/ChannelRoomPreview.tsx +++ b/src/client/pages/ChannelRoomPreview.tsx @@ -133,11 +133,9 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) const samplePictureId = "sample-screen-0"; const sampleFlowsShown = picture === "candidate" || picture === "handoff"; const omitSamplePicture = !sharingRoom && (sampleFlowsShown || picture === "paused" || pictureSamples.some(([mode]) => mode !== "playing" && mode === picture)); - const [watchError, setWatchError] = useState(null); - const watchFailure = async (name: string, report: boolean | (() => boolean) = true) => { + const watchFailure = async (name: string) => { if (new URLSearchParams(location.search).get("fails") !== name) return; await new Promise(resolve => setTimeout(resolve, 900)); - if (typeof report === "function" ? report() : report) setWatchError("request_timeout"); throw new Error("request_timeout"); }; const actionFails = (name: string) => { if (new URLSearchParams(location.search).get("fails") === name) throw new Error("request_timeout"); }; @@ -396,7 +394,7 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) if (pendingScreenRoom) pending.add(`screen:${pendingScreenRoom}`); if (requesting) pending.add(`watch:${samplePictureId}`); const channel = { ...sample.channel, state, self: profiles.get(users[0].id)!, profiles, streams: omitSamplePicture ? new Map([...[...streams].filter(([id]) => id !== samplePictureId), - ...selectedSample ? [[samplePictureId, selectedSample.stream] as const] : []]) : streams, error: watchError, siteURL: "https://friends.example/", + ...selectedSample ? [[samplePictureId, selectedSample.stream] as const] : []]) : streams, siteURL: "https://friends.example/", pending, watchPlayers, roomOpenFailures: unopened && hostOffline ? new Map([["friday", unopened]]) : sample.channel.roomOpenFailures, watchMediaChoices: async () => new URLSearchParams(location.search).has("mpd-tracks") ? { choices: [], indexed: [], mpd: mpdSample.map(({ candidate }) => ({ candidate })) } @@ -498,10 +496,10 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) setWatchMode("owner"); setWatchActivity({ id: `sample-watch-${crypto.randomUUID()}`, roomId, viewerSessionIds: [], source: { kind: "media", url }, userId: "sample-ada", sessionId: "sample-ada-session", playback: { timeline: "media" as const, position: 0, paused: true, rate: 1, anchorTime: 0 } }); }, - joinWatch: async (_id, mode = "direct", report) => { await watchFailure("watch-join", report); setReceiveMode(mode); setWatchMode(watchActivity?.playback.timeline === "program" ? "live-viewer" : "viewer"); }, + joinWatch: async (_id, mode = "direct") => { await watchFailure("watch-join"); setReceiveMode(mode); setWatchMode(watchActivity?.playback.timeline === "program" ? "live-viewer" : "viewer"); }, watchEmbedPreparation: () => undefined, cancelWatchPage: () => setPageSample(undefined), - leaveWatch: async () => { setWatchPlayers(new Map()); await watchFailure("watch-leave", false); setWatchMode("available"); setPageSample(undefined); }, - stopWatch: async () => { setWatchPlayers(new Map()); await watchFailure("watch-stop", false); setWatchActivity(null); }, + leaveWatch: async () => { setWatchPlayers(new Map()); await watchFailure("watch-leave"); setWatchMode("available"); setPageSample(undefined); }, + stopWatch: async () => { setWatchPlayers(new Map()); await watchFailure("watch-stop"); setWatchActivity(null); }, resumeWatch: async id => { const player = watchPlayers.get(id); if (!player) return; @@ -569,7 +567,7 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) setScreenTitle: async (id, title) => { if (ownedScreens.has(id)) setTitles(previous => ({ ...previous, [id]: title })); }, inputPolicy: async () => sample.received(), inputDecide: async () => sample.received(), inputSimultaneous: async () => sample.received(), inputShortcut: async () => { throw new Error("No input device in this preview"); }, - screenPresentation: () => {}, screenPlaybackError: () => undefined, reconnect: sample.received, clearError: () => setWatchError(null), + screenPresentation: () => {}, screenPlaybackError: () => undefined, reconnect: sample.received, setVoiceMuted: () => sample.received(), setVoiceVolume: () => sample.received(), updateProfile: sample.channel.updateProfile, updateDomain: sample.channel.updateDomain, setRoomCreationPolicy: async policy => setRoomCreationPolicy(policy), diff --git a/src/client/ui/use-settings-action.ts b/src/client/ui/use-settings-action.ts index 0f9038523..6d1203af1 100644 --- a/src/client/ui/use-settings-action.ts +++ b/src/client/ui/use-settings-action.ts @@ -39,7 +39,7 @@ type ActionFailure = { code: string; label?: string; retry(): Promise }; /** A surface owns keyed results; optional rows limit them to entities still present. */ export function useKeyedSettingsAction(owner: string, rows?: readonly { id: string }[]): { - errors: ReadonlyMap; run(key: string, work: (reportError: () => boolean) => Promise, label?: string): Promise; clearError(key: string): void; + errors: ReadonlyMap; run(key: string, work: () => Promise, label?: string): Promise; clearError(key: string): void; } { const [errors, setErrors] = useState>(new Map()); const lifetime = useRef(null); @@ -63,15 +63,15 @@ export function useKeyedSettingsAction(owner: string, rows?: readonly { id: stri next.delete(key); return next; }), []); - const run = useCallback(async function attempt(key: string, work: (reportError: () => boolean) => Promise, label?: string): Promise { + const run = useCallback(async function attempt(key: string, work: () => Promise, label?: string): Promise { const current = lifetime.current; if (!current) return; clearError(key); - const reportError = () => lifetime.current !== current || liveRows.current?.some(row => row.id === key) === false; - try { await work(reportError); } + const isCurrent = () => lifetime.current === current && (liveRows.current?.some(row => row.id === key) ?? true); + try { await work(); } catch (error) { const failure = settingsActionFailure(error); - if (!reportError() && failure) setErrors(previous => new Map(previous).set(key, { code: failure, label, retry: async () => { if (!reportError()) await attempt(key, work, label); } })); + if (isCurrent() && failure) setErrors(previous => new Map(previous).set(key, { code: failure, label, retry: async () => { if (isCurrent()) await attempt(key, work, label); } })); } }, [clearError]); return { errors, run, clearError }; diff --git a/tests/channel-picture-feedback.test.ts b/tests/channel-picture-feedback.test.ts index 55ce439f7..f9283a02e 100644 --- a/tests/channel-picture-feedback.test.ts +++ b/tests/channel-picture-feedback.test.ts @@ -44,17 +44,11 @@ test("picture feedback follows live publications across room views and reconnect expect(action.errors.size).toBe(0); await render(["live"]); let reject!: (error: Error) => void; - let report!: () => boolean; let pending!: Promise; await act(() => { - pending = action.run("live", fallback => { - report = fallback; - return new Promise((_, rejectWork) => { reject = rejectWork; }); - }); + pending = action.run("live", () => new Promise((_, rejectWork) => { reject = rejectWork; })); }); - expect(report()).toBe(false); await render([]); - expect(report()).toBe(true); await act(async () => { reject(new Error("late")); await pending; }); expect(action.errors.size).toBe(0); await render(["live"]); diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts index d8a42b6c2..76e5a18e4 100644 --- a/tests/channel-session.test.ts +++ b/tests/channel-session.test.ts @@ -2546,19 +2546,22 @@ test("a voice join owned by its control returns the failure without the page ban } finally { session.close(); } }); -test.each([[false, null], [true, "room_host_offline"]] as const)("a Watch owned by its picture reaches the banner only once that owner is gone (gone: %s)", async (gone, banner) => { +test("a manual picture Watch returns its failure and preserves the session notice", async () => { const { session, socket } = await setup(); socket.receive({ type: "state", state: { ...session.getSnapshot().state!, publications: [ { audience: [], id: "screen", roomId: "first", sessionId: "source", userId: "friend", kind: "screen", source: { kind: "screen", name: null }, title: null, videoSettings: screenVideoSettings(QUALITY_PROFILES["1080p30"]), paused: false }, ] } }); try { - const watching = session.watch("screen", undefined, undefined, () => gone); + socket.receive({ type: "error", code: "directory_storage_failed" }); + const watching = session.watch("screen"); + const errorWhilePending = session.getSnapshot().error; const request = socket.sent.at(-1)!; expect(request).toMatchObject({ type: "subscribe", publicationId: "screen", enabled: true }); socket.receive({ type: "reply", requestId: request.requestId, result: { type: "error", code: "room_host_offline" } }); await expect(watching).rejects.toThrow("room_host_offline"); - expect(session.getSnapshot().error).toBe(banner); + expect(errorWhilePending).toBe("directory_storage_failed"); + expect(session.getSnapshot().error).toBe("directory_storage_failed"); } finally { session.close(); } }); @@ -5776,7 +5779,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), false)); + await vi.waitFor(() => expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal))); 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" }); @@ -5831,7 +5834,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), false); + expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal)); } else { capture.mockRejectedValueOnce(new DOMException("Denied", "NotAllowedError")); await expect(session.startScreen("first", source)).rejects.toMatchObject({ name: "NotAllowedError" }); @@ -5878,7 +5881,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), false); + expect(watch).toHaveBeenCalledWith(publicationId, "first", expect.any(AbortSignal)); } } finally { session.close(); } }); @@ -12243,6 +12246,9 @@ test("a committed domain restore with unavailable hosting keeps the restored ide const retry = ChannelSocket.current; await retry.onopen?.(); expect(retry.sent.find(command => command.type === "join")).toMatchObject({ ownerKey: metadata.ownerKey }); expect(retry.sent.find(command => command.type === "join")).not.toHaveProperty("credential"); + retry.receive({ type: "welcome", ...PRODUCT_VERSION, credential: "old-authority", sessionId: "endpoint", state: oldState }); + expect(saved).not.toHaveBeenCalled(); + expect(session.getSnapshot()).toMatchObject({ connection: "closed", state: null, error: "domain_restored_connection_failed" }); expect(fetch).toHaveBeenCalledOnce(); } finally { session.close(); } }); @@ -13798,7 +13804,9 @@ test("a peer-only HLS join shares the stage's pending capability check", async ( playback: { timeline: "media", position: 0, paused: true, rate: 1, anchorTime: 1000 } }; try { socket.receive({ type: "state", state: { ...session.getSnapshot().state!, watchActivities: [activity] } }); + socket.receive({ type: "error", code: "directory_storage_failed" }); await expect(session.joinWatch(activity.id)).rejects.toBe(failure); + expect(session.getSnapshot().error).toBe("directory_storage_failed"); const checking = watchMedia.probeWatchHls(), joining = session.joinWatch(activity.id); expect(socket.sent.some(command => command.type === "join_watch")).toBe(false); await checking; @@ -14290,10 +14298,12 @@ test.each(["channel", "writer"])("local video leave clears its audience membersh const offline = structuredClone(state); offline.channel.rooms[0].available = false; socket.receive({ type: "state", state: offline }); expect(session.getSnapshot().watchPlayers.get(activity.id)?.video).toBe(video); + socket.receive({ type: "error", code: "directory_storage_failed" }); const leaving = session.leaveWatch(activity.id); const leave = socket.sent.findLast(command => command.type === "join_watch")!; socket.receive({ type: "reply", requestId: leave.requestId, result: { type: "error", code: "room_host_offline" } }); await expect(leaving).rejects.toThrow("room_host_offline"); + expect(session.getSnapshot().error).toBe("directory_storage_failed"); } else { socket.close(); await session.leaveWatch(activity.id); } @@ -16676,15 +16686,18 @@ test.each([false, true])("manual picture retry restores Browser viewing before A } finally { session.close(); } }); -test("a picture retry owned by its picture returns the failure without the page banner", async () => { +test("a manual picture retry returns its failure and preserves the session notice", async () => { const { session, socket } = await retryPictureFixture(); try { - const retry = session.retryPicture("one", () => false); + socket.receive({ type: "error", code: "directory_storage_failed" }); + const retry = session.retryPicture("one"); + const errorWhilePending = session.getSnapshot().error; const off = socket.sent.at(-1)!; expect(off).toMatchObject({ type: "subscribe", publicationId: "one", enabled: false }); socket.receive({ type: "reply", requestId: off.requestId, result: { type: "error", code: "request_timeout" } }); await expect(retry).rejects.toThrow("request_timeout"); - expect(session.getSnapshot().error).toBeNull(); + expect(errorWhilePending).toBe("directory_storage_failed"); + expect(session.getSnapshot().error).toBe("directory_storage_failed"); } finally { session.close(); } }); @@ -16763,7 +16776,7 @@ test("manual picture retry reports a rejected reacquisition without retiring sib socket.receive({ type: "reply", requestId: off.requestId, result: { type: "done" } }); await vi.waitFor(() => expect(socket.sent.at(-1)).toMatchObject({ type: "subscribe", publicationId: "one", enabled: true })); const on = socket.sent.at(-1)!; socket.receive({ type: "reply", requestId: on.requestId, result: { type: "error", code: "room_unavailable" } }); await rejected; - expect(session.getSnapshot().error).toBe("room_unavailable"); expect(session.getSnapshot().state?.subscriptions).toContain("two"); + expect(session.getSnapshot().error).toBeNull(); expect(session.getSnapshot().state?.subscriptions).toContain("two"); expect(session.getSnapshot().state?.voice.some(v => v.roomId === "first")).toBe(true); expect(pc.close).not.toHaveBeenCalled(); expect(socket.sent.filter(c => c.type === "subscribe" && c.publicationId === "one").slice(-2)).toEqual([off, on]); } finally { session.close(); } @@ -16782,6 +16795,38 @@ test("manual picture retry rejects a duplicate or failed withdrawal through the }); +test.each(["voice", "publish"])("leaving voice releases a pending %s reply before rejoining", async pending => { + const { session, socket } = await setup(3, false); + const raw = remoteTrack("audio"), clone = remoteTrack("audio"); + const contexts = microphoneMixer([remoteStream("room", [clone])]); + vi.stubGlobal("navigator", { mediaDevices: { getUserMedia: async () => remoteStream("source", [raw]) } }); + const next = nextSocketCommand(socket, "voice"); + const first = session.joinVoice("first").catch(error => error); + try { + let stale = await next; + if (pending === "publish") { + const publishing = nextSocketCommand(socket, "publish"); + socket.receive({ type: "reply", requestId: stale.requestId, result: { type: "done" } }); + stale = await publishing; + } + await session.leaveVoice("first"); + expect(socket.sent.at(-1)).toMatchObject({ type: "voice", roomId: "first", joined: false }); + expect(raw.stop).toHaveBeenCalledOnce(); + expect(contexts[0].close).toHaveBeenCalledOnce(); + if (pending === "publish") expect(clone.stop).toHaveBeenCalledOnce(); + await vi.waitFor(() => expect(session.voiceBusy("first")).toBe(false), { timeout: 200 }); + expect(await first).toMatchObject({ name: "AbortError" }); + + const listening = session.joinVoice("first", true); + const current = socket.sent.at(-1)!; + socket.receive({ type: "reply", requestId: stale.requestId, result: pending === "publish" ? { type: "done" } : { type: "error", code: "room_unavailable" } }); + expect(session.voiceBusy("first")).toBe(true); + socket.receive({ type: "reply", requestId: current.requestId, result: { type: "done" } }); + await listening; + expect(session.getSnapshot().error).toBeNull(); + } finally { session.close(); await first; } +}); + test("last voice leave retires an unresolved microphone request before a late permission grant", async () => { const { session, socket } = await setup(3, false); const contexts = microphoneMixer([]), late = remoteTrack("audio"); diff --git a/tests/text-participant.test.ts b/tests/text-participant.test.ts index 7de3bbb84..167a1aea4 100644 --- a/tests/text-participant.test.ts +++ b/tests/text-participant.test.ts @@ -228,6 +228,37 @@ test('a rejected room selection can be retried without exposing or mixing unconf } }); +test('reconnect during stop preserves the socket until leave receives its reply', async () => { + const { TextParticipant } = await import('../prototype/channel-browser/node/text-participant'); + const server = new WebSocketServer({ host: '127.0.0.1', port: 0 }); + await once(server, 'listening'); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Expected loopback port'); + const client = new TextParticipant({ url: 'ws://127.0.0.1:' + address.port, origin: 'http://127.0.0.1' }); + try { + const accepted = once(server, 'connection'); + const connected = client.connect(); + const [socket] = await accepted; + await once(socket, 'message'); + socket.send(JSON.stringify({ type: 'welcome', ...PRODUCT_VERSION, credential: 'fixture', + sessionId: randomUUID(), selfProfile: { id: randomUUID() }, state: { channel: { hostingMode: 'hosted', rooms: [] }, sessions: [] } })); + await connected; + + const received = once(socket, 'message'); + const stopped = client.stop().catch((error: Error) => error); + const [raw] = await received; + const leave = JSON.parse(raw.toString()); + expect(leave.type).toBe('leave'); + await expect(client.reconnect()).rejects.toThrow('closed'); + socket.send(JSON.stringify({ type: 'reply', requestId: leave.requestId, result: { type: 'done' } })); + expect(await stopped).toBeUndefined(); + } finally { + for (const socket of server.clients) socket.terminate(); + await client.stop().catch(() => {}); + await new Promise(resolve => server.close(() => resolve())); + } +}); + test('narrow conversation verification keeps authority required and signed records closed', async () => { const rust = await import('../prototype/channel-browser/pkg/piik_channel_browser.js'); await rust.default({ module_or_path: await readFile('prototype/channel-browser/pkg/piik_channel_browser_bg.wasm') });