@privateclaw/privateclaw 0.1.34 → 0.1.36

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.
@@ -39,7 +39,7 @@ interface OpenClawCommandRuntime {
39
39
  listSkillCommandsForAgents?: (
40
40
  config: unknown,
41
41
  ) => OpenClawSkillCommandSpecLike[];
42
- getPluginCommandSpecs: (provider?: string) => OpenClawPluginCommandSpecLike[];
42
+ getPluginCommandSpecs?: (provider?: string) => OpenClawPluginCommandSpecLike[];
43
43
  }
44
44
 
45
45
  let cachedRuntimePromise: Promise<OpenClawCommandRuntime | null> | undefined;
@@ -231,6 +231,10 @@ function findExportedFunction<T extends (...args: never[]) => unknown>(
231
231
  module: Record<string, unknown>,
232
232
  functionName: string,
233
233
  ): T | null {
234
+ const direct = module[functionName];
235
+ if (typeof direct === "function") {
236
+ return direct as T;
237
+ }
234
238
  for (const exported of Object.values(module)) {
235
239
  if (typeof exported === "function" && exported.name === functionName) {
236
240
  return exported as T;
@@ -239,6 +243,90 @@ function findExportedFunction<T extends (...args: never[]) => unknown>(
239
243
  return null;
240
244
  }
241
245
 
246
+ function findExportedFunctionInModules<T extends (...args: never[]) => unknown>(
247
+ modules: ReadonlyArray<Record<string, unknown>>,
248
+ functionName: string,
249
+ ): T | null {
250
+ for (const module of modules) {
251
+ const resolved = findExportedFunction<T>(module, functionName);
252
+ if (resolved) {
253
+ return resolved;
254
+ }
255
+ }
256
+ return null;
257
+ }
258
+
259
+ function dedupePaths(paths: ReadonlyArray<string | null | undefined>): string[] {
260
+ const unique = new Set<string>();
261
+ for (const candidate of paths) {
262
+ if (candidate) {
263
+ unique.add(candidate);
264
+ }
265
+ }
266
+ return [...unique];
267
+ }
268
+
269
+ async function resolveCommandDiscoveryModulePaths(
270
+ distDir: string,
271
+ ): Promise<string[]> {
272
+ const stablePaths = await Promise.all(
273
+ [
274
+ path.join(distDir, "plugin-sdk", "command-auth.js"),
275
+ path.join(distDir, "plugin-sdk", "plugin-runtime.js"),
276
+ ].map(async (candidate) => ((await pathExists(candidate)) ? candidate : null)),
277
+ );
278
+
279
+ const hashedPaths = await Promise.all([
280
+ resolveHashedModulePath({
281
+ distDir,
282
+ entryFile: "index.js",
283
+ prefix: "commands-registry-",
284
+ }),
285
+ resolveHashedModulePath({
286
+ distDir,
287
+ entryFile: "index.js",
288
+ prefix: "commands-registry.runtime-",
289
+ }),
290
+ resolveHashedModulePath({
291
+ distDir,
292
+ entryFile: "index.js",
293
+ prefix: "skill-commands-",
294
+ }),
295
+ resolveHashedModulePath({
296
+ distDir,
297
+ entryFile: "index.js",
298
+ prefix: "skill-commands.runtime-",
299
+ }),
300
+ resolveHashedModulePath({
301
+ distDir,
302
+ entryFile: "index.js",
303
+ prefix: "config-",
304
+ }),
305
+ resolveHashedModulePath({
306
+ distDir,
307
+ entryFile: "index.js",
308
+ prefix: "io-",
309
+ }),
310
+ resolveHashedModulePath({
311
+ distDir,
312
+ entryFile: "index.js",
313
+ prefix: "pi-embedded-",
314
+ }),
315
+ resolveHashedModulePath({
316
+ distDir,
317
+ entryFile: "index.js",
318
+ prefix: "reply-",
319
+ }),
320
+ resolveHashedModulePath({
321
+ distDir,
322
+ entryFile: "index.js",
323
+ prefix: "registry-",
324
+ }),
325
+ ]);
326
+
327
+ return dedupePaths([...stablePaths, ...hashedPaths]);
328
+ }
329
+
242
330
  async function loadRuntime(): Promise<OpenClawCommandRuntime | null> {
243
331
  if (!cachedRuntimePromise) {
244
332
  cachedRuntimePromise = (async () => {
@@ -248,51 +336,41 @@ async function loadRuntime(): Promise<OpenClawCommandRuntime | null> {
248
336
  }
249
337
 
250
338
  const distDir = path.join(openClawRoot, "dist");
251
- const [replyPath, registryPath] = await Promise.all([
252
- resolveHashedModulePath({
253
- distDir,
254
- entryFile: "index.js",
255
- prefix: "reply-",
256
- }),
257
- resolveHashedModulePath({
258
- distDir,
259
- entryFile: "index.js",
260
- prefix: "registry-",
261
- }),
262
- ]);
263
-
264
- if (!replyPath || !registryPath) {
339
+ const modulePaths = await resolveCommandDiscoveryModulePaths(distDir);
340
+ if (modulePaths.length === 0) {
265
341
  return null;
266
342
  }
267
343
 
268
- const [replyModule, registryModule] = await Promise.all([
269
- import(pathToFileURL(replyPath).href) as Promise<Record<string, unknown>>,
270
- import(pathToFileURL(registryPath).href) as Promise<Record<string, unknown>>,
271
- ]);
344
+ const modules = await Promise.all(
345
+ modulePaths.map(
346
+ (modulePath) =>
347
+ import(pathToFileURL(modulePath).href) as Promise<Record<string, unknown>>,
348
+ ),
349
+ );
272
350
 
273
- const listChatCommands = findExportedFunction<
351
+ const listChatCommands = findExportedFunctionInModules<
274
352
  (params?: {
275
353
  skillCommands?: OpenClawSkillCommandSpecLike[];
276
354
  }) => OpenClawCommandDefinitionLike[]
277
- >(replyModule, "listChatCommands");
278
- const listChatCommandsForConfig = findExportedFunction<
355
+ >(modules, "listChatCommands");
356
+ const listChatCommandsForConfig = findExportedFunctionInModules<
279
357
  (
280
358
  config: unknown,
281
359
  params?: { skillCommands?: OpenClawSkillCommandSpecLike[] },
282
360
  ) => OpenClawCommandDefinitionLike[]
283
- >(replyModule, "listChatCommandsForConfig");
284
- const loadConfig = findExportedFunction<() => unknown>(
285
- replyModule,
361
+ >(modules, "listChatCommandsForConfig");
362
+ const loadConfig = findExportedFunctionInModules<() => unknown>(
363
+ modules,
286
364
  "loadConfig",
287
365
  );
288
- const listSkillCommandsForAgents = findExportedFunction<
366
+ const listSkillCommandsForAgents = findExportedFunctionInModules<
289
367
  (config: unknown) => OpenClawSkillCommandSpecLike[]
290
- >(replyModule, "listSkillCommandsForAgents");
291
- const getPluginCommandSpecs = findExportedFunction<
368
+ >(modules, "listSkillCommandsForAgents");
369
+ const getPluginCommandSpecs = findExportedFunctionInModules<
292
370
  (provider?: string) => OpenClawPluginCommandSpecLike[]
293
- >(registryModule, "getPluginCommandSpecs");
371
+ >(modules, "getPluginCommandSpecs");
294
372
 
295
- if (!listChatCommands || !getPluginCommandSpecs) {
373
+ if (!listChatCommands) {
296
374
  return null;
297
375
  }
298
376
 
@@ -323,8 +401,12 @@ async function loadRuntime(): Promise<OpenClawCommandRuntime | null> {
323
401
  ) as OpenClawSkillCommandSpecLike[],
324
402
  }
325
403
  : {}),
326
- getPluginCommandSpecs: (provider?: string) =>
327
- getPluginCommandSpecs(provider) as OpenClawPluginCommandSpecLike[],
404
+ ...(getPluginCommandSpecs
405
+ ? {
406
+ getPluginCommandSpecs: (provider?: string) =>
407
+ getPluginCommandSpecs(provider) as OpenClawPluginCommandSpecLike[],
408
+ }
409
+ : {}),
328
410
  };
329
411
  })();
330
412
  }
@@ -367,7 +449,7 @@ export async function loadAvailableOpenClawCommands(): Promise<PrivateClawSlashC
367
449
 
368
450
  return dedupeCommands([
369
451
  ...mapBuiltInCommands(builtInCommands),
370
- ...mapPluginCommands(runtime.getPluginCommandSpecs()),
452
+ ...mapPluginCommands(runtime.getPluginCommandSpecs?.() ?? []),
371
453
  ]);
372
454
  }
373
455
 
@@ -408,6 +408,287 @@ test("plugin routes paired app text through OpenClaw runtime helpers with the re
408
408
  });
409
409
  });
