@wkqco33/pi-remote-control 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pi-remote-control contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @wkqco33/pi-remote-control (pi extension)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `pi` 코딩 에이전트 세션을 Go 릴레이 서버(`pi-remote-server`)와 연결해 웹/모바일 브라우저에서 원격 제어할 수 있도록 해주는 `pi` 확장 패키지입니다.
4
+
5
+ ```bash
6
+ pi install npm:@wkqco33/pi-remote-control
7
+ ```
8
+
9
+ - 런타임 npm 의존성 제로 (Node 22+ 내장 `WebSocket` 사용)
10
+ - 로컬 터미널 전용 6자리 페어링 코드
11
+ - 실시간 `text` / `thinking` 델타 스트리밍 및 `steer` / `followUp` / `abort`
12
+ - 원격 턴 도구 정책(`unrestricted` / `read-only` / `no-tools`) 및 웹/로컬 도구 승인
13
+ - 시크릿 리댁션, 이미지 첨부, 작업 다이제스트(`/remote digest`)
14
+
15
+ 자세한 서버 설정과 아키텍처는 [루트 README](../README.md)를 참고하세요.
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@wkqco33/pi-remote-control",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Remote control extension for pi coding agent: stream live sessions, steer/followUp prompts, and approve tool calls from a web relay server.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi-extension",
10
+ "pi",
11
+ "remote-control",
12
+ "web",
13
+ "relay"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22.0.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/wkqco33/pi-remote-control.git",
21
+ "directory": "extension"
22
+ },
23
+ "homepage": "https://github.com/wkqco33/pi-remote-control#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/wkqco33/pi-remote-control/issues"
26
+ },
27
+ "pi": {
28
+ "extensions": [
29
+ "./src/index.ts"
30
+ ]
31
+ },
32
+ "files": [
33
+ "src",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "test": "vitest run",
39
+ "test:watch": "vitest",
40
+ "typecheck": "tsc --noEmit",
41
+ "check": "npm run typecheck && npm run test",
42
+ "pack:check": "npm pack --dry-run",
43
+ "prepublishOnly": "npm run check"
44
+ },
45
+ "peerDependencies": {
46
+ "@earendil-works/pi-coding-agent": "*"
47
+ },
48
+ "devDependencies": {
49
+ "@earendil-works/pi-coding-agent": "^0.85.1",
50
+ "@types/node": "^24.0.0",
51
+ "typescript": "^5.9.2",
52
+ "vitest": "^3.2.4"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ }
57
+ }
@@ -0,0 +1,76 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { DEFAULT_REMOTE_CONFIG } from "../config.js";
3
+ import type { WireEnvelope } from "../core/protocol.js";
4
+ import { RemoteBridge, type RemoteHost, type TransportSink } from "./remote-bridge.js";
5
+
6
+ function makeHarness(requirePairing = true) {
7
+ const sent: WireEnvelope[] = [];
8
+ const notices: string[] = [];
9
+ const prompts: Array<{ text: string; deliverAs?: string }> = [];
10
+ let idx = 0;
11
+ const randSeq = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.9, 0.8, 0.7, 0.0, 0.9, 0.8];
12
+
13
+ const sink: TransportSink = {
14
+ currentStatus: "connected",
15
+ send(env) {
16
+ sent.push(env);
17
+ return true;
18
+ },
19
+ };
20
+ const host: RemoteHost = {
21
+ sessionId: "sess-1",
22
+ host: "box",
23
+ cwd: "/repo",
24
+ isIdle: () => true,
25
+ sendPrompt: (text, opts) => prompts.push({ text, deliverAs: opts?.deliverAs }),
26
+ abort: vi.fn(),
27
+ notify: (text) => notices.push(text),
28
+ getHistory: () => [{ role: "user", text: "hi" }],
29
+ getDigest: async () => "digest md",
30
+ now: () => 1000,
31
+ random: () => randSeq[idx++ % randSeq.length] ?? 0,
32
+ };
33
+ const bridge = new RemoteBridge({
34
+ config: { ...DEFAULT_REMOTE_CONFIG, requirePairing, approvalTimeoutMs: 5000 },
35
+ host,
36
+ sink,
37
+ });
38
+ return { bridge, sent, notices, prompts, host };
39
+ }
40
+
41
+ describe("RemoteBridge", () => {
42
+ it("blocks unauthenticated prompt, shows pairing code only locally, and pairs", async () => {
43
+ const { bridge, sent, notices, prompts } = makeHarness(true);
44
+ await bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text: "hack" });
45
+ expect(prompts).toHaveLength(0);
46
+ expect(notices[0]).toContain("123-456");
47
+ expect(JSON.stringify(sent)).not.toContain("123456");
48
+
49
+ await bridge.handleServerMessage({ type: "pair.submit", clientId: "web-1", code: "123456" });
50
+ expect(sent.at(-1)?.type).toBe("pair.result");
51
+ expect((sent.at(-1)?.payload as { ok: boolean }).ok).toBe(true);
52
+
53
+ await bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text: "hello" });
54
+ expect(prompts).toEqual([{ text: "hello", deliverAs: undefined }]);
55
+ });
56
+
57
+ it("handles web tool approval and resolves false on disconnect", async () => {
58
+ const { bridge, sent } = makeHarness(false);
59
+ const promise = bridge.requestWebApproval("tc-1", "bash");
60
+ const req = sent.find((e) => e.type === "approval.request");
61
+ expect(req).toBeDefined();
62
+ const requestId = (req?.payload as { requestId: string }).requestId;
63
+
64
+ await bridge.handleServerMessage({
65
+ type: "approval.response",
66
+ clientId: "web-1",
67
+ requestId,
68
+ approved: true,
69
+ });
70
+ await expect(promise).resolves.toBe(true);
71
+
72
+ const promise2 = bridge.requestWebApproval("tc-2", "bash");
73
+ bridge.onConnectionStatus("disconnected");
74
+ await expect(promise2).resolves.toBe(false);
75
+ });
76
+ });
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Orchestrates pairing, prompt forwarding, streaming deltas, tool approval,
3
+ * history snapshots, and work digests between pi and the Go relay server.
4
+ */
5
+
6
+ import type { RemoteControlConfig } from "../config.js";
7
+ import { createChallenge, formatChallengeCode, verifyChallenge, type PendingChallenge } from "../core/pairing.js";
8
+ import type { DeliverMode, HistoryItem, PromptImage, ServerInboundMessage, WireEnvelope } from "../core/protocol.js";
9
+ import { redactSecrets } from "../core/redact.js";
10
+ import type { ConnectionStatus, StatusSnapshot } from "../core/status.js";
11
+
12
+ export interface RemoteHost {
13
+ readonly sessionId: string;
14
+ readonly sessionName?: string;
15
+ readonly host: string;
16
+ readonly cwd: string;
17
+ readonly branch?: string;
18
+ readonly model?: string;
19
+ isIdle(): boolean;
20
+ sendPrompt(text: string, options?: { deliverAs?: DeliverMode; images?: readonly PromptImage[] }): void;
21
+ abort(): void;
22
+ notify(text: string, level?: "info" | "warning" | "error"): void;
23
+ onStateChanged?(status: ConnectionStatus, trustedClients: number): void;
24
+ getHistory(): HistoryItem[];
25
+ getDigest(): Promise<string>;
26
+ now(): number;
27
+ random(): number;
28
+ }
29
+
30
+ export interface TransportSink {
31
+ readonly currentStatus: ConnectionStatus;
32
+ send(envelope: WireEnvelope): boolean;
33
+ }
34
+
35
+ interface PendingApproval {
36
+ readonly resolve: (approved: boolean) => void;
37
+ readonly timer: ReturnType<typeof setTimeout>;
38
+ }
39
+
40
+ export class RemoteBridge {
41
+ readonly config: RemoteControlConfig;
42
+ private readonly host: RemoteHost;
43
+ private readonly sink: TransportSink;
44
+ private readonly trustedClients = new Set<string>();
45
+ private readonly pendingChallenges = new Map<string, PendingChallenge>();
46
+ private readonly pendingApprovals = new Map<string, PendingApproval>();
47
+ private approvalCounter = 0;
48
+ private lastError?: string;
49
+
50
+ constructor(options: { config: RemoteControlConfig; host: RemoteHost; sink: TransportSink }) {
51
+ this.config = options.config;
52
+ this.host = options.host;
53
+ this.sink = options.sink;
54
+ }
55
+
56
+ onConnectionStatus(status: ConnectionStatus, detail?: string): void {
57
+ if (status === "error" && detail) {
58
+ this.lastError = detail;
59
+ } else if (status === "connected") {
60
+ this.lastError = undefined;
61
+ }
62
+ if (status === "disconnected" || status === "error") {
63
+ this.rejectAllApprovals();
64
+ }
65
+ this.host.onStateChanged?.(status, this.trustedClients.size);
66
+ }
67
+
68
+ stop(): void {
69
+ this.rejectAllApprovals();
70
+ }
71
+
72
+ disconnectAll(): number {
73
+ const count = this.trustedClients.size;
74
+ this.trustedClients.clear();
75
+ this.pendingChallenges.clear();
76
+ this.rejectAllApprovals();
77
+ this.host.onStateChanged?.(this.sink.currentStatus, 0);
78
+ return count;
79
+ }
80
+
81
+ statusSnapshot(): StatusSnapshot {
82
+ return {
83
+ status: this.sink.currentStatus,
84
+ serverUrl: this.config.serverUrl,
85
+ sessionId: this.host.sessionId,
86
+ trustedClients: this.trustedClients.size,
87
+ pendingPairings: this.pendingChallenges.size,
88
+ remoteToolPolicy: this.config.remoteToolPolicy,
89
+ remoteToolApproval: this.config.remoteToolApproval,
90
+ ...(this.lastError ? { lastError: this.lastError } : {}),
91
+ };
92
+ }
93
+
94
+ async handleServerMessage(msg: ServerInboundMessage): Promise<void> {
95
+ switch (msg.type) {
96
+ case "history.request": {
97
+ const items = this.host.getHistory();
98
+ this.sink.send({
99
+ type: "history.snapshot",
100
+ sessionId: this.host.sessionId,
101
+ ...(msg.clientId ? { clientId: msg.clientId } : {}),
102
+ ts: this.host.now(),
103
+ payload: { items },
104
+ });
105
+ if (msg.clientId && this.config.requirePairing && !this.trustedClients.has(msg.clientId)) {
106
+ this.issuePairingChallenge(msg.clientId, "pairing_required");
107
+ }
108
+ return;
109
+ }
110
+ case "pair.submit":
111
+ this.handlePairSubmit(msg.clientId, msg.code);
112
+ return;
113
+ case "prompt.send":
114
+ if (!this.ensureTrusted(msg.clientId)) return;
115
+ this.handlePromptSend(msg.text, msg.deliverAs, msg.images);
116
+ return;
117
+ case "turn.abort":
118
+ if (!this.ensureTrusted(msg.clientId)) return;
119
+ this.host.abort();
120
+ return;
121
+ case "digest.request":
122
+ if (!this.ensureTrusted(msg.clientId)) return;
123
+ await this.emitDigest();
124
+ return;
125
+ case "approval.response":
126
+ if (!this.ensureTrusted(msg.clientId)) return;
127
+ this.resolveApproval(msg.requestId, msg.approved);
128
+ return;
129
+ default:
130
+ return;
131
+ }
132
+ }
133
+
134
+ emitSessionState(runningTool?: string): void {
135
+ this.sink.send({
136
+ type: "session.state",
137
+ sessionId: this.host.sessionId,
138
+ ts: this.host.now(),
139
+ payload: {
140
+ state: this.host.isIdle() ? "idle" : "busy",
141
+ ...(this.host.sessionName ? { sessionName: this.host.sessionName } : {}),
142
+ ...(this.host.branch ? { branch: this.host.branch } : {}),
143
+ ...(this.host.model ? { model: this.host.model } : {}),
144
+ ...(runningTool ? { runningTool } : {}),
145
+ },
146
+ });
147
+ }
148
+
149
+ emitStreamStart(): void {
150
+ this.sink.send({
151
+ type: "stream.start",
152
+ sessionId: this.host.sessionId,
153
+ ts: this.host.now(),
154
+ payload: {},
155
+ });
156
+ }
157
+
158
+ emitStreamDelta(kind: "text" | "thinking", delta: string): void {
159
+ if (!delta) return;
160
+ this.sink.send({
161
+ type: "stream.delta",
162
+ sessionId: this.host.sessionId,
163
+ ts: this.host.now(),
164
+ payload: { kind, delta: redactSecrets(delta) },
165
+ });
166
+ }
167
+
168
+ emitStreamEnd(text: string): void {
169
+ this.sink.send({
170
+ type: "stream.end",
171
+ sessionId: this.host.sessionId,
172
+ ts: this.host.now(),
173
+ payload: { text: redactSecrets(text) },
174
+ });
175
+ }
176
+
177
+ emitToolStart(toolCallId: string, toolName: string): void {
178
+ this.sink.send({
179
+ type: "tool.start",
180
+ sessionId: this.host.sessionId,
181
+ ts: this.host.now(),
182
+ payload: { toolCallId, toolName },
183
+ });
184
+ }
185
+
186
+ emitToolEnd(toolCallId: string, toolName: string, isError: boolean, durationMs: number): void {
187
+ this.sink.send({
188
+ type: "tool.end",
189
+ sessionId: this.host.sessionId,
190
+ ts: this.host.now(),
191
+ payload: { toolCallId, toolName, isError, durationMs },
192
+ });
193
+ }
194
+
195
+ async emitDigest(): Promise<void> {
196
+ const markdown = await this.host.getDigest();
197
+ this.sink.send({
198
+ type: "digest.snapshot",
199
+ sessionId: this.host.sessionId,
200
+ ts: this.host.now(),
201
+ payload: { markdown: redactSecrets(markdown) },
202
+ });
203
+ }
204
+
205
+ requestWebApproval(toolCallId: string, toolName: string): Promise<boolean> {
206
+ const requestId = `apr_${this.host.now()}_${++this.approvalCounter}`;
207
+ const sent = this.sink.send({
208
+ type: "approval.request",
209
+ sessionId: this.host.sessionId,
210
+ ts: this.host.now(),
211
+ payload: {
212
+ requestId,
213
+ toolCallId,
214
+ toolName,
215
+ timeoutMs: this.config.approvalTimeoutMs,
216
+ },
217
+ });
218
+ if (!sent) {
219
+ return Promise.resolve(false);
220
+ }
221
+ return new Promise<boolean>((resolve) => {
222
+ const timer = setTimeout(() => {
223
+ this.pendingApprovals.delete(requestId);
224
+ resolve(false);
225
+ }, this.config.approvalTimeoutMs);
226
+ if (typeof timer === "object" && "unref" in timer) timer.unref();
227
+ this.pendingApprovals.set(requestId, { resolve, timer });
228
+ });
229
+ }
230
+
231
+ private ensureTrusted(clientId: string): boolean {
232
+ if (!this.config.requirePairing || this.trustedClients.has(clientId)) return true;
233
+ this.issuePairingChallenge(clientId, "pairing_required");
234
+ return false;
235
+ }
236
+
237
+ private issuePairingChallenge(clientId: string, reason: string): void {
238
+ const now = this.host.now();
239
+ let challenge = this.pendingChallenges.get(clientId);
240
+ if (!challenge || now > challenge.expiresAt) {
241
+ challenge = createChallenge({
242
+ digits: this.config.pairingDigits,
243
+ ttlMs: this.config.pairingTtlMs,
244
+ maxAttempts: this.config.pairingMaxAttempts,
245
+ now,
246
+ random: () => this.host.random(),
247
+ });
248
+ this.pendingChallenges.set(clientId, challenge);
249
+ // Security invariant: code is shown ONLY in the local pi terminal.
250
+ this.host.notify(
251
+ `[remote] Pairing code for ${clientId}: ${formatChallengeCode(challenge.code)}`,
252
+ "info",
253
+ );
254
+ }
255
+ this.sink.send({
256
+ type: "pair.required",
257
+ sessionId: this.host.sessionId,
258
+ ts: now,
259
+ payload: {
260
+ challengeId: challenge.challengeId,
261
+ digits: challenge.code.length,
262
+ expiresAt: challenge.expiresAt,
263
+ reason,
264
+ },
265
+ });
266
+ }
267
+
268
+ private handlePairSubmit(clientId: string, code: string): void {
269
+ const challenge = this.pendingChallenges.get(clientId);
270
+ if (!challenge) {
271
+ this.issuePairingChallenge(clientId, "no_active_challenge");
272
+ return;
273
+ }
274
+ const result = verifyChallenge(challenge, code, this.host.now());
275
+ if (result.ok) {
276
+ this.pendingChallenges.delete(clientId);
277
+ this.trustedClients.add(clientId);
278
+ this.host.notify(`[remote] Paired client ${clientId}.`, "info");
279
+ this.host.onStateChanged?.(this.sink.currentStatus, this.trustedClients.size);
280
+ this.sink.send({
281
+ type: "pair.result",
282
+ sessionId: this.host.sessionId,
283
+ clientId,
284
+ ts: this.host.now(),
285
+ payload: { ok: true, clientId },
286
+ });
287
+ return;
288
+ }
289
+ if (result.reason === "mismatch" && result.next) {
290
+ this.pendingChallenges.set(clientId, result.next);
291
+ } else {
292
+ this.pendingChallenges.delete(clientId);
293
+ }
294
+ this.sink.send({
295
+ type: "pair.result",
296
+ sessionId: this.host.sessionId,
297
+ clientId,
298
+ ts: this.host.now(),
299
+ payload: { ok: false, clientId, error: result.reason },
300
+ });
301
+ }
302
+
303
+ private handlePromptSend(text: string, deliverAs?: DeliverMode, images?: readonly PromptImage[]): void {
304
+ const validImages: PromptImage[] = [];
305
+ if (images) {
306
+ for (const img of images.slice(0, this.config.maxImages)) {
307
+ const estimatedBytes = Math.ceil((img.data.length * 3) / 4);
308
+ if (estimatedBytes <= this.config.maxImageBytes) {
309
+ validImages.push(img);
310
+ }
311
+ }
312
+ }
313
+ this.host.sendPrompt(text, {
314
+ ...(deliverAs ? { deliverAs } : {}),
315
+ ...(validImages.length > 0 ? { images: validImages } : {}),
316
+ });
317
+ }
318
+
319
+ private resolveApproval(requestId: string, approved: boolean): void {
320
+ const entry = this.pendingApprovals.get(requestId);
321
+ if (!entry) return;
322
+ clearTimeout(entry.timer);
323
+ this.pendingApprovals.delete(requestId);
324
+ entry.resolve(approved);
325
+ }
326
+
327
+ private rejectAllApprovals(): void {
328
+ for (const [id, entry] of this.pendingApprovals.entries()) {
329
+ clearTimeout(entry.timer);
330
+ entry.resolve(false);
331
+ this.pendingApprovals.delete(id);
332
+ }
333
+ }
334
+ }
@@ -0,0 +1,103 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { WsClient, type WebSocketLike } from "./ws-client.js";
3
+
4
+ class FakeWebSocket implements WebSocketLike {
5
+ readyState = 0;
6
+ sent: string[] = [];
7
+ private listeners = new Map<string, Array<(ev: unknown) => void>>();
8
+
9
+ addEventListener(type: string, listener: (ev: { data: unknown }) => void): void {
10
+ const list = this.listeners.get(type) ?? [];
11
+ list.push(listener as (ev: unknown) => void);
12
+ this.listeners.set(type, list);
13
+ }
14
+
15
+ send(data: string): void {
16
+ this.sent.push(data);
17
+ }
18
+
19
+ close(): void {
20
+ this.readyState = 3;
21
+ this.emit("close", {});
22
+ }
23
+
24
+ emit(type: string, ev: unknown): void {
25
+ if (type === "open") this.readyState = 1;
26
+ for (const fn of this.listeners.get(type) ?? []) fn(ev);
27
+ }
28
+ }
29
+
30
+ describe("WsClient", () => {
31
+ it("sends agent.hello on open and responds to ping", () => {
32
+ const sockets: FakeWebSocket[] = [];
33
+ const received: unknown[] = [];
34
+ const client = new WsClient({
35
+ serverUrl: "ws://localhost:8787/ws/agent",
36
+ reconnectBaseMs: 50,
37
+ reconnectMaxMs: 200,
38
+ getHello: () => ({
39
+ serverToken: "tok",
40
+ sessionId: "s1",
41
+ host: "box",
42
+ cwd: "/repo",
43
+ state: "idle",
44
+ requirePairing: true,
45
+ }),
46
+ onMessage: (m) => received.push(m),
47
+ createWebSocket: () => {
48
+ const s = new FakeWebSocket();
49
+ sockets.push(s);
50
+ return s;
51
+ },
52
+ });
53
+
54
+ client.start();
55
+ expect(sockets).toHaveLength(1);
56
+ sockets[0]?.emit("open", {});
57
+ expect(client.currentStatus).toBe("connected");
58
+ expect(JSON.parse(sockets[0]?.sent[0] ?? "{}").type).toBe("agent.hello");
59
+
60
+ sockets[0]?.emit("message", { data: JSON.stringify({ type: "ping" }) });
61
+ expect(JSON.parse(sockets[0]?.sent[1] ?? "{}").type).toBe("pong");
62
+
63
+ sockets[0]?.emit("message", { data: JSON.stringify({ type: "turn.abort", clientId: "c1" }) });
64
+ expect(received).toEqual([{ type: "turn.abort", clientId: "c1" }]);
65
+
66
+ client.stop();
67
+ expect(client.currentStatus).toBe("disconnected");
68
+ // Idempotent stop
69
+ expect(() => client.stop()).not.toThrow();
70
+ });
71
+
72
+ it("schedules reconnect on unexpected close", () => {
73
+ vi.useFakeTimers();
74
+ const sockets: FakeWebSocket[] = [];
75
+ const client = new WsClient({
76
+ serverUrl: "ws://localhost:8787/ws/agent",
77
+ reconnectBaseMs: 100,
78
+ reconnectMaxMs: 400,
79
+ getHello: () => ({
80
+ serverToken: "tok",
81
+ sessionId: "s1",
82
+ host: "box",
83
+ cwd: "/repo",
84
+ state: "idle",
85
+ requirePairing: true,
86
+ }),
87
+ onMessage: () => {},
88
+ createWebSocket: () => {
89
+ const s = new FakeWebSocket();
90
+ sockets.push(s);
91
+ return s;
92
+ },
93
+ });
94
+
95
+ client.start();
96
+ sockets[0]?.emit("close", {});
97
+ expect(sockets).toHaveLength(1);
98
+ vi.advanceTimersByTime(100);
99
+ expect(sockets).toHaveLength(2);
100
+ client.stop();
101
+ vi.useRealTimers();
102
+ });
103
+ });