@privateclaw/privateclaw 0.1.11 → 0.1.12

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.
@@ -0,0 +1,181 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import type {
8
+ PrivateClawInviteBundle,
9
+ PrivateClawProviderHandoffState,
10
+ } from "./types.js";
11
+
12
+ interface PairDaemonSuccessResult {
13
+ ok: true;
14
+ bundle: PrivateClawInviteBundle;
15
+ }
16
+
17
+ interface PairDaemonErrorResult {
18
+ ok: false;
19
+ error: string;
20
+ }
21
+
22
+ type PairDaemonResult = PairDaemonSuccessResult | PairDaemonErrorResult;
23
+
24
+ interface PairDaemonHandoffSuccessResult {
25
+ ok: true;
26
+ resumedSessionCount: number;
27
+ }
28
+
29
+ type PairDaemonHandoffResult = PairDaemonHandoffSuccessResult | PairDaemonErrorResult;
30
+
31
+ async function resolveCliInvocation(
32
+ cliModuleUrl: string,
33
+ ): Promise<{ command: string; args: string[] }> {
34
+ const cliPath = fileURLToPath(cliModuleUrl);
35
+ return path.extname(cliPath) === ".ts"
36
+ ? {
37
+ command: process.execPath,
38
+ args: ["--import", "tsx", cliPath],
39
+ }
40
+ : {
41
+ command: process.execPath,
42
+ args: [cliPath],
43
+ };
44
+ }
45
+
46
+ async function waitForResultFile<T>(
47
+ resultPath: string,
48
+ timeoutMs: number,
49
+ ): Promise<T> {
50
+ const startedAt = Date.now();
51
+ for (;;) {
52
+ try {
53
+ return JSON.parse(await readFile(resultPath, "utf8")) as T;
54
+ } catch (error) {
55
+ const code = (error as NodeJS.ErrnoException).code;
56
+ if (error instanceof SyntaxError) {
57
+ // The daemon may still be writing the result file.
58
+ } else if (code !== "ENOENT") {
59
+ throw error;
60
+ }
61
+ if (Date.now() - startedAt > timeoutMs) {
62
+ throw new Error(
63
+ `Timed out waiting for background pair session result: ${resultPath}`,
64
+ );
65
+ }
66
+ await new Promise((resolve) => setTimeout(resolve, 100));
67
+ }
68
+ }
69
+ }
70
+
71
+ export async function spawnBackgroundPairDaemon(params: {
72
+ cliModuleUrl: string;
73
+ env?: NodeJS.ProcessEnv;
74
+ stateDir: string;
75
+ ttlMs?: number;
76
+ label?: string;
77
+ groupMode?: boolean;
78
+ openInBrowser?: boolean;
79
+ }): Promise<PrivateClawInviteBundle> {
80
+ const tempDir = await mkdtemp(
81
+ path.join(os.tmpdir(), "privateclaw-pair-daemon-"),
82
+ );
83
+ const resultPath = path.join(tempDir, `${randomUUID()}.json`);
84
+
85
+ try {
86
+ const invocation = await resolveCliInvocation(params.cliModuleUrl);
87
+ const args = [
88
+ ...invocation.args,
89
+ "pair",
90
+ "--daemon-child",
91
+ "--result-file",
92
+ resultPath,
93
+ ...(typeof params.ttlMs === "number"
94
+ ? ["--ttl-ms", String(params.ttlMs)]
95
+ : []),
96
+ ...(params.label ? ["--label", params.label] : []),
97
+ ...(params.groupMode ? ["--group"] : []),
98
+ ...(params.openInBrowser ? ["--open"] : []),
99
+ ];
100
+
101
+ await new Promise<void>((resolve, reject) => {
102
+ const child = spawn(invocation.command, args, {
103
+ detached: true,
104
+ stdio: "ignore",
105
+ env: {
106
+ ...process.env,
107
+ ...params.env,
108
+ OPENCLAW_STATE_DIR: params.stateDir,
109
+ },
110
+ });
111
+ child.once("error", reject);
112
+ child.once("spawn", () => {
113
+ child.unref();
114
+ resolve();
115
+ });
116
+ });
117
+
118
+ const result = await waitForResultFile<PairDaemonResult>(resultPath, 30_000);
119
+ if (!result.ok) {
120
+ throw new Error(result.error);
121
+ }
122
+ return result.bundle;
123
+ } finally {
124
+ await rm(tempDir, { recursive: true, force: true });
125
+ }
126
+ }
127
+
128
+ export async function handoffForegroundPairToBackground(params: {
129
+ cliModuleUrl: string;
130
+ env?: NodeJS.ProcessEnv;
131
+ stateDir: string;
132
+ handoffState: PrivateClawProviderHandoffState;
133
+ }): Promise<number> {
134
+ const tempDir = await mkdtemp(
135
+ path.join(os.tmpdir(), "privateclaw-pair-handoff-"),
136
+ );
137
+ const resultPath = path.join(tempDir, `${randomUUID()}.json`);
138
+ const snapshotPath = path.join(tempDir, `${randomUUID()}.snapshot.json`);
139
+
140
+ try {
141
+ await writeFile(snapshotPath, JSON.stringify(params.handoffState), "utf8");
142
+ const invocation = await resolveCliInvocation(params.cliModuleUrl);
143
+ const args = [
144
+ ...invocation.args,
145
+ "pair",
146
+ "--daemon-child",
147
+ "--result-file",
148
+ resultPath,
149
+ "--resume-snapshot-file",
150
+ snapshotPath,
151
+ ];
152
+
153
+ await new Promise<void>((resolve, reject) => {
154
+ const child = spawn(invocation.command, args, {
155
+ detached: true,
156
+ stdio: "ignore",
157
+ env: {
158
+ ...process.env,
159
+ ...params.env,
160
+ OPENCLAW_STATE_DIR: params.stateDir,
161
+ },
162
+ });
163
+ child.once("error", reject);
164
+ child.once("spawn", () => {
165
+ child.unref();
166
+ resolve();
167
+ });
168
+ });
169
+
170
+ const result = await waitForResultFile<PairDaemonHandoffResult>(
171
+ resultPath,
172
+ 30_000,
173
+ );
174
+ if (!result.ok) {
175
+ throw new Error(result.error);
176
+ }
177
+ return result.resumedSessionCount;
178
+ } finally {
179
+ await rm(tempDir, { recursive: true, force: true });
180
+ }
181
+ }
@@ -6,11 +6,14 @@ import {
6
6
  writeInviteQrPreviewHtml,
7
7
  } from "./invite-qr-files.js";
