Skip to content

Commit e70dd1a

Browse files
wesbillmanBrain
andauthored
fix(desktop): actually close relay sockets — plugin:websocket|disconnect does not exist (#1481)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
1 parent 3e282a2 commit e70dd1a

6 files changed

Lines changed: 117 additions & 22 deletions

File tree

‎desktop/src/shared/api/readOnlyRelayClient.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
sortEvents,
88
type RelaySubscriptionFilter,
99
} from "@/shared/api/relayClientShared";
10+
import { closeWebSocket } from "@/shared/api/relayWebSocketClose";
1011

1112
const AUTH_TIMEOUT_MS = 8_000;
1213
const HISTORY_TIMEOUT_MS = 8_000;
@@ -62,9 +63,7 @@ export class ReadOnlyRelayClient {
6263
this.generation++;
6364

6465
if (this.wsId !== null) {
65-
void invoke("plugin:websocket|disconnect", { id: this.wsId }).catch(
66-
() => {},
67-
);
66+
void closeWebSocket(this.wsId, "observer disconnected");
6867
this.wsId = null;
6968
}
7069

‎desktop/src/shared/api/relayClientSession.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
shouldScheduleReconnect,
3535
} from "@/shared/api/relayReconnectPolicy";
3636
import { RelayStallWatchdog } from "@/shared/api/relayStallWatchdog";
37+
import { closeWebSocket } from "@/shared/api/relayWebSocketClose";
3738
import { buildThreadReferenceTags } from "@/features/messages/lib/threading";
3839

3940
const RECONNECT_BASE_DELAY_MS = 1_000,
@@ -114,9 +115,7 @@ export class RelayClient {
114115
this.connectionStateEmitter.set("idle");
115116

116117
if (this.wsId !== null) {
117-
void invoke("plugin:websocket|disconnect", { id: this.wsId }).catch(
118-
() => {},
119-
);
118+
void closeWebSocket(this.wsId, "workspace switch");
120119
this.wsId = null;
121120
}
122121

@@ -981,11 +980,7 @@ export class RelayClient {
981980
}
982981

983982
if (this.wsId !== null) {
984-
void invoke("plugin:websocket|disconnect", { id: this.wsId }).catch(
985-
(err) => {
986-
console.warn("[RelayClientSession] disconnect failed:", err);
987-
},
988-
);
983+
void closeWebSocket(this.wsId, "connection reset");
989984
}
990985

991986
this.wsId = null;
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import assert from "node:assert/strict";
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import test from "node:test";
5+
import { fileURLToPath } from "node:url";
6+
7+
import { closeWebSocket } from "./relayWebSocketClose.ts";
8+
9+
test("closeWebSocket sends a Close frame through plugin:websocket|send", async () => {
10+
const calls = [];
11+
await closeWebSocket(42, "workspace switch", async (cmd, args) => {
12+
calls.push({ cmd, args });
13+
});
14+
15+
assert.equal(calls.length, 1);
16+
assert.equal(calls[0].cmd, "plugin:websocket|send");
17+
assert.deepEqual(calls[0].args, {
18+
id: 42,
19+
message: {
20+
type: "Close",
21+
data: { code: 1000, reason: "workspace switch" },
22+
},
23+
});
24+
});
25+
26+
test("closeWebSocket swallows send failures (socket already gone)", async () => {
27+
await closeWebSocket(7, "connection reset", async () => {
28+
throw new Error("WebSocket connection not found");
29+
});
30+
});
31+
32+
// Regression guard: tauri-plugin-websocket registers only `connect` and
33+
// `send` — there is no `disconnect` command. Invoking one rejects silently
34+
// and leaks the socket (relay zombie pile, workspace-switch disconnects).
35+
// Any socket teardown must go through closeWebSocket.
36+
test("no source file invokes the nonexistent plugin:websocket|disconnect command", () => {
37+
const srcRoot = path.resolve(
38+
path.dirname(fileURLToPath(import.meta.url)),
39+
"..",
40+
"..",
41+
);
42+
const offenders = [];
43+
44+
const walk = (dir) => {
45+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
46+
const full = path.join(dir, entry.name);
47+
if (entry.isDirectory()) {
48+
walk(full);
49+
continue;
50+
}
51+
if (!/\.(ts|tsx|js|jsx|mjs)$/.test(entry.name)) continue;
52+
if (full === fileURLToPath(import.meta.url)) continue;
53+
if (
54+
fs.readFileSync(full, "utf8").includes("plugin:websocket|disconnect")
55+
) {
56+
offenders.push(path.relative(srcRoot, full));
57+
}
58+
}
59+
};
60+
walk(srcRoot);
61+
62+
assert.deepEqual(
63+
offenders,
64+
[],
65+
"plugin:websocket|disconnect does not exist in tauri-plugin-websocket — use closeWebSocket (Close frame via plugin:websocket|send) instead",
66+
);
67+
});
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { invoke } from "@tauri-apps/api/core";
2+
3+
/**
4+
* tauri-plugin-websocket 2.4.2 registers only `connect` and `send` — there is
5+
* no `disconnect` command, so invoking one rejects and the socket leaks. Close
6+
* the way the plugin's own JS API does: send a Close frame; the plugin's read
7+
* loop drops the connection when the peer echoes the Close (or the TCP read
8+
* stream terminates).
9+
*/
10+
export function closeWebSocket(
11+
id: number,
12+
reason: string,
13+
invokeFn: typeof invoke = invoke,
14+
): Promise<void> {
15+
return invokeFn("plugin:websocket|send", {
16+
id,
17+
message: {
18+
type: "Close",
19+
data: { code: 1000, reason },
20+
},
21+
}).then(
22+
() => undefined,
23+
(err) => {
24+
// Expected when the socket is already gone; greppable for anything else.
25+
console.debug(`closeWebSocket(${id}, ${reason}) rejected:`, err);
26+
},
27+
);
28+
}

