Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

test(server): ws.test.ts tears down its sockets and resets the platform

enes0aec93eadc42
diff --git a/src/server/ws.test.ts b/src/server/ws.test.ts
index da9d690f7..39595d2c6 100644
--- a/src/server/ws.test.ts
+++ b/src/server/ws.test.ts
@@ -8,9 +8,22 @@ import { Auth } from './auth'
import { ServerPlatform } from './platform-server'
import { attachWsServer } from './ws'
import { SESSION_COOKIE } from './http'
-import { initPlatform } from '../core/platform'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import { presenceHub } from '../core/presence/hub'
+import { IPC } from '../shared/ipc'
let dir: string, server: http.Server, port: number, auth: Auth, platform: ServerPlatform, cookie: string
+/** Every socket this file opens, so afterEach can tear them all down (see below). */
+let sockets: WebSocket[] = []
+
+/** Poll until `pred` holds (or throw after ~2s) — socket teardown is async. */
+async function until(pred: () => boolean, what: string): Promise<void> {
+ for (let i = 0; i < 200; i++) {
+ if (pred()) return
+ await new Promise((r) => setTimeout(r, 10))
+ }
+ throw new Error(`timed out waiting for: ${what}`)
+}
beforeEach(async () => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-ws-'))
@@ -24,19 +37,37 @@ beforeEach(async () => {
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
port = (server.address() as { port: number }).port
cookie = `${SESSION_COOKIE}=${auth.createSession()}`
+ sockets = []
})
afterEach(async () => {
+ // Tear the sockets down BEFORE the platform, and wait for the server side to notice. The
+ // presence hub is a process-wide singleton while each test builds a fresh ServerPlatform whose
+ // uiIds restart at 1 — so a socket whose 'close' (→ presenceHub.leave(uiId)) lands after the
+ // test boundary would leave/join against the NEXT test's peers. Draining the hub is the
+ // authoritative signal that every server-side 'close' handler has run.
+ for (const ws of sockets) ws.terminate()
+ sockets = []
+ await until(() => presenceHub.peers().length === 0, 'presence hub drains')
await new Promise((r) => server.close(r))
- // Deliberately NOT resetPlatformForTests(): a socket's 'close' can fire a tick after
- // server.close() resolves, and that handler leaves the presence hub — with the platform torn
- // out from under it, that async callback would throw as an uncaught exception. The next
- // beforeEach replaces the singleton anyway.
+ // Safe now: no socket, so no late callback can reach a torn-out platform.
+ resetPlatformForTests()
fs.rmSync(dir, { recursive: true, force: true })
})
+/** Text frames each socket received, recorded from before 'open' so nothing pushed at connect
+ * time (presence:sync) can be missed by a listener attached one tick too late. */
+const recorded = new WeakMap<WebSocket, string[]>()
+function received(ws: WebSocket): string[] {
+ return recorded.get(ws) ?? []
+}
+
function connect(headers: Record<string, string>): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, { headers })
+ sockets.push(ws)
+ const rec: string[] = []
+ recorded.set(ws, rec)
+ ws.on('message', (d, isBinary) => { if (!isBinary) rec.push(d.toString()) })
ws.on('open', () => resolve(ws))
ws.on('error', reject)
})
@@ -107,4 +138,24 @@ describe('ws endpoint', () => {
ws1.close()
ws2.close()
})
+
+ // An ORDERED PAIR guarding afterEach's teardown. The presence hub is process-wide, but each test
+ // builds a fresh ServerPlatform whose uiIds restart at 1 — so a socket outliving its test would
+ // either leave() the next test's first peer or make its join() hit the hub's already-present
+ // early return (and that socket would then never get presence:sync). The first test deliberately
+ // abandons its socket; the second asserts the next test still starts clean.
+ it('joins the presence hub (socket deliberately left open for the next test)', async () => {
+ await connect({ cookie })
+ await until(() => presenceHub.peers().length === 1, 'the socket joins the hub')
+ })
+
+ it('starts with an empty hub, and its first socket receives its own presence:sync', async () => {
+ expect(presenceHub.peers()).toHaveLength(0)
+ const ws = await connect({ cookie })
+ await until(
+ () => received(ws).some((m) => JSON.parse(m).channel === IPC.presenceSync),
+ 'presence:sync on connect'
+ )
+ ws.close()
+ })
})