8
8
  import {
9
+ buildPrivateClawBackgroundHandoffFailureMessage,
9
10
  buildPrivateClawShutdownMessage,
10
11
  formatBilingualInline,
11
12
  PRIVATECLAW_INVITE_URI_LABEL,
12
13
  PRIVATECLAW_QR_PNG_PATH_LABEL,
14
+ PRIVATECLAW_SESSION_ENDED_MESSAGE,
13
15
  PRIVATECLAW_WAITING_FOR_APP_MESSAGE,
16
+ PRIVATECLAW_WAITING_FOR_APP_WITH_BACKGROUND_MESSAGE,
14
17
  } from "./text.js";
15
18
  import type { PrivateClawInviteBundle } from "./types.js";
16
19
 
@@ -20,9 +23,11 @@ export interface PairSessionOptions {
20
23
  label?: string;
21
24
  groupMode?: boolean;
22
25
  printOnly?: boolean;
26
+ foreground?: boolean;
23
27
  openInBrowser?: boolean;
24
28
  qrMediaDir?: string;
25
29
  writeLine?: (line: string) => void;
30
+ handoffToBackground?: () => Promise<string | void>;
26
31
  }
27
32
 
28
33
  export function parsePositiveIntegerFlag(
@@ -66,17 +71,71 @@ async function waitForShutdownSignal(): Promise<NodeJS.Signals> {
66
71
  });
67
72
  }
68
73
 
