@privateclaw/privateclaw 0.1.24 → 0.1.26

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.
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
- import test from "node:test";
2
+ import test, { type TestContext } from "node:test";
3
3
  import {
4
4
  decodeInviteString,
5
5
  decryptPayload,
@@ -8,11 +8,35 @@ import {
8
8
  } from "@privateclaw/protocol";
9
9
  import WebSocket from "ws";
10
10
  import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
11
+ import { BOT_MODE_IDLE_TOPICS } from "./bot-mode-topics.js";
11
12
  import { EchoBridge } from "./bridges/echo-bridge.js";
12
13
  import { DEFAULT_SESSION_TTL_MS, PrivateClawProvider } from "./provider.js";
13
14
 
14
15
  const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
15
16
 
17
+ function createDeferred<T>() {
18
+ let resolve!: (value: T | PromiseLike<T>) => void;
19
+ let reject!: (reason?: unknown) => void;
20
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
21
+ resolve = resolvePromise;
22
+ reject = rejectPromise;
23
+ });
24
+ return { promise, resolve, reject };
25
+ }
26
+
27
+ async function waitForCondition(
28
+ predicate: () => boolean,
29
+ timeoutMs = 500,
30
+ ): Promise<void> {
31
+ const startedAt = Date.now();
32
+ while (!predicate()) {
33
+ if (Date.now() - startedAt > timeoutMs) {
34
+ throw new Error(`condition not met within ${timeoutMs}ms`);
35
+ }
36
+ await new Promise((resolve) => setTimeout(resolve, 5));
37
+ }
38
+ }
39
+
16
40
  function waitForOpen(socket: WebSocket): Promise<void> {
17
41
  return new Promise((resolve, reject) => {
18
42
  socket.once("open", () => resolve());
@@ -115,6 +139,76 @@ async function nextRelayPayload(
115
139
  });
116
140
  }
117
141
 
142
+ async function connectGroupApp(params: {
143
+ invite: ReturnType<typeof decodeInviteString>;
144
+ appId: string;
145
+ displayName: string;
146
+ deviceLabel?: string;
147
+ expectedFrameCount?: number;
148
+ }): Promise<WebSocket> {
149
+ const appUrl = new URL(params.invite.appWsUrl);
150
+ appUrl.searchParams.set("appId", params.appId);
151
+ const socket = new WebSocket(appUrl.toString());
152
+ const attached = nextMessage(socket);
153
+ await waitForOpen(socket);
154
+ assert.equal((await attached).type, "relay:attached");
155
+ const initialFrames = nextMessages(socket, params.expectedFrameCount ?? 3);
156
+ socket.send(
157
+ JSON.stringify({
158
+ type: "app:frame",
159
+ envelope: encryptPayload({
160
+ sessionId: params.invite.sessionId,
161
+ sessionKey: params.invite.sessionKey,
162
+ payload: {
163
+ kind: "client_hello",
164
+ appId: params.appId,
165
+ displayName: params.displayName,
166
+ appVersion: "flutter-test",
167
+ deviceLabel: params.deviceLabel ?? `${params.displayName} device`,
168
+ sentAt: new Date().toISOString(),
169
+ },
170
+ }),
171
+ }),
172
+ );
173
+ await initialFrames;
174
+ return socket;
175
+ }
176
+
177
+ async function createGroupBotModeHarness(
178
+ t: TestContext,
179
+ bridge: { handleUserMessage(params: { message: string }): Promise<string> },
180
+ providerOptions?: Partial<ConstructorParameters<typeof PrivateClawProvider>[0]>,
181
+ ): Promise<{ invite: ReturnType<typeof decodeInviteString>; provider: PrivateClawProvider }> {
182
+ const relay = createRelayServer({
183
+ host: "127.0.0.1",
184
+ port: 0,
185
+ sessionTtlMs: 60_000,
186
+ frameCacheSize: 8,
187
+ });
188
+ const { port } = await relay.start();
189
+ t.after(async () => {
190
+ await relay.stop();
191
+ });
192
+
193
+ const provider = new PrivateClawProvider({
194
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
195
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
196
+ bridge,
197
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
198
+ ...providerOptions,
199
+ });
200
+ await provider.connect();
201
+ t.after(async () => {
202
+ await provider.dispose();
203
+ });
204
+
205
+ const inviteBundle = await provider.createInviteBundle({ groupMode: true });
206
+ return {
207
+ provider,
208
+ invite: decodeInviteString(inviteBundle.inviteUri),
209
+ };
210
+ }
211
+
118
212
  function decryptRelayPayload(
119
213
  frame: Record<string, unknown>,
120
214
  params: { sessionId: string; sessionKey: string },
@@ -157,6 +251,73 @@ class HistoryRecordingBridge {
157
251
  }
158
252
  }
159
253
 
254
+ class BotModeBridge {
255
+ readonly prompts: string[] = [];
256
+ readonly promptKinds: Array<"silent_join" | "idle_group" | "user"> = [];
257
+
258
+ async handleUserMessage(params: {
259
+ message: string;
260
+ }): Promise<string> {
261
+ this.prompts.push(params.message);
262
+ if (params.message.includes("joined this PrivateClaw group chat")) {
263
+ this.promptKinds.push("silent_join");
264
+ return "Bot mode hello";
265
+ }
266
+ if (params.message.includes("has had no new message")) {
267
+ this.promptKinds.push("idle_group");
268
+ return "Bot mode joke";
269
+ }
270
+ this.promptKinds.push("user");
271
+ return `OpenClaw bridge: ${params.message}`;
272
+ }
273
+ }
274
+
275
+ class NoReplyThenJokeBridge {
276
+ readonly prompts: string[] = [];
277
+
278
+ async handleUserMessage(params: {
279
+ message: string;
280
+ }): Promise<string> {
281
+ this.prompts.push(params.message);
282
+ return params.message.includes("\"NO_REPLY\"") ? "Fallback joke" : "NO_REPLY";
283
+ }
284
+ }
285
+
286
+ class ControlledQueueBridge {
287
+ readonly calls: Array<{
288
+ message: string;
289
+ deferred: ReturnType<typeof createDeferred<string>>;
290
+ }> = [];
291
+ maxConcurrentCalls = 0;
292
+ private activeCalls = 0;
293
+
294
+ async handleUserMessage(params: {
295
+ message: string;
296
+ }): Promise<string> {
297
+ const deferred = createDeferred<string>();
298
+ this.calls.push({
299
+ message: params.message,
300
+ deferred,
301
+ });
302
+ this.activeCalls += 1;
303
+ this.maxConcurrentCalls = Math.max(
304
+ this.maxConcurrentCalls,
305
+ this.activeCalls,
306
+ );
307
+ try {
308
+ return await deferred.promise;
309
+ } finally {
310
+ this.activeCalls -= 1;
311
+ }
312
+ }
313
+
314
+ resolveCall(index: number, response: string): void {
315
+ const call = this.calls[index];
316
+ assert.ok(call, `expected bridge call ${index}`);
317
+ call.deferred.resolve(response);
318
+ }
319
+ }
320
+
160
321
  class ThinkingTraceBridge {
161
322
  readonly supportsThinkingTrace = true;
162
323
  readonly conversationMessages: string[] = [];
@@ -370,6 +531,198 @@ test("provider creates one-time invites and replies through the encrypted relay"
370
531
  appSocket.terminate();
371
532
  });
372
533
 
534
+ test("provider turns a NO_REPLY bridge response into a fallback joke", async (t) => {
535
+ const relay = createRelayServer({
536
+ host: "127.0.0.1",
537
+ port: 0,
538
+ sessionTtlMs: 60_000,
539
+ frameCacheSize: 8,
540
+ });
541
+ const { port } = await relay.start();
542
+ t.after(async () => {
543
+ await relay.stop();
544
+ });
545
+
546
+ const bridge = new NoReplyThenJokeBridge();
547
+ const provider = new PrivateClawProvider({
548
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
549
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
550
+ bridge,
551
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
552
+ welcomeMessage: "欢迎来到 PrivateClaw",
553
+ });
554
+ await provider.connect();
555
+ t.after(async () => {
556
+ await provider.dispose();
557
+ });
558
+
559
+ const inviteBundle = await provider.createInviteBundle();
560
+ const invite = decodeInviteString(inviteBundle.inviteUri);
561
+
562
+ const appSocket = new WebSocket(invite.appWsUrl);
563
+ const attachedPromise = nextMessage(appSocket);
564
+ await waitForOpen(appSocket);
565
+ assert.equal((await attachedPromise).type, "relay:attached");
566
+
567
+ appSocket.send(
568
+ JSON.stringify({
569
+ type: "app:frame",
570
+ envelope: encryptPayload({
571
+ sessionId: invite.sessionId,
572
+ sessionKey: invite.sessionKey,
573
+ payload: {
574
+ kind: "client_hello",
575
+ appVersion: "flutter-test",
576
+ deviceLabel: "Simulator",
577
+ sentAt: new Date().toISOString(),
578
+ },
579
+ }),
580
+ }),
581
+ );
582
+ await nextMessages(appSocket, 2);
583
+
584
+ appSocket.send(
585
+ JSON.stringify({
586
+ type: "app:frame",
587
+ envelope: encryptPayload({
588
+ sessionId: invite.sessionId,
589
+ sessionKey: invite.sessionKey,
590
+ payload: {
591
+ kind: "user_message",
592
+ text: "你好",
593
+ clientMessageId: "no-reply-user-1",
594
+ sentAt: new Date().toISOString(),
595
+ },
596
+ }),
597
+ }),
598
+ );
599
+
600
+ const assistant = await nextRelayPayload(appSocket, invite);
601
+ assert.equal(assistant.kind, "assistant_message");
602
+ assert.equal(assistant.replyTo, "no-reply-user-1");
603
+ assert.equal(assistant.text, "Fallback joke");
604
+ assert.equal(bridge.prompts[0], "你好");
605
+ assert.equal(bridge.prompts.length, 2);
606
+ assert.match(
607
+ bridge.prompts[1] ?? "",
608
+ /Your previous assistant reply for this turn was exactly "NO_REPLY"\./u,
609
+ );
610
+ assert.match(
611
+ bridge.prompts[1] ?? "",
612
+ /same language as the recent user\/assistant conversation already in this session/u,
613
+ );
614
+
615
+ appSocket.terminate();
616
+ });
617
+
618
+ test("provider serializes bridge turns per session", async (t) => {
619
+ const relay = createRelayServer({
620
+ host: "127.0.0.1",
621
+ port: 0,
622
+ sessionTtlMs: 60_000,
623
+ frameCacheSize: 8,
624
+ });
625
+ const { port } = await relay.start();
626
+ t.after(async () => {
627
+ await relay.stop();
628
+ });
629
+
630
+ const bridge = new ControlledQueueBridge();
631
+ const provider = new PrivateClawProvider({
632
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
633
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
634
+ bridge,
635
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
636
+ welcomeMessage: "欢迎来到 PrivateClaw",
637
+ });
638
+ await provider.connect();
639
+ t.after(async () => {
640
+ await provider.dispose();
641
+ });
642
+
643
+ const inviteBundle = await provider.createInviteBundle();
644
+ const invite = decodeInviteString(inviteBundle.inviteUri);
645
+
646
+ const appSocket = new WebSocket(invite.appWsUrl);
647
+ const attachedPromise = nextMessage(appSocket);
648
+ await waitForOpen(appSocket);
649
+ assert.equal((await attachedPromise).type, "relay:attached");
650
+
651
+ appSocket.send(
652
+ JSON.stringify({
653
+ type: "app:frame",
654
+ envelope: encryptPayload({
655
+ sessionId: invite.sessionId,
656
+ sessionKey: invite.sessionKey,
657
+ payload: {
658
+ kind: "client_hello",
659
+ appVersion: "flutter-test",
660
+ deviceLabel: "Simulator",
661
+ sentAt: new Date().toISOString(),
662
+ },
663
+ }),
664
+ }),
665
+ );
666
+ await nextMessages(appSocket, 2);
667
+
668
+ appSocket.send(
669
+ JSON.stringify({
670
+ type: "app:frame",
671
+ envelope: encryptPayload({
672
+ sessionId: invite.sessionId,
673
+ sessionKey: invite.sessionKey,
674
+ payload: {
675
+ kind: "user_message",
676
+ text: "first queued message",
677
+ clientMessageId: "queued-message-1",
678
+ sentAt: new Date().toISOString(),
679
+ },
680
+ }),
681
+ }),
682
+ );
683
+ await waitForCondition(() => bridge.calls.length === 1);
684
+
685
+ appSocket.send(
686
+ JSON.stringify({
687
+ type: "app:frame",
688
+ envelope: encryptPayload({
689
+ sessionId: invite.sessionId,
690
+ sessionKey: invite.sessionKey,
691
+ payload: {
692
+ kind: "user_message",
693
+ text: "second queued message",
694
+ clientMessageId: "queued-message-2",
695
+ sentAt: new Date().toISOString(),
696
+ },
697
+ }),
698
+ }),
699
+ );
700
+ await new Promise((resolve) => setTimeout(resolve, 80));
701
+ assert.equal(bridge.calls.length, 1);
702
+ assert.equal(bridge.maxConcurrentCalls, 1);
703
+ assert.equal(bridge.calls[0]?.message, "first queued message");
704
+
705
+ const firstAssistantPromise = nextRelayPayload(appSocket, invite);
706
+ bridge.resolveCall(0, "First queued reply");
707
+ const firstAssistant = await firstAssistantPromise;
708
+ assert.equal(firstAssistant.kind, "assistant_message");
709
+ assert.equal(firstAssistant.replyTo, "queued-message-1");
710
+ assert.equal(firstAssistant.text, "First queued reply");
711
+
712
+ await waitForCondition(() => bridge.calls.length === 2);
713
+ assert.equal(bridge.calls[1]?.message, "second queued message");
714
+ assert.equal(bridge.maxConcurrentCalls, 1);
715
+
716
+ const secondAssistantPromise = nextRelayPayload(appSocket, invite);
717
+ bridge.resolveCall(1, "Second queued reply");
718
+ const secondAssistant = await secondAssistantPromise;
719
+ assert.equal(secondAssistant.kind, "assistant_message");
720
+ assert.equal(secondAssistant.replyTo, "queued-message-2");
721
+ assert.equal(secondAssistant.text, "Second queued reply");
722
+
723
+ appSocket.terminate();
724
+ });
725
+
373
726
  test("provider emits verbose session logs when enabled", async (t) => {
374
727
  const relay = createRelayServer({
375
728
  host: "127.0.0.1",
@@ -2155,6 +2508,446 @@ test("group sessions can mute and unmute bot replies without stopping participan
2155
2508
  await Promise.all([waitForClose(appOne), waitForClose(appTwo)]);
2156
2509
  });
2157
2510
 
2511
+ test("group bot mode stays quiet when disabled", async (t) => {
2512
+ const bridge = new BotModeBridge();
2513
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2514
+ botMode: false,
2515
+ botModeSilentJoinDelayMs: 30,
2516
+ botModeIdleDelayMs: 30,
2517
+ });
2518
+ const app = await connectGroupApp({
2519
+ invite,
2520
+ appId: "app-one",
2521
+ displayName: "SolarFox",
2522
+ });
2523
+ t.after(async () => {
2524
+ app.close();
2525
+ await waitForClose(app);
2526
+ });
2527
+
2528
+ await waitForNoMessage(app, 120);
2529
+ assert.deepEqual(bridge.promptKinds, []);
2530
+ });
2531
+
2532
+ test("group bot mode greets a silent participant after the configured join delay", async (t) => {
2533
+ const bridge = new BotModeBridge();
2534
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2535
+ botMode: true,
2536
+ botModeSilentJoinDelayMs: 40,
2537
+ botModeIdleDelayMs: 250,
2538
+ });
2539
+ const app = await connectGroupApp({
2540
+ invite,
2541
+ appId: "app-one",
2542
+ displayName: "SolarFox",
2543
+ });
2544
+ t.after(async () => {
2545
+ app.close();
2546
+ await waitForClose(app);
2547
+ });
2548
+
2549
+ const proactive = await nextRelayPayload(app, invite);
2550
+ assert.equal(proactive.kind, "assistant_message");
2551
+ assert.equal(proactive.text, "Bot mode hello");
2552
+ assert.deepEqual(bridge.promptKinds, ["silent_join"]);
2553
+ assert.match(bridge.prompts[0]!, /SolarFox/u);
2554
+ assert.match(bridge.prompts[0]!, /has not sent any message yet/u);
2555
+ assert.doesNotMatch(
2556
+ bridge.prompts[0]!,
2557
+ /write the proactive message in English/u,
2558
+ );
2559
+ await waitForNoMessage(app, 120);
2560
+ });
2561
+
2562
+ test("group bot mode turns a NO_REPLY proactive prompt into a fallback joke", async (t) => {
2563
+ const bridge = new NoReplyThenJokeBridge();
2564
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2565
+ botMode: true,
2566
+ botModeSilentJoinDelayMs: 40,
2567
+ botModeIdleDelayMs: 250,
2568
+ });
2569
+ const app = await connectGroupApp({
2570
+ invite,
2571
+ appId: "app-one",
2572
+ displayName: "SolarFox",
2573
+ });
2574
+ t.after(async () => {
2575
+ app.close();
2576
+ await waitForClose(app);
2577
+ });
2578
+
2579
+ const proactive = await nextRelayPayload(app, invite);
2580
+ assert.equal(proactive.kind, "assistant_message");
2581
+ assert.equal(proactive.text, "Fallback joke");
2582
+ assert.equal(bridge.prompts.length, 2);
2583
+ assert.match(bridge.prompts[0] ?? "", /joined this PrivateClaw group chat/u);
2584
+ assert.match(
2585
+ bridge.prompts[1] ?? "",
2586
+ /Your previous assistant reply for this turn was exactly "NO_REPLY"\./u,
2587
+ );
2588
+ });
2589
+
2590
+ test("group bot mode cancels the silent-join greeting after the participant speaks", async (t) => {
2591
+ const bridge = new BotModeBridge();
2592
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2593
+ botMode: true,
2594
+ botModeSilentJoinDelayMs: 80,
2595
+ botModeIdleDelayMs: 250,
2596
+ });
2597
+ const app = await connectGroupApp({
2598
+ invite,
2599
+ appId: "app-one",
2600
+ displayName: "SolarFox",
2601
+ });
2602
+ t.after(async () => {
2603
+ app.close();
2604
+ await waitForClose(app);
2605
+ });
2606
+
2607
+ const replyFramesPromise = nextMessages(app, 2);
2608
+ app.send(
2609
+ JSON.stringify({
2610
+ type: "app:frame",
2611
+ envelope: encryptPayload({
2612
+ sessionId: invite.sessionId,
2613
+ sessionKey: invite.sessionKey,
2614
+ payload: {
2615
+ kind: "user_message",
2616
+ appId: "app-one",
2617
+ text: "hello there",
2618
+ clientMessageId: "bot-mode-user-1",
2619
+ sentAt: new Date().toISOString(),
2620
+ },
2621
+ }),
2622
+ }),
2623
+ );
2624
+
2625
+ const replyFrames = await replyFramesPromise;
2626
+ const participantEcho = decryptRelayPayload(replyFrames[0]!, invite);
2627
+ const assistantReply = decryptRelayPayload(replyFrames[1]!, invite);
2628
+ assert.equal(participantEcho.kind, "participant_message");
2629
+ assert.equal(assistantReply.kind, "assistant_message");
2630
+ assert.deepEqual(bridge.promptKinds, ["user"]);
2631
+ await waitForNoMessage(app, 140);
2632
+ });
2633
+
2634
+ test("group bot mode sends an idle follow-up after the room stays quiet", async (t) => {
2635
+ const bridge = new BotModeBridge();
2636
+ const { invite, provider } = await createGroupBotModeHarness(t, bridge, {
2637
+ botMode: true,
2638
+ botModeSilentJoinDelayMs: 250,
2639
+ botModeIdleDelayMs: 60,
2640
+ });
2641
+ const app = await connectGroupApp({
2642
+ invite,
2643
+ appId: "app-one",
2644
+ displayName: "SolarFox",
2645
+ });
2646
+ t.after(async () => {
2647
+ app.close();
2648
+ await waitForClose(app);
2649
+ });
2650
+
2651
+ const replyFramesPromise = nextMessages(app, 2);
2652
+ app.send(
2653
+ JSON.stringify({
2654
+ type: "app:frame",
2655
+ envelope: encryptPayload({
2656
+ sessionId: invite.sessionId,
2657
+ sessionKey: invite.sessionKey,
2658
+ payload: {
2659
+ kind: "user_message",
2660
+ appId: "app-one",
2661
+ text: "keep this in mind",
2662
+ clientMessageId: "bot-mode-user-2",
2663
+ sentAt: new Date().toISOString(),
2664
+ },
2665
+ }),
2666
+ }),
2667
+ );
2668
+ const replyFrames = await replyFramesPromise;
2669
+ assert.equal(decryptRelayPayload(replyFrames[0]!, invite).kind, "participant_message");
2670
+ assert.equal(decryptRelayPayload(replyFrames[1]!, invite).kind, "assistant_message");
2671
+
2672
+ const idleFollowUp = await nextRelayPayload(app, invite);
2673
+ assert.equal(idleFollowUp.kind, "assistant_message");
2674
+ assert.equal(idleFollowUp.text, "Bot mode joke");
2675
+ assert.deepEqual(bridge.promptKinds, ["user", "idle_group"]);
2676
+ assert.match(bridge.prompts[1]!, /has had no new message/u);
2677
+ assert.match(bridge.prompts[1]!, /Idle topic:/u);
2678
+ assert.match(bridge.prompts[1]!, /Topic prompt:/u);
2679
+ assert.match(
2680
+ bridge.prompts[1]!,
2681
+ /Write the proactive message in the same language as the recent user\/assistant conversation already in this session\./u,
2682
+ );
2683
+ const sessionState = (provider as unknown as { sessions: Map<string, { botModeLastIdleTopicId?: string }> }).sessions.get(
2684
+ invite.sessionId,
2685
+ );
2686
+ assert.ok(sessionState?.botModeLastIdleTopicId);
2687
+ assert.ok(
2688
+ BOT_MODE_IDLE_TOPICS.some(
2689
+ (topic) => topic.id === sessionState.botModeLastIdleTopicId,
2690
+ ),
2691
+ );
2692
+ });
2693
+
2694
+ test("group bot mode proactive turns wait for the session bridge queue", async (t) => {
2695
+ const bridge = new ControlledQueueBridge();
2696
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2697
+ botMode: true,
2698
+ botModeSilentJoinDelayMs: 250,
2699
+ botModeIdleDelayMs: 60,
2700
+ });
2701
+ const app = await connectGroupApp({
2702
+ invite,
2703
+ appId: "app-one",
2704
+ displayName: "SolarFox",
2705
+ });
2706
+ t.after(async () => {
2707
+ app.close();
2708
+ await waitForClose(app);
2709
+ });
2710
+
2711
+ const participantEchoPromise = nextRelayPayload(app, invite);
2712
+ app.send(
2713
+ JSON.stringify({
2714
+ type: "app:frame",
2715
+ envelope: encryptPayload({
2716
+ sessionId: invite.sessionId,
2717
+ sessionKey: invite.sessionKey,
2718
+ payload: {
2719
+ kind: "user_message",
2720
+ appId: "app-one",
2721
+ text: "queue this turn first",
2722
+ clientMessageId: "queued-bot-mode-user-1",
2723
+ sentAt: new Date().toISOString(),
2724
+ },
2725
+ }),
2726
+ }),
2727
+ );
2728
+
2729
+ const participantEcho = await participantEchoPromise;
2730
+ assert.equal(participantEcho.kind, "participant_message");
2731
+ await waitForCondition(() => bridge.calls.length === 1);
2732
+ assert.equal(bridge.calls[0]?.message, "SolarFox: queue this turn first");
2733
+
2734
+ await new Promise((resolve) => setTimeout(resolve, 90));
2735
+ assert.equal(
2736
+ bridge.calls.length,
2737
+ 1,
2738
+ "idle bot-mode prompt should wait behind the queued user turn",
2739
+ );
2740
+ assert.equal(bridge.maxConcurrentCalls, 1);
2741
+
2742
+ const assistantReplyPromise = nextRelayPayload(app, invite);
2743
+ bridge.resolveCall(0, "Queued user reply");
2744
+ const assistantReply = await assistantReplyPromise;
2745
+ assert.equal(assistantReply.kind, "assistant_message");
2746
+ assert.equal(assistantReply.replyTo, "queued-bot-mode-user-1");
2747
+ assert.equal(assistantReply.text, "Queued user reply");
2748
+
2749
+ await waitForCondition(() => bridge.calls.length === 2);
2750
+ assert.match(bridge.calls[1]?.message ?? "", /has had no new message/u);
2751
+ assert.equal(bridge.maxConcurrentCalls, 1);
2752
+
2753
+ const proactiveReplyPromise = nextRelayPayload(app, invite);
2754
+ bridge.resolveCall(1, "Queued bot joke");
2755
+ const proactiveReply = await proactiveReplyPromise;
2756
+ assert.equal(proactiveReply.kind, "assistant_message");
2757
+ assert.equal(proactiveReply.text, "Queued bot joke");
2758
+ });
2759
+
2760
+ test("group bot mode idle timing ignores non-human assistant broadcasts", async (t) => {
2761
+ const bridge = new BotModeBridge();
2762
+ const { invite, provider } = await createGroupBotModeHarness(t, bridge, {
2763
+ botMode: true,
2764
+ botModeSilentJoinDelayMs: 250,
2765
+ botModeIdleDelayMs: 160,
2766
+ });
2767
+ const app = await connectGroupApp({
2768
+ invite,
2769
+ appId: "app-one",
2770
+ displayName: "SolarFox",
2771
+ });
2772
+ t.after(async () => {
2773
+ app.close();
2774
+ await waitForClose(app);
2775
+ });
2776
+
2777
+ const replyFramesPromise = nextMessages(app, 2);
2778
+ app.send(
2779
+ JSON.stringify({
2780
+ type: "app:frame",
2781
+ envelope: encryptPayload({
2782
+ sessionId: invite.sessionId,
2783
+ sessionKey: invite.sessionKey,
2784
+ payload: {
2785
+ kind: "user_message",
2786
+ appId: "app-one",
2787
+ text: "keep the room warm",
2788
+ clientMessageId: "bot-mode-user-3",
2789
+ sentAt: new Date().toISOString(),
2790
+ },
2791
+ }),
2792
+ }),
2793
+ );
2794
+ await replyFramesPromise;
2795
+
2796
+ await new Promise((resolve) => setTimeout(resolve, 110));
2797
+ const qrPayloadPromise = nextRelayPayload(app, invite);
2798
+ await provider.getSessionQrBundle(invite.sessionId, { notifyParticipants: true });
2799
+ const qrPayload = await qrPayloadPromise;
2800
+ assert.equal(qrPayload.kind, "assistant_message");
2801
+
2802
+ const idleWaitStartedAt = Date.now();
2803
+ const idleFollowUp = await nextRelayPayload(app, invite);
2804
+ const idleElapsedMs = Date.now() - idleWaitStartedAt;
2805
+ assert.equal(idleFollowUp.kind, "assistant_message");
2806
+ assert.equal(idleFollowUp.text, "Bot mode joke");
2807
+ assert.ok(
2808
+ idleElapsedMs < 120,
2809
+ `expected idle follow-up without assistant reset, waited ${idleElapsedMs}ms`,
2810
+ );
2811
+ });
2812
+
2813
+ test("group bot mode idle timing ignores participant joins", async (t) => {
2814
+ const bridge = new BotModeBridge();
2815
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2816
+ botMode: true,
2817
+ botModeSilentJoinDelayMs: 250,
2818
+ botModeIdleDelayMs: 160,
2819
+ });
2820
+ const appOne = await connectGroupApp({
2821
+ invite,
2822
+ appId: "app-one",
2823
+ displayName: "SolarFox",
2824
+ });
2825
+ let appTwo: WebSocket | undefined;
2826
+ t.after(async () => {
2827
+ appOne.close();
2828
+ if (appTwo) {
2829
+ appTwo.close();
2830
+ }
2831
+ await Promise.all([
2832
+ waitForClose(appOne),
2833
+ ...(appTwo ? [waitForClose(appTwo)] : []),
2834
+ ]);
2835
+ });
2836
+
2837
+ const replyFramesPromise = nextMessages(appOne, 2);
2838
+ appOne.send(
2839
+ JSON.stringify({
2840
+ type: "app:frame",
2841
+ envelope: encryptPayload({
2842
+ sessionId: invite.sessionId,
2843
+ sessionKey: invite.sessionKey,
2844
+ payload: {
2845
+ kind: "user_message",
2846
+ appId: "app-one",
2847
+ text: "staying active",
2848
+ clientMessageId: "bot-mode-user-4",
2849
+ sentAt: new Date().toISOString(),
2850
+ },
2851
+ }),
2852
+ }),
2853
+ );
2854
+ await replyFramesPromise;
2855
+
2856
+ await new Promise((resolve) => setTimeout(resolve, 110));
2857
+ const joinFramesPromise = nextMessages(appOne, 2);
2858
+ appTwo = await connectGroupApp({
2859
+ invite,
2860
+ appId: "app-two",
2861
+ displayName: "RiverCat",
2862
+ expectedFrameCount: 5,
2863
+ });
2864
+ await joinFramesPromise;
2865
+
2866
+ const idleWaitStartedAt = Date.now();
2867
+ const idleFollowUp = await nextRelayPayload(appOne, invite);
2868
+ const idleElapsedMs = Date.now() - idleWaitStartedAt;
2869
+ assert.equal(idleFollowUp.kind, "assistant_message");
2870
+ assert.equal(idleFollowUp.text, "Bot mode joke");
2871
+ assert.ok(
2872
+ idleElapsedMs < 120,
2873
+ `expected idle follow-up without join reset, waited ${idleElapsedMs}ms`,
2874
+ );
2875
+ });
2876
+
2877
+ test("group bot mode respects /mute-bot and suppresses proactive replies", async (t) => {
2878
+ const bridge = new BotModeBridge();
2879
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2880
+ botMode: true,
2881
+ botModeSilentJoinDelayMs: 50,
2882
+ botModeIdleDelayMs: 70,
2883
+ });
2884
+ const app = await connectGroupApp({
2885
+ invite,
2886
+ appId: "app-one",
2887
+ displayName: "SolarFox",
2888
+ });
2889
+ t.after(async () => {
2890
+ app.close();
2891
+ await waitForClose(app);
2892
+ });
2893
+
2894
+ const muteFramesPromise = nextMessages(app, 2);
2895
+ app.send(
2896
+ JSON.stringify({
2897
+ type: "app:frame",
2898
+ envelope: encryptPayload({
2899
+ sessionId: invite.sessionId,
2900
+ sessionKey: invite.sessionKey,
2901
+ payload: {
2902
+ kind: "user_message",
2903
+ appId: "app-one",
2904
+ text: "/mute-bot",
2905
+ clientMessageId: "bot-mode-mute-1",
2906
+ sentAt: new Date().toISOString(),
2907
+ },
2908
+ }),
2909
+ }),
2910
+ );
2911
+ await muteFramesPromise;
2912
+
2913
+ await waitForNoMessage(app, 150);
2914
+ assert.deepEqual(bridge.promptKinds, []);
2915
+ });
2916
+
2917
+ test("group bot mode does not greet the same silent participant twice after reconnect", async (t) => {
2918
+ const bridge = new BotModeBridge();
2919
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2920
+ botMode: true,
2921
+ botModeSilentJoinDelayMs: 40,
2922
+ botModeIdleDelayMs: 250,
2923
+ });
2924
+ const app = await connectGroupApp({
2925
+ invite,
2926
+ appId: "app-one",
2927
+ displayName: "SolarFox",
2928
+ });
2929
+
2930
+ const proactive = await nextRelayPayload(app, invite);
2931
+ assert.equal(proactive.kind, "assistant_message");
2932
+ assert.equal(proactive.text, "Bot mode hello");
2933
+ app.close();
2934
+ await waitForClose(app);
2935
+
2936
+ const reconnect = await connectGroupApp({
2937
+ invite,
2938
+ appId: "app-one",
2939
+ displayName: "SolarFox",
2940
+ expectedFrameCount: 4,
2941
+ });
2942
+ t.after(async () => {
2943
+ reconnect.close();
2944
+ await waitForClose(reconnect);
2945
+ });
2946
+
2947
+ await waitForNoMessage(reconnect, 120);
2948
+ assert.deepEqual(bridge.promptKinds, ["silent_join"]);
2949
+ });
2950
+
2158
2951
  test("provider forwards unknown slash commands verbatim to the bridge even when bot replies are muted", async (t) => {
2159
2952
  const relay = createRelayServer({
2160
2953
  host: "127.0.0.1",