Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
e2e web session: address review round 1
AdityaUmale3f6a85e0fe29
diff --git a/src/lib/e2e/interop.test.ts b/src/lib/e2e/interop.test.tsindex a2f4711887..fc6fd577f4 100644--- a/src/lib/e2e/interop.test.ts+++ b/src/lib/e2e/interop.test.ts@@ -97,11 +97,15 @@ async function handshake(url: string, token: string, transport: TransportByte) {async function get(ws: ReturnType<typeof open>, keys: SessionKeys, path: string): Promise<string> {const body: Uint8Array[] = [];let sending = Promise.resolve();+ let failSend!: (error: unknown) => void;+ // A failed seal or send ends the wait for the reply at once instead of a receive timeout.+ const sendFailed = new Promise<never>((_resolve, reject) => (failSend = reject));let ended = false;const mux = new Mux("phone", {send: (frame) => {const plaintext = encodeFrame(frame);sending = sending.then(async () => ws.send(await keys.send.seal(plaintext)));+ sending.catch(failSend);},data: (_id, data) => body.push(data.slice()),ended: () => (ended = true),@@ -113,7 +117,7 @@ async function get(ws: ReturnType<typeof open>, keys: SessionKeys, path: string)const id = mux.open();const request = utf8(`GET ${path} HTTP/1.1\r\nHost: companion\r\nConnection: close\r\n\r\n`);expect(mux.write(id, request)).toBe(request.length);- while (!ended) mux.receive(decodeFrame(await keys.receive.open(await ws.next())));+ while (!ended) mux.receive(decodeFrame(await keys.receive.open(await Promise.race([ws.next(), sendFailed]))));mux.finish(id);expect(mux.has(id)).toBe(false);await sending;diff --git a/src/lib/e2e/session.test.ts b/src/lib/e2e/session.test.tsindex fcc45c9506..6151cc7612 100644--- a/src/lib/e2e/session.test.ts+++ b/src/lib/e2e/session.test.ts@@ -8,7 +8,8 @@ import { WebSocket as NodeWebSocket, WebSocketServer, type RawData } from "ws";import { b64u, concat, fromB64u, utf8, type Bytes } from "./bytes.ts";import { admission, credentialHash, keyId, psk } from "./credentials.ts";-import { dial, dialRelay, RELAY_PROTOCOL, SessionClosed, type E2EStream, type PhoneSession } from "./session.ts";+import type { SessionKeys } from "./noise.ts";+import { dial, dialRelay, PhoneSession, RELAY_PROTOCOL, SessionClosed, type E2EStream } from "./session.ts";const SERVER = fileURLToPath(new URL("../../../companion/src/e2e/interop-server.ts", import.meta.url));const BOUND_MS = 10_000;@@ -38,6 +39,12 @@ interface RelayNode {admitted: Set<string>;/** Refuse every phone with this code, as a full (4503) or rate-limiting (4429) node would. */refuseWith: number | null;+ /** The close reason sent with refuseWith. */+ refuseReason: string;+ /** The computer route it splices to; the real relay transport unless a test swaps in another responder. */+ computer: string | null;+ /** Close the phone with this code right after the computer's first message reaches it. */+ closeAfterFirst: number | null;/** Answer ready but never splice, so the handshake deadline passes. */stall: boolean;/** Drop everything the computer sends from now on, as a dead path would. */@@ -56,6 +63,9 @@ async function startNode(): Promise<RelayNode> {closes: [],admitted: new Set(),refuseWith: null,+ refuseReason: "",+ computer: null,+ closeAfterFirst: null,stall: false,mute: false,close: () =>@@ -65,12 +75,12 @@ async function startNode(): Promise<RelayNode> {server.close(() => resolve());}),};- const refuse = (socket: NodeWebSocket, code: number) => {+ const refuse = (socket: NodeWebSocket, code: number, reason?: string) => {node.closes.push(code);- socket.close(code);+ socket.close(code, reason);};wss.on("connection", (phone) => {- if (node.refuseWith !== null) return refuse(phone, node.refuseWith);+ if (node.refuseWith !== null) return refuse(phone, node.refuseWith, node.refuseReason);phone.once("message", (raw: RawData, isBinary: boolean) => {if (isBinary) return refuse(phone, 4400);let first: { t?: unknown; v?: unknown; hid?: unknown; adm?: unknown };@@ -83,12 +93,14 @@ async function startNode(): Promise<RelayNode> {if (first.t !== "phone" || first.v !== 1) return refuse(phone, 4400);if (first.hid !== b64u(HOST_ID) || !node.admitted.has(String(first.adm))) return refuse(phone, 4404);if (node.stall) return void phone.send(JSON.stringify({ t: "ready" }));- const data = new NodeWebSocket(ready.relayTransport, "omb-e2e.v1");+ const data = new NodeWebSocket(node.computer ?? ready.relayTransport, "omb-e2e.v1");data.on("open", () => {phone.send(JSON.stringify({ t: "ready" }));phone.on("message", (bytes: RawData, binary: boolean) => (binary ? data.send(bytes as Buffer) : refuse(phone, 4400)));data.on("message", (bytes: RawData) => {- if (!node.mute && phone.readyState === NodeWebSocket.OPEN) phone.send(bytes as Buffer);+ if (node.mute || phone.readyState !== NodeWebSocket.OPEN) return;+ phone.send(bytes as Buffer);+ if (node.closeAfterFirst !== null) refuse(phone, node.closeAfterFirst);});});// Close codes pass through, as the real relay's splice does.@@ -168,11 +180,17 @@ const health = async (session: PhoneSession) => text(await request(session, "GETdescribe("dialRelay: the browser phone through a relay node", () => {it("sends the pre-auth message, waits for ready, handshakes with the relay prologue and carries requests", async () => {+ const stranger = await startNode();const { node, options } = await admittingNode();const adm = b64u(options.adm);- const dialing = dialRelay({ ...options, urls: [node.url] });+ const urls = [stranger.url, node.url];+ const dialing = dialRelay({ ...options, urls });+ // Every attempt, the fallback node's too, sends what the caller passed at the call.options.adm.fill(0);+ options.psk.fill(0);+ urls.length = 0;const session = await dialing;+ expect(stranger.closes).toEqual([4404]);expect(node.firstMessages).toEqual([{ t: "phone", v: 1, hid: b64u(HOST_ID), adm }]);for (const reply of await Promise.all([health(session), health(session)])) {expect(reply.startsWith("HTTP/1.1 200")).toBe(true);@@ -195,7 +213,11 @@ describe("dialRelay: the browser phone through a relay node", () => {]);expect(text(upload)).toContain(JSON.stringify({ bytes: body.length, sha256 }));expect(text(download.subarray(0, 12))).toBe("HTTP/1.1 200");- expect(download.length).toBeGreaterThan(body.length);+ const headEnd = download.findIndex((_, i) => download[i] === 13 && download[i + 1] === 10 && download[i + 2] === 13 && download[i + 3] === 10);+ expect(headEnd).toBeGreaterThan(0);+ const downloaded = download.subarray(headEnd + 4);+ expect(downloaded.length).toBe(body.length);+ expect(downloaded.every((byte, index) => byte === index % 251)).toBe(true);session.shutdown();});@@ -215,6 +237,26 @@ describe("dialRelay: the browser phone through a relay node", () => {await expect(failure).rejects.toMatchObject({ code: 4404 });});+ it("waits the delay a 4503 asks for before the next node", async () => {+ const full = await startNode();+ full.refuseWith = 4503;+ full.refuseReason = JSON.stringify({ retryInMs: 400 });+ const { node, options } = await admittingNode();+ const started = Date.now();+ const session = await dialRelay({ ...options, urls: [full.url, node.url] });+ expect(Date.now() - started).toBeGreaterThanOrEqual(400);+ session.shutdown();+ });++ it("stops hard on a message 2 that fails to verify, even when the node closes 4404 meanwhile", async () => {+ const { node: closing, options } = await admittingNode();+ closing.computer = ready.wrongKey;+ closing.closeAfterFirst = 4404;+ const { node: next } = await admittingNode();+ await expect(dialRelay({ ...options, urls: [closing.url, next.url] })).rejects.toThrow("e2e: aead");+ expect(next.firstMessages).toEqual([]);+ });+it("does not try another node after any other code", async () => {const strict = await startNode();strict.refuseWith = 4429;@@ -272,4 +314,82 @@ describe("dial: the direct route", () => {await expect(stream.write(utf8("more"))).rejects.toThrow("stream reset");expect(() => session.open()).toThrow(SessionClosed);});++ it("refuses writes once its FIN is sent, while the computer's half is still open", async () => {+ const { psk: key } = await credentials(ready.deviceToken);+ const session = await dial({ url: ready.direct, remoteStatic, psk: key, app: "web-test/1" });+ const stream = session.open();+ const reader = stream.readable.getReader();+ await stream.write(utf8("GET /hang HTTP/1.1\r\nHost: companion\r\n\r\n"));+ expect(text((await reader.read()).value!)).toContain("data: start");+ stream.end();+ await expect(stream.write(utf8("more"))).rejects.toThrow("stream ended");+ session.close(1000);+ });+});++/** A socket that records what the session sends, and records sealed and opened as themselves. */+function fakeSession(seal: (plaintext: Bytes) => Promise<Bytes> = async (plaintext) => plaintext) {+ const sent: Bytes[] = [];+ const closes: Array<number | undefined> = [];+ const socket = {+ bufferedAmount: 0,+ send: (record: Bytes) => sent.push(record.slice()),+ close: (code?: number) => closes.push(code),+ onmessage: null as ((event: MessageEvent) => void) | null,+ onclose: null as ((event: CloseEvent) => void) | null,+ };+ const keys = { send: { seal }, receive: { open: async (record: Bytes) => record } } as unknown as SessionKeys;+ const session = new PhoneSession(socket as unknown as WebSocket, keys);+ const record = (...bytes: number[]) => session.receive({ data: Uint8Array.from(bytes).buffer } as MessageEvent);+ const remoteClose = (code: number) => socket.onclose!({ code } as CloseEvent);+ return { session, sent, closes, record, remoteClose };+}++const GO_AWAY_REMOVED = [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3];+const GO_AWAY_PROTOCOL = [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];+/** A WindowUpdate {SYN} on stream 2: the computer may not open streams. */+const COMPUTER_OPEN = [0, 1, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0];++describe("PhoneSession records and closes", () => {+ it("reads a GoAway(3) still being opened before the 4001 close behind it ends the session", async () => {+ const { session, record, remoteClose } = fakeSession();+ record(...GO_AWAY_REMOVED);+ remoteClose(4001);+ expect(await session.closed).toBe(4001);+ expect(session.removed).toBe(true);+ });++ it("sends GoAway(1) on a yamux violation before closing 4000", async () => {+ const { session, sent, closes, record } = fakeSession();+ record(...COMPUTER_OPEN);+ expect(await session.closed).toBe(4000);+ expect(sent).toEqual([Uint8Array.from(GO_AWAY_PROTOCOL)]);+ expect(closes).toEqual([4000]);+ });++ it("handles a seal that fails while an earlier one is pending, and keeps send order", async () => {+ const unhandled: unknown[] = [];+ const onUnhandled = (reason: unknown) => unhandled.push(reason);+ process.on("unhandledRejection", onUnhandled);+ try {+ let release!: () => void;+ let calls = 0;+ const { session, sent } = fakeSession((plaintext) => {+ calls += 1;+ if (calls === 1) return new Promise((resolve) => (release = () => resolve(plaintext)));+ return Promise.reject(new Error("seal failed"));+ });+ const first = session.open();+ session.open();+ await new Promise((resolve) => setTimeout(resolve, 20));+ release();+ expect(await session.closed).toBe(4000);+ expect(sent).toHaveLength(1);+ expect(sent[0][7]).toBe(first.id);+ expect(unhandled).toEqual([]);+ } finally {+ process.off("unhandledRejection", onUnhandled);+ }+ });});diff --git a/src/lib/e2e/session.ts b/src/lib/e2e/session.tsindex 2de710ce6d..213f5ac659 100644--- a/src/lib/e2e/session.ts+++ b/src/lib/e2e/session.ts@@ -1,6 +1,3 @@-// The phone side of one encrypted session in the browser (companion/src/e2e/README.md sections 6-12): the WebSocket to-// a relay node or a direct route, the handshake, then records carrying yamux frames. Each stream is a raw byte pipe to-// the computer's origin; the HTTP on top comes later.import { b64u, type Bytes } from "./bytes.ts";import { encodePayload1, newConn, NoiseError, phoneHello, TRANSPORT_DIRECT, TRANSPORT_RELAY, type SessionKeys } from "./noise.ts";import { decodeFrame, encodeFrame, GO_AWAY, Mux, PING_INTERVAL_MS, PING_TIMEOUT_MS, YamuxError, type Frame } from "./yamux.ts";@@ -28,12 +25,17 @@ export const SEND_BUFFER_HIGH = 1024 * 1024;const DRAIN_POLL_MS = 5;/** The readable side holds this much before the computer is told to wait. */const READ_HIGH_WATER = 256 * 1024;+/** The longest wait a 4503 can ask for. */+const MAX_RETRY_MS = 60_000;export class SessionClosed extends Error {readonly code: number;- constructor(code: number) {+ /** A 4503's `{"retryInMs":N}`. */+ readonly retryInMs?: number;+ constructor(code: number, retryInMs?: number) {super(`e2e session closed (${code})`);this.code = code;+ this.retryInMs = retryInMs;}}@@ -47,7 +49,8 @@ interface Timers {}export interface DialOptions extends Timers {- /** `ws://host:port/v1/e2e` for Wi-Fi and Tailscale, `wss://relayN.openmausbot.com/v1/phone` for the relay. */+ /** `ws://host:port/v1/e2e` for Wi-Fi and Tailscale, `wss://relayN.openmausbot.com/v1/phone` for the relay. The direct+ * route refuses any Origin header (README section 4), so a web page always goes through the relay. */url: string;/** The pinned transport key `T.pub`. */remoteStatic: Bytes;@@ -95,6 +98,8 @@ export function dial(options: DialOptions): Promise<PhoneSession> {let stage: "connecting" | "relay" | "message2" | "finishing" | "done" = "connecting";/** Records that arrive while message 2 is checked go to the session in order. */const early: MessageEvent[] = [];+ /** A close while message 2 is checked: a failed check wins over it, since a node's 4404 must not hide a hard stop. */+ let closedWhileFinishing: SessionClosed | null = null;const fail = (error: Error, code?: number) => {if (stage === "done") return;stage = "done";@@ -134,6 +139,7 @@ export function dial(options: DialOptions): Promise<PhoneSession> {.then((keys) => {if (stage !== "finishing") return;+ if (closedWhileFinishing) return fail(closedWhileFinishing);stage = "done";clearTimeout(timer);const session = new PhoneSession(socket, keys, options);@@ -143,11 +149,25 @@ export function dial(options: DialOptions): Promise<PhoneSession> {(error: Error) => fail(error, CLOSE.protocol),);};- socket.onclose = (event: CloseEvent) => fail(new SessionClosed(event.code));+ socket.onclose = (event: CloseEvent) => {+ const closed = new SessionClosed(event.code, event.code === CLOSE.relayBusy ? retryDelay(event.reason) : undefined);+ if (stage === "finishing") closedWhileFinishing = closed;+ else fail(closed);+ };socket.onerror = () => {};});}+/** `{"retryInMs":N}` with N a whole number of ms, at most a minute; anything else asks for no wait. */+function retryDelay(reason: string): number | undefined {+ try {+ const value = (JSON.parse(reason) as { retryInMs?: unknown } | null)?.retryInMs;+ return Number.isSafeInteger(value) && (value as number) >= 0 ? Math.min(value as number, MAX_RETRY_MS) : undefined;+ } catch {+ return undefined;+ }+}+function isReady(text: string): boolean {try {return (JSON.parse(text) as { t?: unknown } | null)?.t === "ready";@@ -156,14 +176,20 @@ function isReady(text: string): boolean {}}-/** Tries each node in order. 4404 (not connected or not admitted here) and 4503 (full or restarting) move on to the- * next; any other failure, or the last node's, is the caller's to back off from. */+/** Tries each node in order. 4404 (not connected or not admitted here) moves on at once; 4503 (full or restarting)+ * waits the `retryInMs` it gives, plus jitter, first. Any other failure, or the last node's, is the caller's to back+ * off from. */export async function dialRelay(options: RelayDialOptions): Promise<PhoneSession> {- const { urls, hostId, adm, ...rest } = options;- let last: unknown = new SessionClosed(CLOSE.relayNotHere);- for (const url of urls) {+ // Copied at the call: the caller may reuse or wipe its arrays while the nodes are tried.+ const { urls, hostId, adm, remoteStatic, psk, ...rest } = options;+ const nodes = [...urls];+ const relay = { hostId: hostId.slice(), adm: adm.slice() };+ const keys = { remoteStatic: remoteStatic.slice(), psk: psk.slice() };+ let last = new SessionClosed(CLOSE.relayNotHere);+ for (const [index, url] of nodes.entries()) {+ if (index > 0 && last.retryInMs) await sleep(last.retryInMs * (1 + Math.random() * 0.2));try {- return await dial({ ...rest, url, relay: { hostId, adm } });+ return await dial({ ...rest, ...keys, url, relay });} catch (error) {if (!(error instanceof SessionClosed) || (error.code !== CLOSE.relayNotHere && error.code !== CLOSE.relayBusy)) throw error;last = error;@@ -172,6 +198,8 @@ export async function dialRelay(options: RelayDialOptions): Promise<PhoneSessionthrow last;}+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));+interface PendingWrite {bytes: Uint8Array;resolve(): void;@@ -279,8 +307,7 @@ class Stream implements E2EStream {this.#writes.shift();head.resolve();}- if (!this.#done && this.#ending && this.#writes.length === 0 && mux?.has(this.id)) {- this.#ending = false;+ if (!this.#done && this.#ending && !this.#finSent && this.#writes.length === 0 && mux?.has(this.id)) {this.#finSent = true;mux.finish(this.id);this.#forgetIfDone();@@ -288,7 +315,8 @@ class Stream implements E2EStream {}}-type State = "open" | "closed";+/** "closing": the last records are being sent before the socket closes. */+type State = "open" | "closing" | "closed";/** An open session. Built by dial() once message 2 checks out. */export class PhoneSession {@@ -306,6 +334,9 @@ export class PhoneSession {#pingCounter = 0;#drainWaiters: Array<() => void> = [];#removed = false;+ /** Records still being opened, and the socket's close code if it closed meanwhile. */+ #opening = 0;+ #closedMeanwhile: number | null = null;#settleClosed!: (code: number) => void;readonly closed: Promise<number>;@@ -332,7 +363,11 @@ export class PhoneSession {},});socket.onmessage = (event: MessageEvent) => this.receive(event);- socket.onclose = (event: CloseEvent) => this.#end(event.code);+ // A record already received, such as GoAway(3) just before a 4001, is read before the close ends the session.+ socket.onclose = (event: CloseEvent) => {+ if (this.#opening === 0) this.#end(event.code);+ else this.#closedMeanwhile = event.code;+ };const pingTimeoutMs = timers.pingTimeoutMs ?? PING_TIMEOUT_MS;this.#pingTimer = setInterval(() => this.#ping(pingTimeoutMs), timers.pingIntervalMs ?? PING_INTERVAL_MS);}@@ -381,25 +416,39 @@ export class PhoneSession {if (this.#state !== "open") return;if (typeof event.data === "string") return this.close(CLOSE.protocol);// Opens settle one at a time in call order, so frames reach the mux in wire order.- this.#keys.receive.open(new Uint8Array(event.data as ArrayBuffer)).then(- (plaintext) => {- if (this.#state !== "open") return;- try {- this.#mux.receive(decodeFrame(plaintext));- } catch (error) {- if (!(error instanceof YamuxError)) throw error;- this.#mux.protocolError();- this.close(CLOSE.protocol);- }- },- () => this.close(CLOSE.protocol),- );+ this.#opening += 1;+ this.#keys.receive+ .open(new Uint8Array(event.data as ArrayBuffer))+ .then(+ (plaintext) => {+ if (this.#state !== "open") return;+ try {+ this.#mux.receive(decodeFrame(plaintext));+ } catch (error) {+ if (!(error instanceof YamuxError)) throw error;+ this.#mux.protocolError();+ this.#closeAfterSending(CLOSE.protocol);+ }+ },+ () => this.close(CLOSE.protocol),+ )+ .finally(() => {+ this.#opening -= 1;+ if (this.#opening === 0 && this.#closedMeanwhile !== null) this.#end(this.#closedMeanwhile);+ });}/** A planned close: GoAway first, so the computer knows it isn't an error. */shutdown(): void {- if (this.#state === "open") this.#mux.goAway(GO_AWAY.normal);- this.#sending.then(() => this.close(CLOSE.normal));+ if (this.#state !== "open") return;+ this.#mux.goAway(GO_AWAY.normal);+ this.#closeAfterSending(CLOSE.normal);+ }++ /** Sends what is queued (a GoAway last), then closes; nothing new is sent or read meanwhile. */+ #closeAfterSending(code: number): void {+ this.#state = "closing";+ this.#sending.then(() => this.close(code));}close(code: number): void {@@ -428,24 +477,22 @@ export class PhoneSession {this.#pongTimer = setTimeout(() => this.close(CLOSE.goingAway), timeoutMs);}- /** Seals start now, in frame order, so each takes the next nonce; sends wait for every earlier record. */+ /** Seals start now, in frame order, so each takes the next nonce; sends wait for every earlier record. A seal's+ * failure is caught at once, so it is not unhandled while an earlier record is still being sealed. */#send(frame: Frame): void {if (this.#state !== "open") return;const plaintext = encodeFrame(frame);this.#unsealed += plaintext.length;- const sealed = this.#keys.send.seal(plaintext);- this.#sending = this.#sending.then(() =>- sealed.then(- (record) => {- this.#unsealed -= plaintext.length;- if (this.#state === "open") this.#socket.send(record);- },- (error: unknown) => {- this.#unsealed -= plaintext.length;- // The counter ran out: close before it could repeat; the phone reconnects.- this.close(error instanceof NoiseError ? CLOSE.normal : CLOSE.protocol);- },- ),+ const sealed = this.#keys.send.seal(plaintext).then(+ (record) => ({ record }),+ (error: unknown) => ({ error }),);+ this.#sending = this.#sending.then(async () => {+ const result = await sealed;+ this.#unsealed -= plaintext.length;+ // The counter ran out: close before it could repeat; the phone reconnects.+ if ("error" in result) return this.close(result.error instanceof NoiseError ? CLOSE.normal : CLOSE.protocol);+ if (this.#state !== "closed") this.#socket.send(result.record);+ });}}diff --git a/src/lib/e2e/yamux.test.ts b/src/lib/e2e/yamux.test.tsindex 2287b56770..335e89c372 100644--- a/src/lib/e2e/yamux.test.ts+++ b/src/lib/e2e/yamux.test.ts@@ -217,10 +217,19 @@ describe("the browser mux, after the peer's FIN and inside callbacks", () => {const { mux } = phoneWith();const id = mux.open();mux.receive({ type: 1, flags: 2 | 4, streamId: id, length: 0 });+ const window = mux.sendWindow(id);mux.receive({ type: 1, flags: 0, streamId: id, length: 10 });+ expect(mux.sendWindow(id)).toBe(window + 10);expect(() => mux.receive({ type: 0, flags: 0, streamId: id, length: 0, data: new Uint8Array(0) })).toThrow(YamuxError);});+ it("refuses Data on a phone-opened stream before the computer's ACK, and delivers none of it", () => {+ const { mux, log } = phoneWith();+ const id = mux.open();+ expect(() => mux.receive({ type: 0, flags: 0, streamId: id, length: 1, data: new Uint8Array([7]) })).toThrow("data_before_ack");+ expect(log.filter((entry) => entry.startsWith("data"))).toEqual([]);+ });+it("stops handling a frame once the data callback resets the stream", () => {const { mux, log } = phoneWith((m, event, id) => event === "data" && m.reset(id));const id = mux.open();diff --git a/src/lib/e2e/yamux.ts b/src/lib/e2e/yamux.tsindex c0fc1c9c33..211aea310b 100644--- a/src/lib/e2e/yamux.ts+++ b/src/lib/e2e/yamux.ts@@ -1,7 +1,3 @@-// The yamux profile carried inside the records, for the phone web app: one frame per record, phone-opened streams-// only, 2 MiB windows. A browser port of companion/src/e2e/yamux.ts with the same rules, on plain Uint8Array and-// DataView. Wire spec: companion/src/e2e/README.md, "Multiplexing"; vectors V5 and V6 pin it. This module does no I/O.-import type { Bytes } from "./bytes.ts";export const VERSION = 0;@@ -307,7 +303,7 @@ export class Mux {if (stream.established) throw new YamuxError("duplicate_ack");stream.established = true;this.#events.accepted?.(frame.streamId);- if (!this.#still(frame.streamId, stream)) return;+ if (!this.#isCurrentStream(frame.streamId, stream)) return;this.#receiveOnStream(frame.streamId, stream, { ...frame, flags: frame.flags & ~FLAG.ack });}@@ -318,6 +314,7 @@ export class Mux {return;}if (frame.type === TYPE.data) {+ if (this.role === "phone" && !stream.established) throw new YamuxError("data_before_ack");if (stream.remoteFin) throw new YamuxError("data_after_fin");if (frame.length > stream.receiveWindow) throw new YamuxError("window_exceeded");stream.receiveWindow -= frame.length;@@ -326,7 +323,7 @@ export class Mux {stream.sendWindow += frame.length;this.#events.writable(streamId);}- if (!this.#still(streamId, stream)) return;+ if (!this.#isCurrentStream(streamId, stream)) return;if (frame.flags & FLAG.fin) {if (stream.remoteFin) throw new YamuxError("data_after_fin");stream.remoteFin = true;@@ -335,8 +332,7 @@ export class Mux {}}- /** False once a callback reset the stream while this frame was being handled. */- #still(streamId: number, stream: StreamState): boolean {+ #isCurrentStream(streamId: number, stream: StreamState): boolean {return this.#streams.get(streamId) === stream;}