74
+ async function waitForStdinEof(): Promise<void> {
75
+ if (!process.stdin.isTTY || process.stdin.destroyed) {
76
+ return new Promise<void>(() => undefined);
77
+ }
78
+
79
+ return new Promise((resolve) => {
80
+ const wasPaused = process.stdin.isPaused();
81
+ const handleEnd = () => {
82
+ cleanup();
83
+ resolve();
84
+ };
85
+ const handleClose = () => {
86
+ cleanup();
87
+ resolve();
88
+ };
89
+ const cleanup = () => {
90
+ process.stdin.off("end", handleEnd);
91
+ process.stdin.off("close", handleClose);
92
+ if (wasPaused && !process.stdin.destroyed) {
93
+ process.stdin.pause();
94
+ }
95
+ };
96
+
97
+ process.stdin.once("end", handleEnd);
98
+ process.stdin.once("close", handleClose);
99
+ if (wasPaused) {
100
+ process.stdin.resume();
101
+ }
102
+ });
103
+ }
104
+
105
+ async function waitForSessionsToDrain(
106
+ provider: PrivateClawProvider,
107
+ pollMs = 250,
108
+ ): Promise<void> {
109
+ while (provider.listActiveSessions().length > 0) {
110
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
111
+ }
112
+ }
113
+
114
+ export function printPairInviteBundle(
115
+ bundle: PrivateClawInviteBundle,
116
+ writeLine: (line: string) => void,
117
+ ): void {
118
+ writeLine(bundle.announcementText);
119
+ writeLine(`${PRIVATECLAW_INVITE_URI_LABEL}: ${bundle.inviteUri}`);
120
+ if (bundle.qrPngPath) {
121
+ writeLine(`${PRIVATECLAW_QR_PNG_PATH_LABEL}: ${bundle.qrPngPath}`);
122
+ }
123
+ writeLine(bundle.qrTerminal);
124
+ }
125
+
69
126
  export async function runPairSession({
70
127
  provider,
71
128
  ttlMs,
72
129
  label,
73
130
  groupMode = false,
74
131
  printOnly = false,
132
+ foreground = true,
75
133
  openInBrowser = false,
76
134
  qrMediaDir,
77
135
  writeLine = (line) => {
78
136
  console.log(line);
79
137
  },
138
+ handoffToBackground,
80
139
  }: PairSessionOptions): Promise<PrivateClawInviteBundle> {
81
140
  try {
82
141
  const inviteBundle = await provider.createInviteBundle({
@@ -93,10 +152,7 @@ export async function runPairSession({
93
152
  qrPngPath: qrPng.pngPath,
94
153
  };
95
154
 
96
- writeLine(bundle.announcementText);
97
- writeLine(`${PRIVATECLAW_INVITE_URI_LABEL}: ${bundle.inviteUri}`);
98
- writeLine(`${PRIVATECLAW_QR_PNG_PATH_LABEL}: ${qrPng.pngPath}`);
99
- writeLine(bundle.qrTerminal);
155
+ printPairInviteBundle(bundle, writeLine);
100
156
 
101
157
  if (openInBrowser) {
102
158
  const preview = await writeInviteQrPreviewHtml(
@@ -112,16 +168,53 @@ export async function runPairSession({
112
168
  return bundle;
113
169
  }
114
170
 
115
- writeLine(PRIVATECLAW_WAITING_FOR_APP_MESSAGE);
116
- process.stdin.resume();
117
- try {
118
- const signal = await waitForShutdownSignal();
119
- writeLine(buildPrivateClawShutdownMessage(signal));
120
- await provider.dispose();
171
+ if (!foreground) {
121
172
  return bundle;
122
- } finally {
123
- process.stdin.pause();
124
173
  }
174
+
175
+ writeLine(
176
+ handoffToBackground
177
+ ? PRIVATECLAW_WAITING_FOR_APP_WITH_BACKGROUND_MESSAGE
178
+ : PRIVATECLAW_WAITING_FOR_APP_MESSAGE,
179
+ );
180
+ for (;;) {
181
+ const outcome = await Promise.race<
182
+ | { kind: "signal"; signal: NodeJS.Signals }
183
+ | { kind: "session-ended" }
184
+ | { kind: "stdin-eof" }
185
+ >([
186
+ waitForShutdownSignal().then((signal) => ({ kind: "signal", signal })),
187
+ waitForSessionsToDrain(provider).then(() => ({ kind: "session-ended" })),
188
+ ...(handoffToBackground
189
+ ? [waitForStdinEof().then(() => ({ kind: "stdin-eof" as const }))]
190
+ : []),
191
+ ]);
192
+ if (outcome.kind === "stdin-eof") {
193
+ try {
194
+ const message = await handoffToBackground?.();
195
+ if (message) {
196
+ writeLine(message);
197
+ }
198
+ await provider.dispose({ closeSessions: false });
199
+ return bundle;
200
+ } catch (error) {
201
+ writeLine(
202
+ buildPrivateClawBackgroundHandoffFailureMessage(
203
+ error instanceof Error ? error.message : String(error),
204
+ ),
205
+ );
206
+ continue;
207
+ }
208
+ }
209
+ if (outcome.kind === "signal") {
210
+ writeLine(buildPrivateClawShutdownMessage(outcome.signal));
211
+ } else {
212
+ writeLine(PRIVATECLAW_SESSION_ENDED_MESSAGE);
213
+ }
214
+ break;
215
+ }
216
+ await provider.dispose();
217
+ return bundle;
125
218
  } catch (error) {
126
219
  await provider.dispose();
127
220
  throw error;
@@ -165,6 +165,7 @@ test("provider creates one-time invites and replies through the encrypted relay"
165
165
  const inviteBundle = await provider.createInviteBundle();
166
166
  const invite = decodeInviteString(inviteBundle.inviteUri);
167
167
  assert.equal(invite.sessionId, inviteBundle.invite.sessionId);
168
+ assert.equal(invite.relayLabel, `127.0.0.1:${port}`);
168
169
 
169
170
  const appSocket = new WebSocket(invite.appWsUrl);
170
171
  const attachedPromise = nextMessage(appSocket);
@@ -230,6 +231,112 @@ test("provider creates one-time invites and replies through the encrypted relay"
230
231
  await waitForClose(appSocket);
231
232
  });
232
233
 
234
+ test("provider can hand off an active session to a successor provider", async (t) => {
235
+ const relay = createRelayServer({
236
+ host: "127.0.0.1",
237
+ port: 0,
238
+ sessionTtlMs: 60_000,
239
+ frameCacheSize: 8,
240
+ });
241
+ const { port } = await relay.start();
242
+ t.after(async () => {
243
+ await relay.stop();
244
+ });
245
+
246
+ const providerOne = new PrivateClawProvider({
247
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
248
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
249
+ bridge: new EchoBridge("OpenClaw bridge"),
250
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
251
+ welcomeMessage: "欢迎来到 PrivateClaw",
252
+ });
253
+ await providerOne.connect();
254
+ let providerOneDisposed = false;
255
+ t.after(async () => {
256
+ if (!providerOneDisposed) {
257
+ await providerOne.dispose();
258
+ }
259
+ });
260
+
261
+ const inviteBundle = await providerOne.createInviteBundle();
262
+ const invite = decodeInviteString(inviteBundle.inviteUri);
263
+
264
+ const appUrl = new URL(invite.appWsUrl);
265
+ appUrl.searchParams.set("appId", "handoff-app");
266
+ const appSocket = new WebSocket(appUrl.toString());
267
+ const attachedPromise = nextMessage(appSocket);
268
+ await waitForOpen(appSocket);
269
+ assert.equal((await attachedPromise).type, "relay:attached");
270
+
271
+ appSocket.send(
272
+ JSON.stringify({
273
+ type: "app:frame",
274
+ envelope: encryptPayload({
275
+ sessionId: invite.sessionId,
276
+ sessionKey: invite.sessionKey,
277
+ payload: {
278
+ kind: "client_hello",
279
+ appId: "handoff-app",
280
+ displayName: "Handoff Tester",
281
+ appVersion: "flutter-test",
282
+ deviceLabel: "Simulator",
283
+ sentAt: new Date().toISOString(),
284
+ },
285
+ }),
286
+ }),
287
+ );
288
+ await nextMessages(appSocket, 2);
289
+
290
+ providerOne.suppressReconnectsForHandoff();
291
+ const handoffState = providerOne.exportHandoffState();
292
+ assert.equal(handoffState.sessions.length, 1);
293
+ assert.equal(handoffState.sessions[0]?.participants.length, 1);
294
+
295
+ const providerTwo = new PrivateClawProvider({
296
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
297
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
298
+ bridge: new EchoBridge("OpenClaw bridge"),
299
+ providerId: handoffState.providerId,
300
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
301
+ welcomeMessage: "欢迎来到 PrivateClaw",
302
+ });
303
+ providerTwo.importHandoffState(handoffState);
304
+ await providerTwo.connect();
305
+ t.after(async () => {
306
+ await providerTwo.dispose();
307
+ });
308
+
309
+ await providerOne.dispose({ closeSessions: false });
310
+ providerOneDisposed = true;
311
+
312
+ const resumedSession = providerTwo.listManagedSessions()[0];
313
+ assert.ok(resumedSession);
314
+ assert.equal(resumedSession?.participantCount, 1);
315
+
316
+ appSocket.send(
317
+ JSON.stringify({
318
+ type: "app:frame",
319
+ envelope: encryptPayload({
320
+ sessionId: invite.sessionId,
321
+ sessionKey: invite.sessionKey,
322
+ payload: {
323
+ kind: "user_message",
324
+ text: "after handoff",
325
+ clientMessageId: "client-message-handoff",
326
+ sentAt: new Date().toISOString(),
327
+ },
328
+ }),
329
+ }),
330
+ );
331
+
332
+ const assistant = await nextRelayPayload(appSocket, invite);
333
+ assert.equal(assistant.kind, "assistant_message");
334
+ assert.match(assistant.text, /after handoff/);
335
+
336
+ appSocket.close();
337
+ await waitForClose(appSocket);
338
+ });
339
+
233
340
  test("provider returns the current session QR only to the requesting participant", async (t) => {
234
341
  const relay = createRelayServer({
235
342
  host: "127.0.0.1",
@@ -354,6 +461,179 @@ test("provider returns the current session QR only to the requesting participant
354
461
  await Promise.all([waitForClose(appOne), waitForClose(appTwo)]);
355
462
  });
356
463
 
464
+ test("provider can remove a group participant and reject the same app id on rejoin", async (t) => {
465
+ const relay = createRelayServer({
466
+ host: "127.0.0.1",
467
+ port: 0,
468
+ sessionTtlMs: 60_000,
469
+ frameCacheSize: 8,
470
+ });
471
+ const { port } = await relay.start();
472
+ t.after(async () => {
473
+ await relay.stop();
474
+ });
475
+
476
+ const provider = new PrivateClawProvider({
477
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
478
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
479
+ bridge: new GroupBridge(),
480
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
481
+ });
482
+ await provider.connect();
483
+ t.after(async () => {
484
+ await provider.dispose();
485
+ });
486
+
487
+ const inviteBundle = await provider.createInviteBundle({ groupMode: true });
488
+ const invite = decodeInviteString(inviteBundle.inviteUri);
489
+
490
+ const appOneUrl = new URL(invite.appWsUrl);
491
+ appOneUrl.searchParams.set("appId", "app-one");
492
+ const appOne = new WebSocket(appOneUrl.toString());
493
+ const appOneAttached = nextMessage(appOne);
494
+ await waitForOpen(appOne);
495
+ assert.equal((await appOneAttached).type, "relay:attached");
496
+ const appOneInitialFrames = nextMessages(appOne, 3);
497
+ appOne.send(
498
+ JSON.stringify({
499
+ type: "app:frame",
500
+ envelope: encryptPayload({
501
+ sessionId: invite.sessionId,
502
+ sessionKey: invite.sessionKey,
503
+ payload: {
504
+ kind: "client_hello",
505
+ appId: "app-one",
506
+ displayName: "SolarFox",
507
+ appVersion: "flutter-test",
508
+ deviceLabel: "Tester One",
509
+ sentAt: new Date().toISOString(),
510
+ },
511
+ }),
512
+ }),
513
+ );
514
+ await appOneInitialFrames;
515
+
516
+ const appTwoUrl = new URL(invite.appWsUrl);
517
+ appTwoUrl.searchParams.set("appId", "app-two");
518
+ const appTwo = new WebSocket(appTwoUrl.toString());
519
+ const appTwoAttached = nextMessage(appTwo);
520
+ await waitForOpen(appTwo);
521
+ assert.equal((await appTwoAttached).type, "relay:attached");
522
+ const appTwoInitialFrames = nextMessages(appTwo, 3);
523
+ const appOneJoinFrames = nextMessages(appOne, 2);
524
+ appTwo.send(
525
+ JSON.stringify({
526
+ type: "app:frame",
527
+ envelope: encryptPayload({
528
+ sessionId: invite.sessionId,
529
+ sessionKey: invite.sessionKey,
530
+ payload: {
531
+ kind: "client_hello",
532
+ appId: "app-two",
533
+ displayName: "RiverCat",
534
+ appVersion: "flutter-test",
535
+ deviceLabel: "Tester Two",
536
+ sentAt: new Date().toISOString(),
537
+ },
538
+ }),
539
+ }),
540
+ );
541
+ await Promise.all([appTwoInitialFrames, appOneJoinFrames]);
542
+
543
+ const appOneKickFrames = nextMessages(appOne, 2);
544
+ const appTwoClosedMessage = new Promise<Record<string, unknown>>(
545
+ (resolve, reject) => {
546
+ const onMessage = (data: WebSocket.RawData) => {
547
+ const message = JSON.parse(data.toString()) as Record<string, unknown>;
548
+ if (message.type !== "relay:session_closed") {
549
+ return;
550
+ }
551
+ cleanup();
552
+ resolve(message);
553
+ };
554
+ const onError = (error: Error) => {
555
+ cleanup();
556
+ reject(error);
557
+ };
558
+ const cleanup = () => {
559
+ appTwo.off("message", onMessage);
560
+ appTwo.off("error", onError);
561
+ };
562
+ appTwo.on("message", onMessage);
563
+ appTwo.on("error", onError);
564
+ },
565
+ );
566
+ const kicked = await provider.kickGroupParticipant(invite.sessionId, "app-two");
567
+ assert.equal(kicked.appId, "app-two");
568
+ assert.equal(kicked.displayName, "RiverCat");
569
+
570
+ const closed = await appTwoClosedMessage;
571
+ assert.equal(closed.type, "relay:session_closed");
572
+ assert.equal(closed.reason, "participant_removed");
573
+ appTwo.close();
574
+ await waitForClose(appTwo);
575
+
576
+ const [kickNoticeFrame, capabilitiesFrame] = await appOneKickFrames;
577
+ const kickNotice = decryptRelayPayload(kickNoticeFrame!, invite);
578
+ assert.equal(kickNotice.kind, "system_message");
579
+ assert.match(kickNotice.message, /移出群聊|removed from the group chat/i);
580
+ const capabilities = decryptRelayPayload(capabilitiesFrame!, invite);
581
+ assert.equal(capabilities.kind, "provider_capabilities");
582
+ assert.equal(capabilities.participants?.length, 1);
583
+ assert.equal(capabilities.participants?.[0]?.appId, "app-one");
584
+
585
+ const appTwoReconnect = new WebSocket(appTwoUrl.toString());
586
+ const appTwoReconnectAttached = nextMessage(appTwoReconnect);
587
+ await waitForOpen(appTwoReconnect);
588
+ assert.equal((await appTwoReconnectAttached).type, "relay:attached");
589
+ const appTwoReconnectClosed = new Promise<Record<string, unknown>>(
590
+ (resolve, reject) => {
591
+ const onMessage = (data: WebSocket.RawData) => {
592
+ const message = JSON.parse(data.toString()) as Record<string, unknown>;
593
+ if (message.type !== "relay:session_closed") {
594
+ return;
595
+ }
596
+ cleanup();
597
+ resolve(message);
598
+ };
599
+ const onError = (error: Error) => {
600
+ cleanup();
601
+ reject(error);
602
+ };
603
+ const cleanup = () => {
604
+ appTwoReconnect.off("message", onMessage);
605
+ appTwoReconnect.off("error", onError);
606
+ };
607
+ appTwoReconnect.on("message", onMessage);
608
+ appTwoReconnect.on("error", onError);
609
+ },
610
+ );
611
+ appTwoReconnect.send(
612
+ JSON.stringify({
613
+ type: "app:frame",
614
+ envelope: encryptPayload({
615
+ sessionId: invite.sessionId,
616
+ sessionKey: invite.sessionKey,
617
+ payload: {
618
+ kind: "client_hello",
619
+ appId: "app-two",
620
+ displayName: "RiverCat",
621
+ appVersion: "flutter-test",
622
+ deviceLabel: "Tester Two",
623
+ sentAt: new Date().toISOString(),
624
+ },
625
+ }),
626
+ }),
627
+ );
628
+ const reconnectClosed = await appTwoReconnectClosed;
629
+ assert.equal(reconnectClosed.type, "relay:session_closed");
630
+ assert.equal(reconnectClosed.reason, "participant_removed");
631
+ await waitForClose(appTwoReconnect);
632
+
633
+ appOne.close();
634
+ await waitForClose(appOne);
635
+ });
636
+
357
637
  test("provider renews the session key and keeps the chat usable after re-handshake", async (t) => {
358
638
  const relay = createRelayServer({
359
639
  host: "127.0.0.1",