// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // kwserial's host side (js/core/serial.ts) against FakeSerialBackend: the // imports driven directly on a memory of their own, as the kernel calls // them, with SerialDevice and SerialHost joined as createKernel joins them // inline (and once across a MessageChannel, as in worker mode). No kernel // is booted; test/serial.test.ts is the end-to-end test with the kernel. // // node --test test/serial-host.test.ts (pnpm test:serial-host; pnpm test:serial runs both) import { afterEach, test } from "node:test"; import assert from "node:assert/strict"; import { FakeSerialBackend, OPEN_DEBOUNCE_MS, SERIAL_ATTACHED, SERIAL_CTS, SERIAL_DCD, SERIAL_EV_BREAK, SERIAL_EV_FRAMING, SERIAL_EV_HANGUP, SERIAL_EV_OVERRUN, SERIAL_EV_PARITY, SERIAL_EV_RX, SERIAL_EV_SIGNALS, SERIAL_EV_TX_ROOM, SERIAL_POLL_MS, SERIAL_RX_WINDOW, SERIAL_SIG_BREAK, SERIAL_SIG_DTR, SERIAL_SIG_RTS, SERIAL_TX_EMPTY, SERIAL_TX_WINDOW, SerialDevice, SerialHost, decodeSerialConfig, encodeSerialConfig, serialTransfer, type FakeSerialCall, type SerialDown, } from "../js/core/serial.ts"; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function until(what: string, cond: () => boolean, ms = 2000): Promise { const end = performance.now() + ms; while (!cond()) { if (performance.now() > end) throw new Error(`timed out waiting for ${what}`); await sleep(2); } } const CS8 = encodeSerialConfig({ dataBits: 8, stopBits: 1, parity: "none", flowControl: "none" }); const BUF = 0x1000, OUT = 0x8000; type Imports = { wasm_driver_serial_init(): number; wasm_driver_serial_open(port: number): number; wasm_driver_serial_close(port: number): void; wasm_driver_serial_config(port: number, baud: number, cfg: number): void; wasm_driver_serial_write(port: number, buf: bigint, len: number): number; wasm_driver_serial_read(port: number, buf: bigint, max: number): number; wasm_driver_serial_set_signals(port: number, signals: number): void; wasm_driver_serial_status(port: number): number; }; const hosts: SerialHost[] = []; afterEach(() => { for (const h of hosts.splice(0)) h.shutdown(); }); /** A device and its ports, joined as inline mode joins them, on a memory of 4 pages. */ function machine(ports = 4) { const memory = new WebAssembly.Memory({ initial: 4 }); const u8 = new Uint8Array(memory.buffer); let irqs = 0; let dev!: SerialDevice; const logs: string[] = []; const host = new SerialHost({ ports, send: (ops) => { for (const m of ops) dev.receive(m); }, log: (m) => logs.push(m) }); dev = new SerialDevice({ ports, memory: () => memory, raise: () => irqs++, send: (m) => host.receive(m) }); hosts.push(host); const k = dev.imports() as unknown as Imports; return { dev, host, k, logs, get irqs() { return irqs; }, /** The guest writes `data` (as much as is accepted). */ write(port: number, data: Uint8Array | string): number { const b = typeof data === "string" ? new TextEncoder().encode(data) : data; u8.set(b, BUF); return k.wasm_driver_serial_write(port, BigInt(BUF), b.length); }, /** The guest reads until 0, as after an IRQ with bit 8. */ readAll(port: number): string { let s = ""; for (;;) { const n = k.wasm_driver_serial_read(port, BigInt(OUT), 256); if (!n) return s; s += new TextDecoder().decode(u8.slice(OUT, OUT + n)); } }, status: (port: number) => k.wasm_driver_serial_status(port), /** The tty open as serial_core makes it: open, config, DTR and RTS up. */ ttyOpen(port: number, baud = 115200, cfg = CS8): number { const r = k.wasm_driver_serial_open(port); if (r) return r; k.wasm_driver_serial_config(port, baud, cfg); k.wasm_driver_serial_set_signals(port, SERIAL_SIG_DTR | SERIAL_SIG_RTS); return 0; }, }; } const ops = (fake: FakeSerialBackend) => fake.calls.map((c) => c.op); const describeCall = (c: FakeSerialCall): string => c.op === "open" ? `open ${c.config.baudRate}` : c.op === "setSignals" ? `sig ${c.signals.dataTerminalReady ? "D" : "d"}${c.signals.requestToSend ? "R" : "r"}${c.signals.break ? "B" : ""}` : c.op === "write" ? `write ${new TextDecoder().decode(c.data)}` : c.op; test("config words decode as the contract says", () => { assert.deepEqual(decodeSerialConfig(115200, CS8), { baudRate: 115200, dataBits: 8, stopBits: 1, parity: "none", flowControl: "none" }); // 7E2 with RTS/CTS: 7 | two stop bits | even << 5 | bit 7. assert.deepEqual(decodeSerialConfig(9600, 7 | 0x10 | (2 << 5) | 0x80), { baudRate: 9600, dataBits: 7, stopBits: 2, parity: "even", flowControl: "hardware" }); assert.equal(decodeSerialConfig(0, 5 | (1 << 5), decodeSerialConfig(57600, CS8)).baudRate, 57600, "B0 keeps the rate"); assert.equal(decodeSerialConfig(300, 5 | (1 << 5)).parity, "odd"); }); test("no device: init and open answer ENODEV; a port without a backend answers ENODEV", () => { const memory = new WebAssembly.Memory({ initial: 1 }); const off = new SerialDevice({ memory: () => memory, raise: () => {} }).imports() as unknown as Imports; assert.equal(off.wasm_driver_serial_init(), -19); assert.equal(off.wasm_driver_serial_open(0), -19); assert.equal(off.wasm_driver_serial_status(0), 0); const m = machine(2); assert.equal(m.k.wasm_driver_serial_init(), 2); const wanted: number[] = []; m.host.onWanted((slot) => wanted.push(slot)); assert.equal(m.k.wasm_driver_serial_open(0), -19); assert.equal(m.k.wasm_driver_serial_open(0), -19); assert.deepEqual(wanted, [0], "onWanted, once a second for a port"); assert.equal(m.k.wasm_driver_serial_open(5), -19, "a port it does not offer"); assert.equal(m.status(0) & SERIAL_ATTACHED, 0); }); test("a tty open is one physical open with the guest's settings; loopback bytes come back with IRQ 12's bit 8", async () => { const m = machine(); m.k.wasm_driver_serial_init(); const fake = new FakeSerialBackend(); assert.equal(m.host.attach(fake), 0); await sleep(0); assert.ok(m.status(0) & SERIAL_ATTACHED, "attached level"); assert.equal(m.ttyOpen(0, 115200), 0); // A program's tcsetattr right after its open (picocom) is still in the same physical open. await sleep(OPEN_DEBOUNCE_MS / 3); m.k.wasm_driver_serial_config(0, 230400, CS8); await until("the open", () => fake.isOpen); assert.deepEqual(fake.calls.map(describeCall), ["open 230400", "sig DR"]); assert.equal(m.write(0, "hello"), 5); const irqs = m.irqs; await until("the loopback", () => m.dev.rxPending(0) === 5); assert.ok(m.irqs > irqs, "IRQ raised"); const st = m.status(0); assert.ok(st & SERIAL_EV_RX, "RX event"); assert.ok(st & SERIAL_TX_EMPTY, "everything written out"); assert.equal(m.status(0) & SERIAL_EV_RX, 0, "events are cleared by the read"); assert.equal(m.readAll(0), "hello"); assert.equal(m.host.state(0).phase, "open"); assert.deepEqual(m.host.state(0).config, { baudRate: 230400, dataBits: 8, stopBits: 1, parity: "none", flowControl: "none" }); m.k.wasm_driver_serial_set_signals(0, 0); // HUPCL m.k.wasm_driver_serial_close(0); await until("the close", () => !fake.isOpen); assert.deepEqual(fake.calls.map(describeCall).slice(2), ["write hello", "sig dr", "close"]); assert.equal(m.host.state(0).attached, true, "the attachment stays"); }); test("a config change while open reopens, with writes held in order; the same config does not", async () => { const m = machine(); const fake = new FakeSerialBackend({ loopback: false }); m.host.attach(fake); await sleep(0); m.ttyOpen(0, 115200); await until("the open", () => fake.isOpen); m.write(0, "a"); m.k.wasm_driver_serial_config(0, 115200, CS8); // tcsetattr with nothing changed m.write(0, "b"); m.k.wasm_driver_serial_config(0, 460800, CS8); // esptool's change_baud m.write(0, "c"); m.k.wasm_driver_serial_set_signals(0, SERIAL_SIG_DTR); m.write(0, "d"); await until("everything written", () => fake.written().length === 4 && (m.status(0) & SERIAL_TX_EMPTY) !== 0); assert.deepEqual(fake.calls.map(describeCall), [ "open 115200", "sig DR", "write a", "write b", "close", "open 460800", "sig DR", "write c", "sig Dr", "write d", ]); assert.equal(m.host.state(0).opens, 2); m.k.wasm_driver_serial_close(0); await until("the close", () => !fake.isOpen); }); test("signal changes reach the port in order with writes, none merged (an esptool reset)", async () => { const m = machine(); const fake = new FakeSerialBackend({ loopback: false }); m.host.attach(fake); await sleep(0); m.ttyOpen(0, 115200); await until("the open", () => fake.isOpen); const seq = [ SERIAL_SIG_RTS, // EN low (DTR off, RTS on) SERIAL_SIG_DTR, // IO0 low, EN high 0, ]; m.k.wasm_driver_serial_set_signals(0, 0); for (const s of seq) { m.k.wasm_driver_serial_set_signals(0, s); await sleep(5); } m.write(0, "x"); m.k.wasm_driver_serial_set_signals(0, SERIAL_SIG_BREAK | SERIAL_SIG_DTR); m.k.wasm_driver_serial_set_signals(0, SERIAL_SIG_DTR); m.write(0, "y"); await until("all", () => fake.written().length === 2); assert.deepEqual(fake.calls.map(describeCall), ["open 115200", "sig DR", "sig dr", "sig dR", "sig Dr", "sig dr", "write x", "sig DrB", "sig Dr", "write y"]); // Each change at least as late as the one before it. const at = fake.callsOf("setSignals").map((c) => c.at); for (let i = 1; i < at.length; i++) assert.ok(at[i]! >= at[i - 1]!); m.k.wasm_driver_serial_close(0); }); test("TX backpressure: the window, TX room, TX empty; a close does not wait for a held write", async () => { const m = machine(); const fake = new FakeSerialBackend({ loopback: false }); m.host.attach(fake); await sleep(0); m.ttyOpen(0, 9600); await until("the open", () => fake.isOpen); fake.holdWrites(); const big = new Uint8Array(SERIAL_TX_WINDOW + 1000).fill(65); assert.equal(m.write(0, big), SERIAL_TX_WINDOW, "the window"); assert.equal(m.write(0, "z"), 0, "no room"); assert.equal(m.status(0) & (SERIAL_TX_EMPTY | SERIAL_EV_TX_ROOM), 0); await until("the write reached the device", () => fake.callsOf("write").length === 1); const irqs = m.irqs; fake.releaseWrites(); await until("TX room", () => m.irqs > irqs); const st = m.status(0); assert.ok(st & SERIAL_EV_TX_ROOM, "TX room event"); assert.ok(st & SERIAL_TX_EMPTY, "TX empty"); // Held again: the close drops the pending TX and closes the port anyway. fake.holdWrites(); m.write(0, "held"); m.write(0, "pending"); await until("held", () => fake.callsOf("write").length === 2); m.k.wasm_driver_serial_close(0); await until("the close", () => !fake.isOpen && m.host.state(0).phase === "closed"); assert.deepEqual(ops(fake).slice(-2), ["write", "close"]); assert.equal(new TextDecoder().decode(fake.callsOf("write").at(-1)!.data), "held", "the pending write was dropped"); }); test("read errors map to event bits and the reader goes on", async () => { const m = machine(); const fake = new FakeSerialBackend({ loopback: false }); m.host.attach(fake); await sleep(0); m.ttyOpen(0); await until("the open", () => fake.isOpen); const want: Array<[string, number]> = [["BreakError", SERIAL_EV_BREAK], ["FramingError", SERIAL_EV_FRAMING], ["ParityError", SERIAL_EV_PARITY], ["BufferOverrunError", SERIAL_EV_OVERRUN], ["BufferOverflowError", SERIAL_EV_OVERRUN]]; for (const [name, bit] of want) { m.status(0); fake.inject(name); let st = 0; await until(`${name}'s event bit`, () => ((st |= m.status(0)) & bit) !== 0, 500); } fake.feed("after"); await until("data after the errors", () => m.dev.rxPending(0) === 5); assert.equal(m.readAll(0), "after"); assert.equal(m.host.state(0).phase, "open"); assert.equal(m.status(0) & SERIAL_EV_HANGUP, 0); m.k.wasm_driver_serial_close(0); }); test("hangup: an unplugged device, a detach while open, a failed open; the session ends at the guest's close", async () => { const m = machine(); const a = new FakeSerialBackend(); m.host.attach(a, 1); await sleep(0); m.ttyOpen(1); await until("the open", () => a.isOpen); a.unplug(); let st = 0; await until("hangup", () => ((st |= m.status(1)) & SERIAL_EV_HANGUP) !== 0); await sleep(0); assert.equal(m.host.state(1).attached, false, "a lost device is detached"); assert.equal(m.status(1) & SERIAL_ATTACHED, 0); assert.equal(m.write(1, "dropped"), 7, "writes of a hung session are taken and dropped"); assert.ok(m.status(1) & SERIAL_TX_EMPTY); m.k.wasm_driver_serial_close(1); assert.equal(m.k.wasm_driver_serial_open(1), -19, "nothing attached now"); // Detach while open. const b = new FakeSerialBackend(); m.host.attach(b, 1); await sleep(0); m.ttyOpen(1); await until("the open", () => b.isOpen); m.status(1); await m.host.detach(1); await sleep(0); assert.ok(m.status(1) & SERIAL_EV_HANGUP, "hangup on detach"); assert.equal(b.isOpen, false, "the port was closed"); m.k.wasm_driver_serial_close(1); // The open fails (the port is busy): a hangup, the attachment kept, the next open works. const c = new FakeSerialBackend(); m.host.attach(c, 2); await sleep(0); c.failNextOpen("NetworkError"); m.ttyOpen(2); st = 0; await until("hangup", () => ((st |= m.status(2)) & SERIAL_EV_HANGUP) !== 0); assert.match(m.host.state(2).error ?? "", /open/); assert.equal(m.host.state(2).attached, true); m.k.wasm_driver_serial_close(2); await until("closed", () => m.host.state(2).phase === "closed" && !m.host.state(2).guestOpen); m.ttyOpen(2); await until("the second open", () => c.isOpen); m.k.wasm_driver_serial_close(2); await until("closed", () => !c.isOpen); }); test("input signals are polled only while the guest has the port open; a change raises bit 11", async () => { const m = machine(); const fake = new FakeSerialBackend({ inputs: { clearToSend: true } }); m.host.attach(fake); await sleep(SERIAL_POLL_MS * 2); assert.equal(fake.polls, 0, "no polling before the open"); m.ttyOpen(0); await until("the first poll", () => fake.polls > 0); await until("levels", () => (m.status(0) & SERIAL_CTS) !== 0); assert.ok(m.host.polling(0)); m.status(0); fake.setInputs({ dataCarrierDetect: true, clearToSend: false }); let st = 0; await until("the change", () => ((st |= m.status(0)) & SERIAL_EV_SIGNALS) !== 0, SERIAL_POLL_MS * 4); assert.ok(m.status(0) & SERIAL_DCD); assert.equal(m.status(0) & SERIAL_CTS, 0); assert.deepEqual(m.host.state(0).inputs, { clearToSend: false, dataSetReady: false, dataCarrierDetect: true, ringIndicator: false }); m.k.wasm_driver_serial_close(0); await until("closed", () => !fake.isOpen); assert.equal(m.host.polling(0), false); const polls = fake.polls; await sleep(SERIAL_POLL_MS * 3); assert.equal(fake.polls, polls, "polling stopped"); }); test("RX backpressure: the reader waits while the kernel has a window's worth unread", async () => { const m = machine(); const fake = new FakeSerialBackend({ loopback: false }); m.host.attach(fake); await sleep(0); m.ttyOpen(0); await until("the open", () => fake.isOpen); const chunk = new Uint8Array(16384).fill(66); for (let i = 0; i < 8; i++) fake.feed(chunk); // 128 KiB, twice the window await until("a window's worth", () => m.dev.rxPending(0) >= SERIAL_RX_WINDOW); await sleep(20); assert.equal(m.dev.rxPending(0), SERIAL_RX_WINDOW, "the reader stopped at the window"); let total = 0; for (let i = 0; i < 100 && total < 8 * 16384; i++) { total += m.readAll(0).length; await sleep(2); } assert.equal(total, 8 * 16384, "everything arrived once the kernel read"); m.k.wasm_driver_serial_close(0); }); test("close drops unread RX; a reopen starts clean", async () => { const m = machine(); const fake = new FakeSerialBackend(); m.host.attach(fake); await sleep(0); m.ttyOpen(0); await until("the open", () => fake.isOpen); m.write(0, "unread"); await until("rx", () => m.dev.rxPending(0) > 0); m.k.wasm_driver_serial_close(0); assert.equal(m.dev.rxPending(0), 0); await until("closed", () => !fake.isOpen); m.ttyOpen(0); await until("reopened", () => fake.isOpen); assert.equal(m.readAll(0), ""); m.write(0, "fresh"); await until("rx", () => m.dev.rxPending(0) === 5); assert.equal(m.readAll(0), "fresh"); m.k.wasm_driver_serial_close(0); }); test("snapshots keep no port state: a restored machine sees its open ports hung up", async () => { const m = machine(); m.k.wasm_driver_serial_init(); const fake = new FakeSerialBackend(); m.host.attach(fake); await sleep(0); m.ttyOpen(0); await until("the open", () => fake.isOpen); const saved = m.dev.saveState(); assert.deepEqual(saved, { ports: 4, open: [0] }); // The new machine, with the option and with none. for (const ports of [4, 0]) { const memory = new WebAssembly.Memory({ initial: 1 }); let irqs = 0; const dev = new SerialDevice({ ports, memory: () => memory, raise: () => irqs++ }); dev.restoreState(structuredClone(saved)); const k = dev.imports() as unknown as Imports; assert.ok(irqs > 0); assert.ok(k.wasm_driver_serial_status(0) & SERIAL_EV_HANGUP, `hung up (ports ${ports})`); assert.equal(k.wasm_driver_serial_read(0, 0n, 16), 0); assert.equal(k.wasm_driver_serial_write(0, 0n, 3), 3); k.wasm_driver_serial_close(0); // the kernel's hangup ends in a close assert.equal(k.wasm_driver_serial_open(0), -19); } m.k.wasm_driver_serial_close(0); }); test("a backend attaches to one slot, every slot can be taken, and state changes are reported", async () => { const m = machine(2); const seen: string[] = []; m.host.onChange((s) => seen.push(`${s.device}:${s.attached}`)); const a = new FakeSerialBackend(), b = new FakeSerialBackend(), c = new FakeSerialBackend(); assert.equal(m.host.attach(a), 0); assert.throws(() => m.host.attach(a), /attached/); assert.equal(m.host.attach(b), 1); assert.throws(() => m.host.attach(c), /every port is taken/); await sleep(0); assert.deepEqual(seen, ["/dev/ttyACM0:true", "/dev/ttyACM1:true"]); await m.host.detach(0); await sleep(0); assert.equal(m.host.attach(c), 0); assert.equal(m.host.slotOf(c), 0); assert.equal(m.host.stats.attached, 2); }); test("the open waits for the last config, at most OPEN_DEBOUNCE_MAX_MS", async () => { const m = machine(); const fake = new FakeSerialBackend(); m.host.attach(fake); await sleep(0); const t0 = performance.now(); m.ttyOpen(0, 9600); // A program that keeps changing the rate: the open goes ahead after the cap with the latest. let baud = 9600; const iv = setInterval(() => m.k.wasm_driver_serial_config(0, (baud += 100), CS8), 10); await until("the open", () => fake.isOpen, 2000); clearInterval(iv); const dt = performance.now() - t0; assert.ok(dt >= 200 && dt < 1000, `opened after ${dt.toFixed(0)} ms`); assert.ok(fake.callsOf("open")[0]!.config.baudRate > 9600, "with a later rate than the open's"); m.k.wasm_driver_serial_close(0); await until("closed", () => !fake.isOpen); }); test("across a message boundary (worker mode's batches, writes transferred), in order", async () => { const memory = new WebAssembly.Memory({ initial: 4 }); const u8 = new Uint8Array(memory.buffer); const { port1: kernelSide, port2: ownerSide } = new MessageChannel(); const host = new SerialHost({ ports: 4, send: (ops) => ownerSide.postMessage({ t: "serial", ops }) }); hosts.push(host); // The worker's batching: one message per microtask, write data transferred. let out: SerialDown[] = []; const dev = new SerialDevice({ ports: 4, memory: () => memory, raise: () => {}, send: (m) => { if (out.push(m) === 1) queueMicrotask(() => { const batch = out; out = []; kernelSide.postMessage({ t: "serial", ops: batch }, serialTransfer(batch)); }); }, }); ownerSide.onmessage = (e: MessageEvent) => { for (const m of e.data.ops) host.receive(m); }; kernelSide.onmessage = (e: MessageEvent) => { for (const m of e.data.ops) dev.receive(m); }; const k = dev.imports() as unknown as Imports; try { assert.equal(k.wasm_driver_serial_init(), 4); const fake = new FakeSerialBackend(); host.attach(fake, 3); await until("the attach crossed", () => (k.wasm_driver_serial_status(3) & SERIAL_ATTACHED) !== 0); assert.equal(k.wasm_driver_serial_open(3), 0); k.wasm_driver_serial_config(3, 115200, CS8); k.wasm_driver_serial_set_signals(3, SERIAL_SIG_DTR | SERIAL_SIG_RTS); u8.set(new TextEncoder().encode("ping"), BUF); assert.equal(k.wasm_driver_serial_write(3, BigInt(BUF), 4), 4); k.wasm_driver_serial_config(3, 921600, CS8); u8.set(new TextEncoder().encode("pong"), BUF); k.wasm_driver_serial_write(3, BigInt(BUF), 4); await until("the echo", () => dev.rxPending(3) === 8); // The configs during the open's debounce are folded into it; the writes stay apart around the second. assert.deepEqual(fake.calls.map(describeCall), ["open 921600", "sig DR", "write ping", "write pong"]); const n = k.wasm_driver_serial_read(3, BigInt(OUT), 64); assert.equal(new TextDecoder().decode(u8.slice(OUT, OUT + n)), "pingpong"); k.wasm_driver_serial_close(3); await until("closed", () => !fake.isOpen); } finally { kernelSide.close(); ownerSide.close(); } });