‎desktop/src/testing/e2eBridge.ts‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7985,14 +7985,6 @@ export function maybeInstallE2eTauriMocks() {
79857985
return sendToMockSocket(
79867986
payload as Parameters<typeof sendToMockSocket>[0],
79877987
);
7988-
case "plugin:websocket|disconnect":
7989-
if (isRelayMode(activeConfig)) {
7990-
realSockets.get((payload as { id: number }).id)?.close();
7991-
realSockets.delete((payload as { id: number }).id);
7992-
return;
7993-
}
7994-
7995-
return disconnectMockSocket((payload as { id: number }).id);
79967988
case "plugin:window|show":
79977989
case "plugin:window|unminimize":
79987990
case "plugin:window|set_focus":

‎desktop/tests/e2e/onboarding.spec.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,15 +1316,29 @@ test("membership denial can import a different invited key", async ({
13161316

13171317
// Alice already has a relay profile with a display name, so after the
13181318
// identity swap the onboarding gate auto-completes.
1319+
// The identity swap must tear down the old relay socket. There is no
1320+
// `plugin:websocket|disconnect` command in tauri-plugin-websocket — closing
1321+
// is a Close frame sent through `plugin:websocket|send`.
13191322
await expect
13201323
.poll(() =>
13211324
page.evaluate(
13221325
() =>
1323-
(window as Window & { __BUZZ_E2E_COMMANDS__?: string[] })
1324-
.__BUZZ_E2E_COMMANDS__ ?? [],
1326+
(
1327+
window as Window & {
1328+
__BUZZ_E2E_COMMAND_PAYLOADS__?: Array<{
1329+
command: string;
1330+
payload: unknown;
1331+
}>;
1332+
}
1333+
).__BUZZ_E2E_COMMAND_PAYLOADS__?.some(
1334+
(entry) =>
1335+
entry.command === "plugin:websocket|send" &&
1336+
(entry.payload as { message?: { type?: string } })?.message
1337+
?.type === "Close",
1338+
) ?? false,
13251339
),
13261340
)
1327-
.toEqual(expect.arrayContaining(["plugin:websocket|disconnect"]));
1341+
.toBe(true);
13281342
await expect
13291343
.poll(() =>
13301344
page.evaluate((storageKey) => {

0 commit comments

Comments
 (0)