fix: acknowledge TS6 screen cleanup and include removal reason

This commit is contained in:
illusia committed 2026-10-03 14:31:45 +08:00
1 parent 77fef3bed9
commit 921e83dfb3
5 files changed
+158 -12

No files matched your search

@@ -161,3 +161,56 @@ test("a failed old native join cannot remove a newer membership", async () => {
assert.equal(f.list(viewer)[0]?.viewerCount, 1);
assert.equal(f.messages.some(({ message }) => message.type === "screenShareError" && message.requestId === "old"), false);
});
test("leaving a native source includes the removal reason required by TS6", () => {
const f = fixture();
const viewer = f.participant("viewer", 2);
viewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
f.coordinator.handleNotification(viewer, { name: "notifystreamstarted", params: { id: "native", clid: "17" } });
f.handle(viewer, { type: "screenShareJoin", streamId: "native" });
f.handle(viewer, { type: "screenShareLeave", streamId: "native" });
assert.ok(f.commands.some(({ command }) => command === "removeclientfromstream id=native clid=2 reason=1"));
});
test("a refused native viewer removal retains membership and reports failure until retry succeeds", async () => {
const f = fixture();
const owner = f.participant("owner", 1);
const streamId = f.start(owner);
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "native", clid: "1" } });
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "native", clid: "17" } });
let reject!: (error: Error) => void;
const denied = new Promise<void>((_, no) => { reject = no; });
owner.tsClient.sendProtocolCommand = command => {
assert.equal(command, "removeclientfromstream id=native clid=17 reason=1");
return denied;
};
const close: ScreenShareClientMessage = { type: "screenShareSignal", streamId, targetPeerId: "ts-viewer-17", signal: { kind: "close" } };
f.handle(owner, close);
assert.equal(f.list(owner)[0]?.viewerCount, 1);
reject(new Error("denied"));
await nextTurn();
assert.equal(f.list(owner)[0]?.viewerCount, 1);
assert.equal(f.messages.some(({ message }) => message.type === "screenShareViewerLeft"), false);
assert.ok(f.messages.some(({ message }) => message.type === "screenShareError" && message.code === "SCREEN_SHARE_SIGNAL_FAILED"));
owner.tsClient.sendProtocolCommand = async () => {};
f.handle(owner, close);
await nextTurn();
assert.equal(f.list(owner)[0]?.viewerCount, 0);
assert.equal(f.messages.filter(({ message }) => message.type === "screenShareViewerLeft").length, 1);
});
test("native removal notification and acknowledgement publish only one viewer-left event", async () => {
const f = fixture();
const owner = f.participant("owner", 1);
const streamId = f.start(owner);
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "native", clid: "1" } });
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "native", clid: "17" } });
let resolve!: () => void;
owner.tsClient.sendProtocolCommand = () => new Promise<void>(yes => { resolve = yes; });
f.handle(owner, { type: "screenShareSignal", streamId, targetPeerId: "ts-viewer-17", signal: { kind: "close" } });
f.coordinator.handleNotification(owner, { name: "notifystreamclientleft", params: { id: "native", clid: "17" } });
resolve();
await nextTurn();
assert.equal(f.list(owner)[0]?.viewerCount, 0);
assert.equal(f.messages.filter(({ message }) => message.type === "screenShareViewerLeft").length, 1);
});
+18 -6
View File
@@ -257,7 +257,9 @@ export class ScreenShareCoordinator {
void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", {
id: stream.teamSpeakStreamId,
reason: "1",
})).catch(() => undefined);
})).catch((error: unknown) => {
this.logger.warn({ streamId: stream.teamSpeakStreamId, err: error instanceof Error ? error.message : String(error) }, "Could not stop native screen publication");
});
}
}
const message: ServerMessage = { type: "screenShareStopped", streamId: stream.streamId, reason };
@@ -275,6 +277,7 @@ export class ScreenShareCoordinator {
void entry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", {
id: stream.streamId,
clid: String(entry.tsClient.getClientId()),
reason: "1",
})).catch(() => undefined);
}
this.sendToEntry(entry.id, { type: "screenShareLeft", streamId: stream.streamId });
@@ -330,11 +333,20 @@ export class ScreenShareCoordinator {
void publisher.tsClient.sendProtocolCommand(buildTeamSpeakCommand("removeclientfromstream", {
id: stream.teamSpeakStreamId,
clid: String(viewerClid),
})).catch(() => undefined);
stream.nativeViewerClids.delete(viewerClid);
stream.viewerCount = this.screenShareViewerCount(stream);
this.sendToEntry(entry.id, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: targetPeerId });
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
reason: "1",
})).then(() => {
if (this.entries.get(entry.id) !== entry
|| this.screenStreams.get(screenStreamKey(stream.targetKey, stream.streamId)) !== stream
|| !stream.nativeViewerClids.delete(viewerClid)) return;
// The native notification may already have removed this viewer.
stream.viewerCount = this.screenShareViewerCount(stream);
this.sendToEntry(entry.id, { type: "screenShareViewerLeft", streamId: stream.streamId, viewerPeerId: targetPeerId });
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
}).catch((error: unknown) => {
if (this.entries.get(entry.id) !== entry
|| this.screenStreams.get(screenStreamKey(stream.targetKey, stream.streamId)) !== stream) return;
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "无法移除 TeamSpeak 观看者" });
});
return;
}
if (signal.kind === "answer") {
+53
View File
@@ -39,6 +39,59 @@ function fixture() {
return { client, sdk, state };
}
test("stream commands wait for server acknowledgement and propagate refusals", async () => {
const f = fixture();
const ack = deferred<void>();
f.sdk.inputUpdate = () => ack.promise;
let completed = false;
const pending = f.client.sendProtocolCommand("setupstream name=Test").then(() => { completed = true; });
await nextTurn();
assert.equal(completed, false);
ack.resolve();
await pending;
f.sdk.inputUpdate = async () => { throw new Error("missing required parameter"); };
await assert.rejects(f.client.sendProtocolCommand("removeclientfromstream id=test"), /missing required parameter/);
});
test("stream cleanup flood retries back off and stop after two retries", async t => {
const f = fixture();
t.mock.timers.enable({ apis: ["setTimeout"] });
const flooding = new Error("TeamSpeak server error: client is flooding (id=524)");
f.sdk.inputUpdate = async () => { throw flooding; };
const pending = assert.rejects(f.client.sendProtocolCommand("stopstream id=test reason=1"), error => error === flooding);
await nextTurn();
t.mock.timers.tick(3999);
await nextTurn();
assert.equal(f.sdk.inputCommands.length, 1);
t.mock.timers.tick(1);
await nextTurn();
assert.equal(f.sdk.inputCommands.length, 2);
t.mock.timers.tick(8000);
await pending;
assert.equal(f.sdk.inputCommands.length, 3);
});
test("stream signaling flood refusals are not replayed", async () => {
const f = fixture();
f.sdk.inputUpdate = async () => { throw new Error("TeamSpeak server error: client is flooding (id=524)"); };
await assert.rejects(f.client.sendProtocolCommand("streamsignaling id=test clid=2 json=payload"), /flooding/);
assert.equal(f.sdk.inputCommands.length, 1);
});
test("stream cleanup retries cannot reach a replacement connection", async t => {
const f = fixture();
t.mock.timers.enable({ apis: ["setTimeout"] });
f.sdk.inputUpdate = async () => { throw new Error("TeamSpeak server error: client is flooding (id=524)"); };
const pending = assert.rejects(f.client.sendProtocolCommand("removeclientfromstream id=test clid=2 reason=1"), /not ready/);
await nextTurn();
await f.client.disconnect();
f.state.client = f.sdk;
f.state.connected = true;
t.mock.timers.tick(4000);
await pending;
assert.equal(f.sdk.inputCommands.length, 1);
});
test("accompaniment remains audible with the microphone muted and stopping restores mute", async () => {
const f = fixture();
await f.client.setInputMuted(true);
+19 -2
View File
@@ -439,8 +439,25 @@ export class TSClient extends EventEmitter {
* assembled by the trusted server-side stream adapter, never by the browser.
*/
async sendProtocolCommand(command: string): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
await this.client.sendCommandNoWait(command);
const client = this.client;
const generation = this.connectionGeneration;
const isCurrent = () => client !== null && this.client === client && this.connected && this.connectionGeneration === generation;
const cleanup = /^(?:stopstream|removeclientfromstream)(?:\s|$)/.test(command);
for (let attempt = 0; ; attempt++) {
if (!isCurrent()) throw new Error("TeamSpeak session is not ready");
try {
// Stream lifecycle callers need the server's acknowledgement, not
// merely confirmation that the command was handed to the transport.
await client!.execCommand(command);
if (!isCurrent()) throw new Error("TeamSpeak session changed while sending stream command");
return;
} catch (error: unknown) {
if (!cleanup || !isCurrent() || attempt >= 2 || normalizeTeamSpeakError(error).code !== "flooding") throw error;
// Only retry an explicit refusal of cleanup. Never replay offers or
// ICE candidates, and never carry an old cleanup into a new connection.
await new Promise<void>(resolve => setTimeout(resolve, (attempt + 1) * 4000));
}
}
}
getIdentityString(): string {