410
410
 
411
+ test("plugin falls back to the bridge when runtime session recording reports an error", async (t) => {
412
+ const relay = createRelayServer({
413
+ host: "127.0.0.1",
414
+ port: 0,
415
+ sessionTtlMs: 60_000,
416
+ frameCacheSize: 8,
417
+ });
418
+ const { port } = await relay.start();
419
+
420
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
421
+ t.after(async () => {
422
+ await rm(stateDir, { recursive: true, force: true });
423
+ await relay.stop();
424
+ });
425
+
426
+ let dispatchCalled = false;
427
+ const fakeRuntime = {
428
+ channel: {
429
+ reply: {
430
+ finalizeInboundContext: <T extends Record<string, unknown>>(ctx: T) =>
431
+ ({
432
+ ...ctx,
433
+ CommandAuthorized: true,
434
+ }) as T & { CommandAuthorized: true },
435
+ dispatchReplyWithBufferedBlockDispatcher: async () => {
436
+ dispatchCalled = true;
437
+ return {};
438
+ },
439
+ },
440
+ routing: {
441
+ resolveAgentRoute: ({ ctx }: { ctx: Record<string, unknown> }) => ({
442
+ agentId: "runtime-agent",
443
+ sessionKey: `runtime-${String(ctx.To ?? "session")}`,
444
+ mainSessionKey: `runtime-${String(ctx.To ?? "session")}`,
445
+ lastRoutePolicy: "current" as const,
446
+ }),
447
+ },
448
+ session: {
449
+ resolveStorePath: () => path.join(stateDir, "memory", "runtime-agent.sqlite"),
450
+ recordInboundSession: async (params: { onRecordError(error: unknown): void }) => {
451
+ params.onRecordError(new Error("simulated session-store failure"));
452
+ },
453
+ },
454
+ },
455
+ } satisfies OpenClawPluginRuntimeCompat;
456
+
457
+ const plugin = createOpenClawCompatiblePlugin({
458
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
459
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
460
+ bridge: new EchoBridge("Runtime fallback"),
461
+ welcomeMessage: "Welcome to PrivateClaw",
462
+ });
463
+ const { api, getCommand, getService } = createMockApi(fakeRuntime);
464
+ plugin.register(api);
465
+
466
+ const service = getService();
467
+ await service.start({
468
+ config: {},
469
+ stateDir,
470
+ logger: api.logger,
471
+ });
472
+ t.after(async () => {
473
+ await service.stop?.({
474
+ config: {},
475
+ stateDir,
476
+ logger: api.logger,
477
+ });
478
+ });
479
+
480
+ const command = getCommand();
481
+ const reply = await command.handler({
482
+ channel: "telegram",
483
+ senderId: "tester",
484
+ isAuthorizedSender: true,
485
+ commandBody: "/privateclaw",
486
+ config: {},
487
+ });
488
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
489
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
490
+ const invite = decodeInviteString(inviteUri);
491
+
492
+ const appUrl = new URL(invite.appWsUrl);
493
+ appUrl.searchParams.set("appId", "runtime-record-error-app");
494
+ const appSocket = new WebSocket(appUrl.toString());
495
+ t.after(() => {
496
+ appSocket.terminate();
497
+ });
498
+ const attached = nextMessage(appSocket);
499
+ await waitForOpen(appSocket);
500
+ assert.equal((await attached).type, "relay:attached");
501
+ const initialFrames = nextMessages(appSocket, 2);
502
+ appSocket.send(
503
+ JSON.stringify({
504
+ type: "app:frame",
505
+ envelope: encryptPayload({
506
+ sessionId: invite.sessionId,
507
+ sessionKey: invite.sessionKey,
508
+ payload: {
509
+ kind: "client_hello",
510
+ appId: "runtime-record-error-app",
511
+ displayName: "Runtime Record Error",
512
+ appVersion: "plugin-test",
513
+ deviceLabel: "Runtime Record Error Device",
514
+ sentAt: new Date().toISOString(),
515
+ },
516
+ }),
517
+ }),
518
+ );
519
+ await initialFrames;
520
+
521
+ appSocket.send(
522
+ JSON.stringify({
523
+ type: "app:frame",
524
+ envelope: encryptPayload({
525
+ sessionId: invite.sessionId,
526
+ sessionKey: invite.sessionKey,
527
+ payload: {
528
+ kind: "user_message",
529
+ appId: "runtime-record-error-app",
530
+ text: "hello fallback",
531
+ clientMessageId: "runtime-record-error-msg-1",
532
+ sentAt: new Date().toISOString(),
533
+ },
534
+ }),
535
+ }),
536
+ );
537
+
538
+ const replyFrame = await nextMessage(appSocket);
539
+ const replyPayload = decryptPayload({
540
+ sessionId: invite.sessionId,
541
+ sessionKey: invite.sessionKey,
542
+ envelope: replyFrame.envelope as Parameters<typeof decryptPayload>[0]["envelope"],
543
+ });
544
+ assert.equal(replyPayload.kind, "assistant_message");
545
+ assert.equal(replyPayload.text, "Runtime fallback: hello fallback");
546
+ assert.equal(dispatchCalled, false);
547
+ });
548
+
549
+ test("plugin falls back to the bridge when runtime reply dispatch reports an error", async (t) => {
550
+ const relay = createRelayServer({
551
+ host: "127.0.0.1",
552
+ port: 0,
553
+ sessionTtlMs: 60_000,
554
+ frameCacheSize: 8,
555
+ });
556
+ const { port } = await relay.start();
557
+
558
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
559
+ t.after(async () => {
560
+ await rm(stateDir, { recursive: true, force: true });
561
+ await relay.stop();
562
+ });
563
+
564
+ const fakeRuntime = {
565
+ channel: {
566
+ reply: {
567
+ finalizeInboundContext: <T extends Record<string, unknown>>(ctx: T) =>
568
+ ({
569
+ ...ctx,
570
+ CommandAuthorized: true,
571
+ }) as T & { CommandAuthorized: true },
572
+ dispatchReplyWithBufferedBlockDispatcher: async ({
573
+ dispatcherOptions,
574
+ }: {
575
+ dispatcherOptions: {
576
+ onError?(error: unknown, info: { kind: "tool" | "block" | "final" }): void;
577
+ };
578
+ }) => {
579
+ dispatcherOptions.onError?.(
580
+ new Error("simulated runtime dispatch failure"),
581
+ { kind: "final" },
582
+ );
583
+ return {};
584
+ },
585
+ },
586
+ routing: {
587
+ resolveAgentRoute: ({ ctx }: { ctx: Record<string, unknown> }) => ({
588
+ agentId: "runtime-agent",
589
+ sessionKey: `runtime-${String(ctx.To ?? "session")}`,
590
+ mainSessionKey: `runtime-${String(ctx.To ?? "session")}`,
591
+ lastRoutePolicy: "current" as const,
592
+ }),
593
+ },
594
+ session: {
595
+ resolveStorePath: () => path.join(stateDir, "memory", "runtime-agent.sqlite"),
596
+ recordInboundSession: async () => undefined,
597
+ },
598
+ },
599
+ } satisfies OpenClawPluginRuntimeCompat;
600
+
601
+ const plugin = createOpenClawCompatiblePlugin({
602
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
603
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
604
+ bridge: new EchoBridge("Runtime fallback"),
605
+ welcomeMessage: "Welcome to PrivateClaw",
606
+ });
607
+ const { api, getCommand, getService } = createMockApi(fakeRuntime);
608
+ plugin.register(api);
609
+
610
+ const service = getService();
611
+ await service.start({
612
+ config: {},
613
+ stateDir,
614
+ logger: api.logger,
615
+ });
616
+ t.after(async () => {
617
+ await service.stop?.({
618
+ config: {},
619
+ stateDir,
620
+ logger: api.logger,
621
+ });
622
+ });
623
+
624
+ const command = getCommand();
625
+ const reply = await command.handler({
626
+ channel: "telegram",
627
+ senderId: "tester",
628
+ isAuthorizedSender: true,
629
+ commandBody: "/privateclaw",
630
+ config: {},
631
+ });
632
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
633
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
634
+ const invite = decodeInviteString(inviteUri);
635
+
636
+ const appUrl = new URL(invite.appWsUrl);
637
+ appUrl.searchParams.set("appId", "runtime-dispatch-error-app");
638
+ const appSocket = new WebSocket(appUrl.toString());
639
+ t.after(() => {
640
+ appSocket.terminate();
641
+ });
642
+ const attached = nextMessage(appSocket);
643
+ await waitForOpen(appSocket);
644
+ assert.equal((await attached).type, "relay:attached");
645
+ const initialFrames = nextMessages(appSocket, 2);
646
+ appSocket.send(
647
+ JSON.stringify({
648
+ type: "app:frame",
649
+ envelope: encryptPayload({
650
+ sessionId: invite.sessionId,
651
+ sessionKey: invite.sessionKey,
652
+ payload: {
653
+ kind: "client_hello",
654
+ appId: "runtime-dispatch-error-app",
655
+ displayName: "Runtime Dispatch Error",
656
+ appVersion: "plugin-test",
657
+ deviceLabel: "Runtime Dispatch Error Device",
658
+ sentAt: new Date().toISOString(),
659
+ },
660
+ }),
661
+ }),
662
+ );
663
+ await initialFrames;
664
+
665
+ appSocket.send(
666
+ JSON.stringify({
667
+ type: "app:frame",
668
+ envelope: encryptPayload({
669
+ sessionId: invite.sessionId,
670
+ sessionKey: invite.sessionKey,
671
+ payload: {
672
+ kind: "user_message",
673
+ appId: "runtime-dispatch-error-app",
674
+ text: "hello dispatch fallback",
675
+ clientMessageId: "runtime-dispatch-error-msg-1",
676
+ sentAt: new Date().toISOString(),
677
+ },
678
+ }),
679
+ }),
680
+ );
681
+
682
+ const replyFrame = await nextMessage(appSocket);
683
+ const replyPayload = decryptPayload({
684
+ sessionId: invite.sessionId,
685
+ sessionKey: invite.sessionKey,
686
+ envelope: replyFrame.envelope as Parameters<typeof decryptPayload>[0]["envelope"],
687
+ });
688
+ assert.equal(replyPayload.kind, "assistant_message");
689
+ assert.equal(replyPayload.text, "Runtime fallback: hello dispatch fallback");
690
+ });
691
+
411
692
  test("privateclaw channel outbound delivers replies into managed sessions", async (t) => {
412
693
  const relay = createRelayServer({
413
694
  host: "127.0.0.1",
@@ -931,6 +931,7 @@ class PrivateClawPluginRuntime {
931
931
  agentId: route.agentId,
932
932
  },
933
933
  );
934
+ let recordErrorMessage: string | undefined;
934
935
  await runtime.session.recordInboundSession({
935
936
  storePath,
936
937
  sessionKey: route.sessionKey,
@@ -946,16 +947,28 @@ class PrivateClawPluginRuntime {
946
947
  accountId: PRIVATECLAW_OPENCLAW_ACCOUNT_ID,
947
948
  },
948
949
  onRecordError: (error) => {
950
+ const detail = formatCommandError(error);
951
+ if (!recordErrorMessage) {
952
+ recordErrorMessage = detail;
953
+ }
949
954
  this.providerOptions.onLog?.(
950
- `[privateclaw] runtime_session_record_error session=${message.sessionId} message=${formatCommandError(error)}`,
955
+ `[privateclaw] runtime_session_record_error session=${message.sessionId} message=${detail}`,
951
956
  );
952
957
  },
953
958
  });
959
+ if (recordErrorMessage) {
960
+ throw new Error(
961
+ `Failed to record the OpenClaw runtime session for ${message.sessionId}: ${recordErrorMessage}`,
962
+ );
963
+ }
964
+ let finalReplyDelivered = false;
965
+ let dispatchErrorKind: string | undefined;
966
+ let dispatchErrorMessage: string | undefined;
954
967
  await runtime.reply.dispatchReplyWithBufferedBlockDispatcher({
955
968
  ctx: finalizedCtx,
956
969
  cfg,
957
970
  dispatcherOptions: {
958
- deliver: async (payload) => {
971
+ deliver: async (payload, info) => {
959
972
  const replyToId =
960
973
  typeof payload.replyToId === "string" && payload.replyToId.trim() !== ""
961
974
  ? payload.replyToId
@@ -970,24 +983,37 @@ class PrivateClawPluginRuntime {
970
983
  : {}),
971
984
  replyToId,
972
985
  });
986
+ if (info.kind === "final") {
987
+ finalReplyDelivered = true;
988
+ }
973
989
  },
974
990
  onError: (error, info) => {
991
+ const detail = formatCommandError(error);
992
+ if (!dispatchErrorMessage) {
993
+ dispatchErrorKind = info.kind;
994
+ dispatchErrorMessage = detail;
995
+ }
975
996
  this.providerOptions.onLog?.(
976
- `[privateclaw] runtime_dispatch_error kind=${info.kind} message=${formatCommandError(error)}`,
997
+ `[privateclaw] runtime_dispatch_error kind=${info.kind} message=${detail}`,
977
998
  );
978
999
  },
979
1000
  },
980
1001
  });
1002
+ if (dispatchErrorMessage && !finalReplyDelivered) {
1003
+ throw new Error(
1004
+ `Failed to dispatch the OpenClaw runtime reply for ${message.sessionId} (${dispatchErrorKind ?? "unknown"}): ${dispatchErrorMessage}`,
1005
+ );
1006
+ }
981
1007
  }
982
1008
 
983
1009
  private async routeOrForwardAppMessage(
984
1010
  message: PrivateClawRoutedAppMessage,
985
1011
  ): Promise<boolean> {
986
- if (this.openClawRuntime?.channel) {
987
- await this.routeAppMessageToOpenClaw(message);
988
- return true;
989
- }
990
1012
  try {
1013
+ if (this.openClawRuntime?.channel) {
1014
+ await this.routeAppMessageToOpenClaw(message);
1015
+ return true;
1016
+ }
991
1017
  await dispatchRoutedAppMessageToPluginServiceFromStateDir({
992
1018
  stateDir: this.ensureStateDir(),
993
1019
  message,
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawn } from "node:child_process";
3
3
  import { createServer } from "node:http";
4
- import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
4
+ import { access, mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
5
5
  import { type AddressInfo } from "node:net";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
@@ -77,6 +77,21 @@ function nextMessages(socket: WebSocket, count: number): Promise<Record<string,
77
77
  });
78
78
  }
79
79
 
80
+ function findUnusedPid(start = 999_999): number {
81
+ let candidate = start;
82
+ for (;;) {
83
+ try {
84
+ process.kill(candidate, 0);
85
+ candidate += 1;
86
+ } catch (error) {
87
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "ESRCH") {
88
+ return candidate;
89
+ }
90
+ candidate += 1;
91
+ }
92
+ }
93
+ }
94
+
80
95
  function waitForClose(socket: WebSocket): Promise<void> {
81
96
  return new Promise((resolve) => {
82
97
  if (socket.readyState === WebSocket.CLOSED) {
@@ -816,3 +831,69 @@ test("session control falls back to the saved QR PNG when an older host lacks th
816
831
  /TestFlight|Google Play|Google Group/u,
817
832
  );
818
833
  });
834
+
835
+ test("session listings keep a live descriptor when one sessions probe fails", async (t) => {
836
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-live-"));
837
+ t.after(async () => {
838
+ await rm(stateDir, { recursive: true, force: true });
839
+ });
840
+
841
+ const descriptorDir = resolvePrivateClawControlDir(stateDir);
842
+ await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
843
+ const descriptorPath = path.join(descriptorDir, "pair-daemon-live.json");
844
+ await writeFile(
845
+ descriptorPath,
846
+ JSON.stringify(
847
+ {
848
+ version: 1,
849
+ controlId: "live-control-id",
850
+ kind: "pair-daemon",
851
+ pid: process.pid,
852
+ host: "127.0.0.1",
853
+ port: 1,
854
+ token: "live-token",
855
+ startedAt: new Date().toISOString(),
856
+ },
857
+ null,
858
+ 2,
859
+ ),
860
+ "utf8",
861
+ );
862
+
863
+ const listings = await listManagedSessionsFromStateDir(stateDir);
864
+ assert.deepEqual(listings, []);
865
+ await access(descriptorPath);
866
+ });
867
+
868
+ test("session listings prune a stale descriptor after a failed sessions probe", async (t) => {
869
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-stale-"));
870
+ t.after(async () => {
871
+ await rm(stateDir, { recursive: true, force: true });
872
+ });
873
+
874
+ const descriptorDir = resolvePrivateClawControlDir(stateDir);
875
+ await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
876
+ const descriptorPath = path.join(descriptorDir, "pair-daemon-stale.json");
877
+ await writeFile(
878
+ descriptorPath,
879
+ JSON.stringify(
880
+ {
881
+ version: 1,
882
+ controlId: "stale-control-id",
883
+ kind: "pair-daemon",
884
+ pid: findUnusedPid(),
885
+ host: "127.0.0.1",
886
+ port: 1,
887
+ token: "stale-token",
888
+ startedAt: new Date().toISOString(),
889
+ },
890
+ null,
891
+ 2,
892
+ ),
893
+ "utf8",
894
+ );
895
+
896
+ const listings = await listManagedSessionsFromStateDir(stateDir);
897
+ assert.deepEqual(listings, []);
898
+ await assert.rejects(access(descriptorPath));
899
+ });