mirror of
https://github.com/Tencent/BrowserSkill.git
synced 2026-09-10 13:01:23 +08:00
Initial public release
This commit is contained in:
commit
f1036a860c
289 files changed
+54589
No files matched your search
@@ -0,0 +1,85 @@
|
||||
# Extension transport layer
|
||||
|
||||
`apps/extension/src/transport/` is the single, swappable seam between the
|
||||
browser-skill extension and whatever channel it uses to talk to the local
|
||||
daemon. v0.1 ships exactly one implementation —
|
||||
[`ws-transport.ts`](./ws-transport.ts) — which speaks the JSON-line wire
|
||||
format defined in `crates/bsk-protocol/schema/*.json` over a plain WebSocket.
|
||||
|
||||
## How to fork the transport
|
||||
|
||||
If you want to swap the WebSocket for native messaging, `chrome.runtime`
|
||||
messaging, a shared `MessageChannel`, etc., implement the
|
||||
[`Transport`](./transport.ts) interface and instantiate your class in
|
||||
`apps/extension/src/entrypoints/background.ts` instead of `WSTransport`.
|
||||
|
||||
The contract is:
|
||||
|
||||
```ts
|
||||
import type { Transport } from "@/transport/transport";
|
||||
import type { ProtocolFrame, ConnectionState } from "@/transport/types";
|
||||
|
||||
class MyTransport implements Transport {
|
||||
readonly state: ConnectionState;
|
||||
connect(): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
send(msg: ProtocolFrame): void;
|
||||
onMessage(handler: (msg: ProtocolFrame) => void): { dispose(): void };
|
||||
onConnectionStateChange(handler: (s: ConnectionState) => void): { dispose(): void };
|
||||
}
|
||||
```
|
||||
|
||||
### Protocol-frame contract
|
||||
|
||||
A `ProtocolFrame` is one of three JSON shapes (mirrors `bsk-protocol::Frame`):
|
||||
|
||||
```jsonc
|
||||
// Request — both peers may send
|
||||
{ "id": "<rpc-id>", "method": "tool.snapshot", "params": { "session_id": "ab12" } }
|
||||
|
||||
// Response — one of result | error, never both
|
||||
{ "id": "<rpc-id>", "result": { ... } }
|
||||
{ "id": "<rpc-id>", "error": { "code": "not_found", "message": "session ab12 unknown" } }
|
||||
|
||||
// Event — no id, no response expected
|
||||
{ "event": "session.window_closed", "payload": { "session_id": "ab12" } }
|
||||
```
|
||||
|
||||
The transport is **purely a byte pipe**. It must not interpret RPC method
|
||||
names, route by id, or re-order frames. Higher-level concerns
|
||||
(handshake, dispatcher, ref-store) all live in `tools/` and
|
||||
`session-manager/`. The transport's only obligations are:
|
||||
|
||||
1. **Frame-oriented delivery.** One `send()` call ⇒ exactly one frame on
|
||||
the wire. Inbound bytes are split into discrete frames before being
|
||||
handed to message handlers.
|
||||
2. **Best-effort reconnect.** When the underlying channel breaks
|
||||
unexpectedly, the transport reopens it with backoff and surfaces
|
||||
`connecting` / `disconnected` via `onConnectionStateChange`.
|
||||
`WSTransport` uses 1 s → 2 s → 4 s → 8 s → 16 s → 30 s (capped),
|
||||
resetting on a successful reconnect.
|
||||
3. **State observability.** `state` must be one of `disconnected`,
|
||||
`connecting`, `connected`, or `version_skew`. Only the handshake
|
||||
logic should set `version_skew` when `protocol_version` strings differ
|
||||
but majors match; app semver is not compared. The bare transport
|
||||
stays at `connected` once the socket is open. Handshake may still
|
||||
include deprecated `min_compatible_peer` (`"0.0.0"`) alongside
|
||||
`min_compatible_protocol` for backward compatibility.
|
||||
4. **No throwing on malformed frames.** Drop non-JSON inbound traffic
|
||||
silently; surface decode failures through logs only.
|
||||
|
||||
### Handshake responsibility
|
||||
|
||||
A fresh `Transport` instance is **not** authenticated. The first frame
|
||||
sent over the wire **must** be `system.handshake`. Forks are expected to
|
||||
preserve that contract — see `lib/instance-id.ts` and
|
||||
`transport/handshake.ts` (added in M4.3) for the helper that owns the
|
||||
extension side.
|
||||
|
||||
### Testing forks
|
||||
|
||||
`__tests__/ws-transport.test.ts` is the reference test suite. It uses a
|
||||
hand-rolled `FakeSocket` so a new transport can copy its structure
|
||||
verbatim and adapt the inner channel. See the suite for: connect/
|
||||
disconnect, send/onMessage, malformed-frame tolerance, and exponential-
|
||||
backoff reconnect verification.
|
||||
@@ -0,0 +1,224 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
detectBrowserMeta,
|
||||
EXTENSION_VERSION,
|
||||
MIN_COMPATIBLE_PEER,
|
||||
MIN_COMPATIBLE_PROTOCOL,
|
||||
PROTOCOL_VERSION,
|
||||
performHandshake,
|
||||
} from "../handshake";
|
||||
import type { ConnectionStateHandler, FrameHandler, Transport } from "../transport";
|
||||
import type { ConnectionState, HandshakeResult, ProtocolFrame } from "../types";
|
||||
|
||||
function fakeTransport(reply: (req: ProtocolFrame) => ProtocolFrame | null): Transport {
|
||||
const handlers = new Set<FrameHandler>();
|
||||
const t: Transport = {
|
||||
state: "connected" as ConnectionState,
|
||||
connect: () => Promise.resolve(),
|
||||
disconnect: () => Promise.resolve(),
|
||||
send: (msg) => {
|
||||
const response = reply(msg);
|
||||
if (response) {
|
||||
for (const h of handlers) h(response);
|
||||
}
|
||||
},
|
||||
onMessage: (h: FrameHandler) => {
|
||||
handlers.add(h);
|
||||
return {
|
||||
dispose: () => {
|
||||
handlers.delete(h);
|
||||
},
|
||||
};
|
||||
},
|
||||
onConnectionStateChange: (_h: ConnectionStateHandler) => ({
|
||||
dispose: () => {},
|
||||
}),
|
||||
};
|
||||
return t;
|
||||
}
|
||||
|
||||
function deferredFakeTransport(): { transport: Transport; emit: (frame: ProtocolFrame) => void } {
|
||||
const handlers = new Set<FrameHandler>();
|
||||
const transport: Transport = {
|
||||
state: "connected" as ConnectionState,
|
||||
connect: () => Promise.resolve(),
|
||||
disconnect: () => Promise.resolve(),
|
||||
send: () => {},
|
||||
onMessage: (h: FrameHandler) => {
|
||||
handlers.add(h);
|
||||
return {
|
||||
dispose: () => {
|
||||
handlers.delete(h);
|
||||
},
|
||||
};
|
||||
},
|
||||
onConnectionStateChange: (_h: ConnectionStateHandler) => ({
|
||||
dispose: () => {},
|
||||
}),
|
||||
};
|
||||
return {
|
||||
transport,
|
||||
emit: (frame) => {
|
||||
for (const h of handlers) h(frame);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("performHandshake", () => {
|
||||
it("sends system.handshake with identity and both compat fields", async () => {
|
||||
let sentFrame: ProtocolFrame | null = null;
|
||||
const transport = fakeTransport((req) => {
|
||||
sentFrame = req;
|
||||
return {
|
||||
id: (req as { id: string }).id,
|
||||
result: {
|
||||
server: "browser-skill-daemon",
|
||||
version: "0.1.0",
|
||||
protocol_version: "1.0",
|
||||
min_compatible_peer: "0.0.0",
|
||||
min_compatible_protocol: "1.0",
|
||||
},
|
||||
};
|
||||
});
|
||||
const outcome = await performHandshake(transport, {
|
||||
instanceId: "abcdef01-2345-4678-89ab-cdef01234567",
|
||||
browser: { name: "chrome", version: "131.0" },
|
||||
label: "Personal Chrome",
|
||||
rpcId: "hs-test",
|
||||
});
|
||||
|
||||
expect(sentFrame).toEqual({
|
||||
id: "hs-test",
|
||||
method: "system.handshake",
|
||||
params: {
|
||||
client: "browser-skill-extension",
|
||||
version: EXTENSION_VERSION,
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
instance_id: "abcdef01-2345-4678-89ab-cdef01234567",
|
||||
browser: { name: "chrome", version: "131.0" },
|
||||
label: "Personal Chrome",
|
||||
min_compatible_peer: MIN_COMPATIBLE_PEER,
|
||||
min_compatible_protocol: MIN_COMPATIBLE_PROTOCOL,
|
||||
},
|
||||
});
|
||||
expect(outcome.result.min_compatible_peer).toBe("0.0.0");
|
||||
expect(outcome.result.min_compatible_protocol).toBe("1.0");
|
||||
});
|
||||
|
||||
it("accepts legacy daemon reply with only min_compatible_peer", async () => {
|
||||
const transport = fakeTransport((req) => ({
|
||||
id: (req as { id: string }).id,
|
||||
result: {
|
||||
server: "browser-skill-daemon",
|
||||
version: "0.1.0",
|
||||
protocol_version: "1.0",
|
||||
min_compatible_peer: "0.1.0",
|
||||
},
|
||||
}));
|
||||
const outcome = await performHandshake(transport, {
|
||||
instanceId: "x",
|
||||
browser: { name: "chrome", version: "131" },
|
||||
label: "",
|
||||
rpcId: "hs-legacy",
|
||||
});
|
||||
expect(outcome.result.protocol_version).toBe("1.0");
|
||||
expect(outcome.result.min_compatible_protocol).toBeUndefined();
|
||||
});
|
||||
|
||||
it("accepts daemon reply without legacy min_compatible_peer", async () => {
|
||||
const response = {
|
||||
server: "browser-skill-daemon",
|
||||
version: "0.1.0",
|
||||
protocol_version: "1.0",
|
||||
min_compatible_protocol: "1.0",
|
||||
} satisfies HandshakeResult;
|
||||
const transport = fakeTransport((req) => ({
|
||||
id: (req as { id: string }).id,
|
||||
result: response,
|
||||
}));
|
||||
|
||||
const outcome = await performHandshake(transport, {
|
||||
instanceId: "x",
|
||||
browser: { name: "chrome", version: "131" },
|
||||
label: "",
|
||||
rpcId: "hs-no-legacy-peer",
|
||||
});
|
||||
|
||||
expect(outcome.result.min_compatible_peer).toBeUndefined();
|
||||
expect(outcome.result.min_compatible_protocol).toBe("1.0");
|
||||
});
|
||||
|
||||
it("rejects when the daemon responds with an error", async () => {
|
||||
const transport = fakeTransport((req) => ({
|
||||
id: (req as { id: string }).id,
|
||||
error: { code: "version_too_old", message: "extension is too old" },
|
||||
}));
|
||||
await expect(
|
||||
performHandshake(transport, {
|
||||
instanceId: "x",
|
||||
browser: { name: "chrome", version: "131" },
|
||||
label: "",
|
||||
rpcId: "hs-err",
|
||||
}),
|
||||
).rejects.toThrow(/version_too_old/);
|
||||
});
|
||||
|
||||
it("ignores unrelated frames and resolves on the matching response id", async () => {
|
||||
const { transport, emit } = deferredFakeTransport();
|
||||
const pending = performHandshake(transport, {
|
||||
instanceId: "x",
|
||||
browser: { name: "chrome", version: "131" },
|
||||
label: "",
|
||||
rpcId: "hs-target",
|
||||
});
|
||||
|
||||
emit({ event: "browser.event", payload: { ignored: true } });
|
||||
emit({
|
||||
id: "hs-other",
|
||||
result: {
|
||||
server: "browser-skill-daemon",
|
||||
version: "0.1.0",
|
||||
protocol_version: "1.0",
|
||||
min_compatible_peer: "0.0.0",
|
||||
min_compatible_protocol: "1.0",
|
||||
},
|
||||
});
|
||||
emit({
|
||||
id: "hs-target",
|
||||
result: {
|
||||
server: "browser-skill-daemon",
|
||||
version: "0.1.0",
|
||||
protocol_version: "1.0",
|
||||
min_compatible_peer: "0.0.0",
|
||||
min_compatible_protocol: "1.0",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
result: { server: "browser-skill-daemon", protocol_version: "1.0" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectBrowserMeta", () => {
|
||||
it("recognises Chrome", () => {
|
||||
const meta = detectBrowserMeta(
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.86 Safari/537.36",
|
||||
);
|
||||
expect(meta).toEqual({ name: "chrome", version: "131.0.6778.86" });
|
||||
});
|
||||
|
||||
it("recognises Edge before the Chrome fallback", () => {
|
||||
const meta = detectBrowserMeta(
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.2903.70",
|
||||
);
|
||||
expect(meta).toEqual({ name: "edge", version: "131.0.2903.70" });
|
||||
});
|
||||
|
||||
it("falls back to chromium with unknown version for unknown UAs", () => {
|
||||
expect(detectBrowserMeta("Unknown Browser/1.0")).toEqual({
|
||||
name: "chromium",
|
||||
version: "unknown",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ConnectionState, ProtocolFrame } from "../types";
|
||||
import { WSTransport } from "../ws-transport";
|
||||
|
||||
type WebSocketEventListener = (event: { data?: unknown } | undefined) => void;
|
||||
|
||||
class FakeSocket {
|
||||
static instances: FakeSocket[] = [];
|
||||
static OPEN = 1;
|
||||
static CLOSING = 2;
|
||||
static CLOSED = 3;
|
||||
|
||||
url: string;
|
||||
readyState: number = 0;
|
||||
sent: string[] = [];
|
||||
closeCalls = 0;
|
||||
listeners: Record<string, WebSocketEventListener[]> = {};
|
||||
|
||||
constructor(url: string) {
|
||||
this.url = url;
|
||||
FakeSocket.instances.push(this);
|
||||
}
|
||||
|
||||
addEventListener(type: string, listener: WebSocketEventListener): void {
|
||||
(this.listeners[type] ??= []).push(listener);
|
||||
}
|
||||
|
||||
send(payload: string): void {
|
||||
this.sent.push(payload);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closeCalls += 1;
|
||||
this.readyState = FakeSocket.CLOSED;
|
||||
this.emit("close", { code: 1000, reason: "client" });
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.readyState = FakeSocket.OPEN;
|
||||
this.emit("open", undefined);
|
||||
}
|
||||
|
||||
receive(frame: ProtocolFrame): void {
|
||||
this.emit("message", { data: JSON.stringify(frame) });
|
||||
}
|
||||
|
||||
serverClose(code = 1006): void {
|
||||
this.readyState = FakeSocket.CLOSED;
|
||||
this.emit("close", { code, reason: "server-gone" });
|
||||
}
|
||||
|
||||
private emit(type: string, ev: unknown): void {
|
||||
for (const l of this.listeners[type] ?? []) {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: minimal fake mirrors WebSocket Event shape
|
||||
l(ev as any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function lastSocket(): FakeSocket {
|
||||
const s = FakeSocket.instances.at(-1);
|
||||
if (!s) throw new Error("no FakeSocket created yet");
|
||||
return s;
|
||||
}
|
||||
|
||||
describe("WSTransport", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: false });
|
||||
FakeSocket.instances = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("constructs a WebSocket against the configured URL when connect() is called", async () => {
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const connectPromise = t.connect();
|
||||
expect(FakeSocket.instances.length).toBe(1);
|
||||
expect(lastSocket().url).toBe("ws://127.0.0.1:52800");
|
||||
lastSocket().open();
|
||||
await connectPromise;
|
||||
expect(t.state).toBe("connected");
|
||||
});
|
||||
|
||||
it("emits connection state transitions disconnected → connecting → connected", async () => {
|
||||
const transitions: ConnectionState[] = [];
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
t.onConnectionStateChange((s) => transitions.push(s));
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
expect(transitions).toEqual(["connecting", "connected"]);
|
||||
});
|
||||
|
||||
it("serialises outbound frames as JSON when the socket is open", async () => {
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
t.send({ id: "1", method: "system.ping" });
|
||||
expect(lastSocket().sent).toEqual([JSON.stringify({ id: "1", method: "system.ping" })]);
|
||||
});
|
||||
|
||||
it("invokes onMessage for inbound JSON frames", async () => {
|
||||
const handler = vi.fn();
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
t.onMessage(handler);
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
lastSocket().receive({ id: "1", result: { pong: true } });
|
||||
expect(handler).toHaveBeenCalledWith({ id: "1", result: { pong: true } });
|
||||
});
|
||||
|
||||
it("disconnect() closes the socket and stops reconnecting", async () => {
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
await t.disconnect();
|
||||
expect(lastSocket().closeCalls).toBeGreaterThan(0);
|
||||
expect(t.state).toBe("disconnected");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(FakeSocket.instances.length).toBe(1);
|
||||
});
|
||||
|
||||
it("backs off exponentially across consecutive failed reconnects (1s, 2s, 4s, …, capped at 5s)", async () => {
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const states: ConnectionState[] = [];
|
||||
t.onConnectionStateChange((s) => states.push(s));
|
||||
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
expect(FakeSocket.instances.length).toBe(1);
|
||||
|
||||
// First unexpected close kicks off the backoff cascade. From this point
|
||||
// we never let a reconnect attempt succeed; each new socket is closed
|
||||
// immediately so the backoff counter keeps growing.
|
||||
lastSocket().serverClose();
|
||||
|
||||
const expectedDelays = [1_000, 2_000, 4_000, 5_000, 5_000, 5_000, 5_000];
|
||||
for (let i = 0; i < expectedDelays.length; i += 1) {
|
||||
const beforeCount = FakeSocket.instances.length;
|
||||
const advance = expectedDelays[i];
|
||||
if (advance > 1) {
|
||||
await vi.advanceTimersByTimeAsync(advance - 1);
|
||||
expect(FakeSocket.instances.length).toBe(beforeCount);
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(FakeSocket.instances.length).toBe(beforeCount + 1);
|
||||
lastSocket().serverClose();
|
||||
}
|
||||
|
||||
expect(states.includes("connecting")).toBe(true);
|
||||
expect(states.includes("disconnected")).toBe(true);
|
||||
});
|
||||
|
||||
it("resets the backoff counter after a successful (re)connect", async () => {
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
|
||||
// First reconnect attempt at 1s, succeeds.
|
||||
lastSocket().serverClose();
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(FakeSocket.instances.length).toBe(2);
|
||||
lastSocket().open();
|
||||
await Promise.resolve();
|
||||
|
||||
// After a successful reconnect, the next failure should once again wait
|
||||
// only the initial delay (1s), not 2s.
|
||||
lastSocket().serverClose();
|
||||
const beforeCount = FakeSocket.instances.length;
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(FakeSocket.instances.length).toBe(beforeCount);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(FakeSocket.instances.length).toBe(beforeCount + 1);
|
||||
});
|
||||
|
||||
it("ignores malformed inbound messages (non-JSON) without throwing", async () => {
|
||||
const handler = vi.fn();
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
t.onMessage(handler);
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
|
||||
const socket = lastSocket();
|
||||
for (const l of socket.listeners.message ?? []) {
|
||||
l({ data: "{not json" });
|
||||
}
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
expect(t.state).toBe("connected");
|
||||
});
|
||||
|
||||
it("disposes handlers via Disposable returned from onMessage", async () => {
|
||||
const handler = vi.fn();
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const disp = t.onMessage(handler);
|
||||
const p = t.connect();
|
||||
lastSocket().open();
|
||||
await p;
|
||||
|
||||
lastSocket().receive({ id: "1", result: 1 });
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
disp.dispose();
|
||||
lastSocket().receive({ id: "2", result: 2 });
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
// Build-time constants injected via Vite's `define` (see
|
||||
// wxt.config.ts and vitest.config.ts). Declared globally so any module
|
||||
// that wants to surface the extension's own semver to the daemon /
|
||||
// popup / status panel can read it without re-importing package.json
|
||||
// at runtime (review M3 fix to round-1).
|
||||
|
||||
declare const __BSK_EXT_VERSION__: string;
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { Transport } from "./transport";
|
||||
import type {
|
||||
HandshakeParams,
|
||||
HandshakeResult,
|
||||
ProtocolFrame,
|
||||
RequestFrame,
|
||||
ResponseFrame,
|
||||
} from "./types";
|
||||
|
||||
export const PROTOCOL_VERSION = "1.0";
|
||||
/**
|
||||
* Extension semver, injected at build time from `package.json` via
|
||||
* Vite's `define` (see `wxt.config.ts` and `vitest.config.ts`).
|
||||
*/
|
||||
export const EXTENSION_VERSION: string =
|
||||
typeof __BSK_EXT_VERSION__ === "string" ? __BSK_EXT_VERSION__ : "0.0.0-unset";
|
||||
/**
|
||||
* Lowest **protocol** version this extension accepts (e.g. `"1.0"`).
|
||||
* Must stay in sync with daemon `MIN_COMPATIBLE_PROTOCOL`.
|
||||
*/
|
||||
export const MIN_COMPATIBLE_PROTOCOL = "1.0";
|
||||
/**
|
||||
* **Deprecated** — legacy app-semver floor for wire compat with old
|
||||
* daemons. New code sends `"0.0.0"`; compat decisions ignore this.
|
||||
*/
|
||||
export const MIN_COMPATIBLE_PEER = "0.0.0";
|
||||
export const CLIENT_ID = "browser-skill-extension";
|
||||
|
||||
export interface BrowserMeta {
|
||||
name: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
export interface HandshakeInput {
|
||||
instanceId: string;
|
||||
browser: BrowserMeta;
|
||||
label: string;
|
||||
/**
|
||||
* Used to make the handshake's RPC id stable in tests. Defaults to a
|
||||
* random short string.
|
||||
*/
|
||||
rpcId?: string;
|
||||
}
|
||||
|
||||
export interface HandshakeOutcome {
|
||||
params: HandshakeParams;
|
||||
result: HandshakeResult;
|
||||
}
|
||||
|
||||
function ridToString(): string {
|
||||
return `hs-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the mandatory first frame on a fresh connection: `system.handshake`.
|
||||
*/
|
||||
export function performHandshake(
|
||||
transport: Transport,
|
||||
input: HandshakeInput,
|
||||
options: { timeoutMs?: number } = {},
|
||||
): Promise<HandshakeOutcome> {
|
||||
const id = input.rpcId ?? ridToString();
|
||||
const params: HandshakeParams = {
|
||||
client: CLIENT_ID,
|
||||
version: EXTENSION_VERSION,
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
instance_id: input.instanceId,
|
||||
browser: input.browser,
|
||||
label: input.label,
|
||||
min_compatible_peer: MIN_COMPATIBLE_PEER,
|
||||
min_compatible_protocol: MIN_COMPATIBLE_PROTOCOL,
|
||||
};
|
||||
|
||||
const req: RequestFrame = { id, method: "system.handshake", params };
|
||||
const timeoutMs = options.timeoutMs ?? 10_000;
|
||||
|
||||
return new Promise<HandshakeOutcome>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error("[handshake] timed out waiting for daemon response"));
|
||||
}, timeoutMs);
|
||||
|
||||
const sub = transport.onMessage((msg: ProtocolFrame) => {
|
||||
if (!isResponseFor(msg, id)) return;
|
||||
cleanup();
|
||||
const r = msg as ResponseFrame;
|
||||
if ("error" in r) {
|
||||
reject(
|
||||
new Error(`[handshake] daemon rejected handshake: ${r.error.code} — ${r.error.message}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const result = r.result as HandshakeResult;
|
||||
resolve({ params, result });
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
clearTimeout(timer);
|
||||
sub.dispose();
|
||||
}
|
||||
|
||||
try {
|
||||
transport.send(req);
|
||||
} catch (err) {
|
||||
cleanup();
|
||||
reject(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function isResponseFor(msg: ProtocolFrame, id: string): boolean {
|
||||
return (
|
||||
typeof (msg as ResponseFrame).id === "string" &&
|
||||
(msg as ResponseFrame).id === id &&
|
||||
("result" in (msg as object) || "error" in (msg as object))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort browser meta detection from `navigator.userAgent`.
|
||||
*/
|
||||
export function detectBrowserMeta(ua: string = navigator.userAgent): BrowserMeta {
|
||||
const probes: Array<[RegExp, string]> = [
|
||||
[/Edg\/([0-9.]+)/, "edge"],
|
||||
[/OPR\/([0-9.]+)/, "opera"],
|
||||
[/Brave\/([0-9.]+)/, "brave"],
|
||||
[/Arc\/([0-9.]+)/, "arc"],
|
||||
[/Chrome\/([0-9.]+)/, "chrome"],
|
||||
];
|
||||
for (const [re, name] of probes) {
|
||||
const m = re.exec(ua);
|
||||
if (m) return { name, version: m[1] };
|
||||
}
|
||||
return { name: "chromium", version: "unknown" };
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ConnectionState, ProtocolFrame } from "./types";
|
||||
|
||||
export interface Disposable {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export type FrameHandler = (msg: ProtocolFrame) => void;
|
||||
export type ConnectionStateHandler = (state: ConnectionState) => void;
|
||||
|
||||
/**
|
||||
* Abstraction over a bidirectional protocol channel (§4.7).
|
||||
*
|
||||
* v1 ships a single {@link WSTransport} implementation. Forks that want a
|
||||
* different transport (e.g. native messaging, MessageChannel for embedding
|
||||
* in a host page) only have to implement this interface and swap the
|
||||
* concrete class in `entrypoints/background.ts`.
|
||||
*/
|
||||
export interface Transport {
|
||||
connect(): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
send(msg: ProtocolFrame): void;
|
||||
onMessage(handler: FrameHandler): Disposable;
|
||||
onConnectionStateChange(handler: ConnectionStateHandler): Disposable;
|
||||
readonly state: ConnectionState;
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
// Wire-protocol shapes mirroring bsk-protocol (see crates/bsk-protocol/schema/*.json). The
|
||||
// daemon serialises Rust structs via serde; these TS types intentionally
|
||||
// stay structural (interface, not class) so the same JSON parses on both
|
||||
// sides without extra adapters.
|
||||
|
||||
export type RpcId = string;
|
||||
|
||||
export type ErrorCode =
|
||||
| "unknown_method"
|
||||
| "unsupported"
|
||||
| "invalid_params"
|
||||
| "not_found"
|
||||
| "permission_denied"
|
||||
| "timeout"
|
||||
| "cdp_failed"
|
||||
| "protocol_error"
|
||||
| "cancelled"
|
||||
| "version_too_old"
|
||||
| "multiple_browsers_online"
|
||||
| "no_browser_connected";
|
||||
|
||||
/** Stable `RpcError.data.reason` values for CLI hint selection. */
|
||||
export type RpcErrorReason =
|
||||
| "agent_window_scope"
|
||||
| "element_not_visible"
|
||||
| "ref_not_found"
|
||||
| "selector_not_found"
|
||||
| "target_not_fillable"
|
||||
| "target_not_select"
|
||||
| "option_not_found"
|
||||
| "single_select_value_count"
|
||||
| "tab_not_active"
|
||||
| "borrow_conflict";
|
||||
|
||||
export interface RpcErrorData {
|
||||
reason?: RpcErrorReason;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface RpcError {
|
||||
code: ErrorCode;
|
||||
message: string;
|
||||
data?: RpcErrorData;
|
||||
}
|
||||
|
||||
export interface RequestFrame {
|
||||
id: RpcId;
|
||||
method: string;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export interface OkResponseFrame {
|
||||
id: RpcId;
|
||||
result: unknown;
|
||||
}
|
||||
|
||||
export interface ErrResponseFrame {
|
||||
id: RpcId;
|
||||
error: RpcError;
|
||||
}
|
||||
|
||||
export type ResponseFrame = OkResponseFrame | ErrResponseFrame;
|
||||
|
||||
export interface EventFrame {
|
||||
event: string;
|
||||
payload?: unknown;
|
||||
}
|
||||
|
||||
export type ProtocolFrame = RequestFrame | ResponseFrame | EventFrame;
|
||||
|
||||
export function isRequestFrame(f: ProtocolFrame): f is RequestFrame {
|
||||
return typeof (f as RequestFrame).method === "string";
|
||||
}
|
||||
|
||||
export function isResponseFrame(f: ProtocolFrame): f is ResponseFrame {
|
||||
return (
|
||||
typeof (f as ResponseFrame).id === "string" &&
|
||||
("result" in (f as object) || "error" in (f as object))
|
||||
);
|
||||
}
|
||||
|
||||
export function isEventFrame(f: ProtocolFrame): f is EventFrame {
|
||||
return typeof (f as EventFrame).event === "string";
|
||||
}
|
||||
|
||||
export interface BrowserPeerInfo {
|
||||
name: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
export interface HandshakeParams {
|
||||
client: string;
|
||||
version: string;
|
||||
protocol_version: string;
|
||||
instance_id: string;
|
||||
browser: BrowserPeerInfo;
|
||||
label: string;
|
||||
/**
|
||||
* **Deprecated** — legacy app-semver floor for old daemons. New code
|
||||
* sends `"0.0.0"` and ignores on read.
|
||||
*/
|
||||
min_compatible_peer?: string;
|
||||
/** Lowest daemon **protocol** version this extension accepts. */
|
||||
min_compatible_protocol?: string;
|
||||
}
|
||||
|
||||
export interface HandshakeResult {
|
||||
server: string;
|
||||
version: string;
|
||||
protocol_version: string;
|
||||
/** Deprecated legacy app-semver floor; absent on newer daemons. */
|
||||
min_compatible_peer?: string;
|
||||
/** Protocol floor advertised by the daemon; absent on legacy daemons. */
|
||||
min_compatible_protocol?: string;
|
||||
}
|
||||
|
||||
export type ConnectionState = "disconnected" | "connecting" | "connected" | "version_skew";
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// M6 tool payloads — mirror bsk-protocol (crates/bsk-protocol/src/tools/*.rs)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export type JavaScriptDialogType = "alert" | "confirm" | "prompt" | "beforeunload";
|
||||
export type JavaScriptDialogHandledAction = "accepted" | "dismissed";
|
||||
|
||||
export interface JavaScriptDialogInfo {
|
||||
tab_id: number;
|
||||
type: JavaScriptDialogType;
|
||||
message: string;
|
||||
url?: string;
|
||||
default_prompt?: string;
|
||||
has_browser_handler?: boolean;
|
||||
handled: JavaScriptDialogHandledAction;
|
||||
sequence: number;
|
||||
}
|
||||
|
||||
export type TabScopeFilter = "user" | "agent" | "all";
|
||||
|
||||
export interface TabInfo {
|
||||
tab_id: number;
|
||||
title?: string;
|
||||
url?: string;
|
||||
window_id?: number;
|
||||
active?: boolean;
|
||||
scope?: "user" | "agent";
|
||||
}
|
||||
|
||||
export interface TabListParams {
|
||||
session_id: string;
|
||||
scope?: TabScopeFilter;
|
||||
}
|
||||
|
||||
export interface TabListResult {
|
||||
tabs: TabInfo[];
|
||||
}
|
||||
|
||||
// --- M8 tab management payloads (M8.1) ---
|
||||
|
||||
export interface TabCreateParams {
|
||||
session_id: string;
|
||||
url?: string;
|
||||
active?: boolean;
|
||||
index?: number;
|
||||
}
|
||||
|
||||
export interface TabCreateResult {
|
||||
tab_id: number;
|
||||
window_id: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface TabCloseParams {
|
||||
session_id: string;
|
||||
tab_id: number;
|
||||
}
|
||||
|
||||
export interface TabCloseResult {
|
||||
tab_id: number;
|
||||
}
|
||||
|
||||
export interface TabSelectParams {
|
||||
session_id: string;
|
||||
tab_id: number;
|
||||
}
|
||||
|
||||
export interface TabSelectResult {
|
||||
tab_id: number;
|
||||
window_id: number;
|
||||
}
|
||||
|
||||
export interface TabBorrowParams {
|
||||
session_id: string;
|
||||
tab_id: number;
|
||||
confirm?: boolean;
|
||||
}
|
||||
|
||||
export interface TabBorrowResult {
|
||||
tab_id: number;
|
||||
original_window_id: number;
|
||||
original_index: number;
|
||||
agent_window_id: number;
|
||||
}
|
||||
|
||||
export interface TabReturnParams {
|
||||
session_id: string;
|
||||
tab_id: number;
|
||||
}
|
||||
|
||||
export interface TabReturnResult {
|
||||
tab_id: number;
|
||||
returned_to_window_id: number;
|
||||
returned_to_index: number;
|
||||
fallback?: boolean;
|
||||
}
|
||||
|
||||
export interface ScreenshotParams {
|
||||
session_id: string;
|
||||
tab_id?: number;
|
||||
/** `@eN` ref from the last `tool.snapshot`. */
|
||||
ref?: string;
|
||||
}
|
||||
|
||||
export interface ScreenshotResult {
|
||||
image_base64: string;
|
||||
width: number;
|
||||
height: number;
|
||||
format: string;
|
||||
tab_id: number;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface SnapshotParams {
|
||||
session_id: string;
|
||||
tab_id?: number;
|
||||
max_depth?: number;
|
||||
max_tokens?: number;
|
||||
}
|
||||
|
||||
export interface SnapshotResult {
|
||||
text: string;
|
||||
ref_count: number;
|
||||
tab_id: number;
|
||||
truncated?: boolean;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface GetHtmlParams {
|
||||
session_id: string;
|
||||
tab_id?: number;
|
||||
ref?: string;
|
||||
max_bytes?: number;
|
||||
}
|
||||
|
||||
export interface GetHtmlResult {
|
||||
html: string;
|
||||
truncated?: boolean;
|
||||
byte_size: number;
|
||||
tab_id: number;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// M7 tool payloads — navigation (mirror bsk-protocol)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export type WaitUntil = "load" | "domcontentloaded" | "networkidle" | "commit";
|
||||
|
||||
export interface NavigateParams {
|
||||
session_id: string;
|
||||
url: string;
|
||||
tab_id?: number;
|
||||
wait_until?: WaitUntil;
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface NavigateResult {
|
||||
tab_id: number;
|
||||
url: string;
|
||||
final_url?: string;
|
||||
reached: string;
|
||||
error_text?: string;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface NavigateBackParams {
|
||||
session_id: string;
|
||||
tab_id?: number;
|
||||
wait_until?: WaitUntil;
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface NavigateForwardParams extends NavigateBackParams {}
|
||||
|
||||
export interface NavigateHistoryResult {
|
||||
tab_id: number;
|
||||
previous_url?: string;
|
||||
final_url?: string;
|
||||
reached: string;
|
||||
error_text?: string;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface ReloadParams {
|
||||
session_id: string;
|
||||
tab_id?: number;
|
||||
wait_until?: WaitUntil;
|
||||
timeout_ms?: number;
|
||||
hard?: boolean;
|
||||
}
|
||||
|
||||
export type ReloadResult = NavigateHistoryResult;
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// M7 tool payloads — interaction (mirror bsk-protocol)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export type MouseButton = "left" | "middle" | "right";
|
||||
export type KeyModifier = "alt" | "ctrl" | "meta" | "shift";
|
||||
|
||||
export interface ClickParams {
|
||||
session_id: string;
|
||||
ref?: string;
|
||||
selector?: string;
|
||||
tab_id?: number;
|
||||
button?: MouseButton;
|
||||
click_count?: number;
|
||||
modifiers?: KeyModifier[];
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface ClickResult {
|
||||
tab_id: number;
|
||||
used_ref?: string;
|
||||
used_selector?: string;
|
||||
x: number;
|
||||
y: number;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface FillParams {
|
||||
session_id: string;
|
||||
value: string;
|
||||
ref?: string;
|
||||
selector?: string;
|
||||
tab_id?: number;
|
||||
clear_before?: boolean;
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface FillResult {
|
||||
tab_id: number;
|
||||
used_ref?: string;
|
||||
used_selector?: string;
|
||||
value_length: number;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface PressParams {
|
||||
session_id: string;
|
||||
key: string;
|
||||
modifiers?: KeyModifier[];
|
||||
ref?: string;
|
||||
selector?: string;
|
||||
tab_id?: number;
|
||||
hold_ms?: number;
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface PressResult {
|
||||
tab_id: number;
|
||||
key: string;
|
||||
code: string;
|
||||
modifiers: KeyModifier[];
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface SelectParams {
|
||||
session_id: string;
|
||||
values: string[];
|
||||
ref?: string;
|
||||
selector?: string;
|
||||
tab_id?: number;
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface SelectResult {
|
||||
tab_id: number;
|
||||
used_ref?: string;
|
||||
used_selector?: string;
|
||||
multiple: boolean;
|
||||
selected_values: string[];
|
||||
selected_labels: string[];
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// M9 tool payloads — evaluate / wait_for_navigation / wait_ms
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export interface EvaluateParams {
|
||||
session_id: string;
|
||||
expression: string;
|
||||
tab_id?: number;
|
||||
await_promise?: boolean;
|
||||
return_by_value?: boolean;
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface EvaluateError {
|
||||
text: string;
|
||||
line?: number;
|
||||
column?: number;
|
||||
}
|
||||
|
||||
export interface EvaluateResult {
|
||||
ok: boolean;
|
||||
tab_id: number;
|
||||
value?: unknown;
|
||||
error?: EvaluateError;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
export interface WaitForNavigationParams {
|
||||
session_id: string;
|
||||
tab_id?: number;
|
||||
wait_until?: WaitUntil;
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export type WaitForNavigationReached = WaitUntil | "timeout";
|
||||
|
||||
export interface WaitForNavigationResult {
|
||||
tab_id: number;
|
||||
reached: WaitForNavigationReached;
|
||||
error_text?: string;
|
||||
dialogs?: JavaScriptDialogInfo[];
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Human-in-loop payloads — request_help (mirror bsk-protocol)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
export interface HelpTarget {
|
||||
ref?: string;
|
||||
selector?: string;
|
||||
}
|
||||
|
||||
export type HelpOutcome = "continued" | "cancelled" | "timed_out" | "navigated";
|
||||
|
||||
export interface ResolvedTarget {
|
||||
matched: boolean;
|
||||
ref?: string;
|
||||
selector?: string;
|
||||
}
|
||||
|
||||
export interface RequestHelpParams {
|
||||
session_id: string;
|
||||
tab_id?: number;
|
||||
prompt: string;
|
||||
title?: string;
|
||||
targets?: HelpTarget[];
|
||||
timeout_ms?: number;
|
||||
}
|
||||
|
||||
export interface RequestHelpResult {
|
||||
outcome: HelpOutcome;
|
||||
note?: string;
|
||||
tab_id: number;
|
||||
resolved_targets?: ResolvedTarget[];
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import type { ConnectionStateHandler, Disposable, FrameHandler, Transport } from "./transport";
|
||||
import type { ConnectionState, ProtocolFrame } from "./types";
|
||||
|
||||
const DEFAULT_INITIAL_DELAY_MS = 1_000;
|
||||
const DEFAULT_MAX_DELAY_MS = 5_000;
|
||||
|
||||
export type WebSocketFactory = (url: string) => WebSocket;
|
||||
|
||||
export interface ReconnectOptions {
|
||||
initialDelayMs?: number;
|
||||
maxDelayMs?: number;
|
||||
}
|
||||
|
||||
export interface WSTransportOptions {
|
||||
url: string;
|
||||
reconnect?: ReconnectOptions;
|
||||
/**
|
||||
* Inject a fake WebSocket constructor in tests; defaults to `globalThis.WebSocket`.
|
||||
*/
|
||||
webSocketFactory?: WebSocketFactory;
|
||||
}
|
||||
|
||||
interface CloseLikeEvent {
|
||||
code?: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
interface MessageLikeEvent {
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket-backed implementation of {@link Transport} (design §4.7).
|
||||
*
|
||||
* Lifecycle:
|
||||
* - `connect()` opens a socket and resolves once it transitions to OPEN.
|
||||
* - Inbound text frames are parsed as JSON and dispatched to message handlers.
|
||||
* - Outbound frames are JSON-serialised and sent only when the socket is OPEN.
|
||||
* - Unexpected closes trigger an exponential-backoff reconnect loop
|
||||
* (1s, 2s, 4s, …, capped at 5s) until `disconnect()` is called.
|
||||
*/
|
||||
export class WSTransport implements Transport {
|
||||
private readonly url: string;
|
||||
private readonly factory: WebSocketFactory;
|
||||
private readonly initialDelayMs: number;
|
||||
private readonly maxDelayMs: number;
|
||||
|
||||
private socket: WebSocket | null = null;
|
||||
private currentState: ConnectionState = "disconnected";
|
||||
private explicitlyClosed = false;
|
||||
private reconnectAttempt = 0;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private connectingPromise: Promise<void> | null = null;
|
||||
private resolveConnect: ((value: void) => void) | null = null;
|
||||
private rejectConnect: ((reason: Error) => void) | null = null;
|
||||
|
||||
private readonly messageHandlers = new Set<FrameHandler>();
|
||||
private readonly stateHandlers = new Set<ConnectionStateHandler>();
|
||||
|
||||
constructor(options: WSTransportOptions) {
|
||||
this.url = options.url;
|
||||
this.factory = options.webSocketFactory ?? ((url: string) => new WebSocket(url));
|
||||
this.initialDelayMs = options.reconnect?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
|
||||
this.maxDelayMs = options.reconnect?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
|
||||
}
|
||||
|
||||
get state(): ConnectionState {
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
connect(): Promise<void> {
|
||||
if (this.connectingPromise) return this.connectingPromise;
|
||||
if (this.currentState === "connected") return Promise.resolve();
|
||||
|
||||
this.explicitlyClosed = false;
|
||||
this.openSocket();
|
||||
|
||||
this.connectingPromise = new Promise<void>((resolve, reject) => {
|
||||
this.resolveConnect = resolve;
|
||||
this.rejectConnect = reject;
|
||||
});
|
||||
return this.connectingPromise;
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.explicitlyClosed = true;
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
if (this.socket) {
|
||||
try {
|
||||
this.socket.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
this.setState("disconnected");
|
||||
// Honour the Promise contract: if connect() never settled because
|
||||
// the caller chose to disconnect first, reject the pending promise
|
||||
// so awaiting code (e.g. ConnectionController.attach) observes the
|
||||
// outcome rather than hanging silently (review M4/M5 round 3
|
||||
// m-R3-2).
|
||||
const reject = this.rejectConnect;
|
||||
this.connectingPromise = null;
|
||||
this.resolveConnect = null;
|
||||
this.rejectConnect = null;
|
||||
reject?.(new Error("[WSTransport] disconnect during connect"));
|
||||
}
|
||||
|
||||
send(msg: ProtocolFrame): void {
|
||||
if (!this.socket || this.socket.readyState !== 1 /* OPEN */) {
|
||||
throw new Error("[WSTransport] cannot send while not connected");
|
||||
}
|
||||
this.socket.send(JSON.stringify(msg));
|
||||
}
|
||||
|
||||
onMessage(handler: FrameHandler): Disposable {
|
||||
this.messageHandlers.add(handler);
|
||||
return {
|
||||
dispose: () => {
|
||||
this.messageHandlers.delete(handler);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
onConnectionStateChange(handler: ConnectionStateHandler): Disposable {
|
||||
this.stateHandlers.add(handler);
|
||||
return {
|
||||
dispose: () => {
|
||||
this.stateHandlers.delete(handler);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private openSocket(): void {
|
||||
this.setState("connecting");
|
||||
const socket = this.factory(this.url);
|
||||
this.socket = socket;
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
this.reconnectAttempt = 0;
|
||||
this.setState("connected");
|
||||
const resolve = this.resolveConnect;
|
||||
this.resolveConnect = null;
|
||||
this.rejectConnect = null;
|
||||
this.connectingPromise = null;
|
||||
resolve?.();
|
||||
});
|
||||
|
||||
socket.addEventListener("message", (ev: MessageEvent) => {
|
||||
this.handleInbound((ev as unknown as MessageLikeEvent).data);
|
||||
});
|
||||
|
||||
socket.addEventListener("close", (ev: Event) => {
|
||||
this.handleClose(ev as unknown as CloseLikeEvent);
|
||||
});
|
||||
|
||||
socket.addEventListener("error", () => {
|
||||
// The 'close' handler always fires after 'error' in browsers, so we
|
||||
// just record the error and let close drive reconnect logic.
|
||||
});
|
||||
}
|
||||
|
||||
private handleInbound(data: unknown): void {
|
||||
if (typeof data !== "string") return;
|
||||
let parsed: ProtocolFrame;
|
||||
try {
|
||||
parsed = JSON.parse(data) as ProtocolFrame;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const h of this.messageHandlers) {
|
||||
try {
|
||||
h(parsed);
|
||||
} catch (err) {
|
||||
console.error("[WSTransport] message handler threw", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleClose(_ev: CloseLikeEvent): void {
|
||||
this.socket = null;
|
||||
if (this.explicitlyClosed) {
|
||||
this.setState("disconnected");
|
||||
return;
|
||||
}
|
||||
this.setState("disconnected");
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimer) return;
|
||||
const delay = Math.min(this.initialDelayMs * 2 ** this.reconnectAttempt, this.maxDelayMs);
|
||||
this.reconnectAttempt += 1;
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
if (this.explicitlyClosed) return;
|
||||
this.openSocket();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private setState(next: ConnectionState): void {
|
||||
if (this.currentState === next) return;
|
||||
this.currentState = next;
|
||||
for (const h of this.stateHandlers) {
|
||||
try {
|
||||
h(next);
|
||||
} catch (err) {
|
||||
console.error("[WSTransport] state handler threw", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user