@clawchatsai/connector 0.1.44 → 0.1.46

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/README.md CHANGED
@@ -31,12 +31,39 @@ The signaling server only facilitates the handshake. After step 4, it is out of
31
31
 
32
32
  ## Installation
33
33
 
34
+ Requires OpenClaw 2026.9.7 or newer on the machine that runs your gateway.
35
+
34
36
  ```bash
35
37
  openclaw plugins install @clawchatsai/connector
36
- openclaw gateway restart
37
38
  ```
38
39
 
39
- Then open [app.clawchats.ai](https://app.clawchats.ai) and follow the setup flow.
40
+ The gateway loads the plugin right away; no restart is needed. OpenClaw warns that the package is
41
+ outside ClawHub review — answer `y` to continue (pass `--force` in scripts).
42
+
43
+ Install while your gateway is running. If it is not, OpenClaw installs locally instead and asks you to
44
+ re-run the same command with `--accept-capabilities` after reviewing what the plugin declares.
45
+
46
+ Then connect it to your ClawChats account:
47
+
48
+ 1. Open [app.clawchats.ai](https://app.clawchats.ai), sign in, and choose **Connect a gateway**.
49
+ 2. Run the `openclaw clawchats setup <token>` command it shows, on the gateway machine.
50
+ 3. Check the result: `openclaw clawchats status` — Gateway and Signaling should say `connected`.
51
+
52
+ Until step 2 is done the plugin idles and `openclaw clawchats status` says it is waiting for setup.
53
+
54
+ ### Supported platforms
55
+
56
+ A WebRTC binary is bundled for Linux (x64, arm64, arm; glibc and musl), macOS (Intel and Apple
57
+ silicon) and Windows (x64, arm64). Nothing is compiled during install.
58
+
59
+ ### Troubleshooting
60
+
61
+ | Symptom | What to do |
62
+ | --- | --- |
63
+ | `openclaw clawchats status` says *waiting for setup* | Finish step 2 above. |
64
+ | Status says *failed to start* | The message names the cause and the fix. After fixing, run `openclaw plugins reload connector`. |
65
+ | Signaling shows `disconnected` | The gateway machine cannot reach the ClawChats server (offline, proxy or firewall). It keeps retrying; see `journalctl --user -u openclaw-gateway -g clawchats`. |
66
+ | Gateway on a custom port, profile or state directory | Supported: the plugin follows the gateway's config, `OPENCLAW_STATE_DIR` and `OPENCLAW_CONFIG_PATH`. |
40
67
 
41
68
  ## Architecture
42
69
 
package/dist/index.js CHANGED
@@ -62,8 +62,21 @@ class BrowserClientMap extends Map {
62
62
  }
63
63
  }
64
64
  const connectedClients = new BrowserClientMap();
65
- /** The local gateway's WebSocket URL (the app's gateway client and Desktop tunnels). */
66
- const GATEWAY_WS_URL = process.env.GATEWAY_WS_URL || 'ws://localhost:18789';
65
+ const DEFAULT_GATEWAY_PORT = 18789;
66
+ /**
67
+ * The local gateway's WebSocket URL (the app's gateway client and Desktop tunnels):
68
+ * GATEWAY_WS_URL, else the port in the gateway config (a gateway on a custom port),
69
+ * else the default port.
70
+ */
71
+ function resolveGatewayWsUrl(gatewayConfig) {
72
+ if (process.env.GATEWAY_WS_URL)
73
+ return process.env.GATEWAY_WS_URL;
74
+ const gw = gatewayConfig?.['gateway'];
75
+ const port = Number(gw?.['port']) || DEFAULT_GATEWAY_PORT;
76
+ return `ws://127.0.0.1:${port}`;
77
+ }
78
+ /** Set when the service starts; the Desktop tunnels read it. */
79
+ let GATEWAY_WS_URL = resolveGatewayWsUrl();
67
80
  /** Open Desktop tunnels per browser connection (server/desktop-tunnel.js); a viewer uses one or two. */
68
81
  const desktopTunnels = new Map();
69
82
  const MAX_TUNNELS_PER_CONNECTION = 8;
@@ -76,6 +89,10 @@ let signaling = null;
76
89
  let webrtcPeer = null;
77
90
  let healthServer = null;
78
91
  let _stopRequested = false;
92
+ let _serviceState = 'stopped';
93
+ let _serviceError = '';
94
+ /** The background startup, so stop() can wait for it to unwind. */
95
+ let _startupRun = null;
79
96
  // Gateway sharing: links this gateway is opening to another gateway (it offers), by share.
80
97
  const PEER_OPEN_TIMEOUT_MS = 30_000;
81
98
  const peerOpens = new Map();
@@ -107,7 +124,15 @@ function settlePeerOpen(shareId, outcome) {
107
124
  // ---------------------------------------------------------------------------
108
125
  // Config helpers
109
126
  // ---------------------------------------------------------------------------
110
- const CONFIG_DIR = path.join(os.homedir(), '.openclaw', 'clawchats');
127
+ /** The gateway's state directory: OPENCLAW_STATE_DIR (profiles, custom installs), else ~/.openclaw. */
128
+ function stateRoot() {
129
+ return process.env.OPENCLAW_STATE_DIR || path.join(os.homedir(), '.openclaw');
130
+ }
131
+ /** The gateway's config file: OPENCLAW_CONFIG_PATH, else <state>/openclaw.json. */
132
+ function gatewayConfigPath() {
133
+ return process.env.OPENCLAW_CONFIG_PATH || path.join(stateRoot(), 'openclaw.json');
134
+ }
135
+ const CONFIG_DIR = path.join(stateRoot(), 'clawchats');
111
136
  const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
112
137
  const RUNTIME_FILE = path.join(CONFIG_DIR, 'runtime.json');
113
138
  function loadConfig() {
@@ -195,8 +220,8 @@ async function ensureNativeModules(ctx) {
195
220
  const require = createRequire(import.meta.url);
196
221
  const ndcRoot = resolvePackageRoot(require, 'node-datachannel');
197
222
  if (!ndcRoot) {
198
- ctx.logger.error('[clawchats] node-datachannel package not resolvable; WebRTC unavailable.');
199
- return;
223
+ throw new Error(`the WebRTC library (node-datachannel) is missing from this install. ` +
224
+ `Reinstall the plugin: openclaw plugins install @clawchatsai/connector --force`);
200
225
  }
201
226
  const targetPath = path.join(ndcRoot, 'build', 'Release', 'node_datachannel.node');
202
227
  // Already built — nothing to do.
@@ -206,10 +231,9 @@ async function ensureNativeModules(ctx) {
206
231
  const prebuildKey = getPrebuildKey();
207
232
  const prebuiltPath = path.join(pluginDir, 'prebuilds', prebuildKey, 'node_datachannel.node');
208
233
  if (!fs.existsSync(prebuiltPath)) {
209
- ctx.logger.error(`[clawchats] No prebuilt binary for ${prebuildKey}. ` +
210
- `WebRTC will be unavailable. To fix manually: ` +
211
- `cd ~/.openclaw/extensions/connector && npm rebuild node-datachannel`);
212
- return;
234
+ throw new Error(`no prebuilt WebRTC binary for ${prebuildKey} (Node ${process.version}). ` +
235
+ `Build it from source (needs cmake, make and a C++ compiler): ` +
236
+ `cd ${pluginDir} && npm rebuild node-datachannel`);
213
237
  }
214
238
  ctx.logger.info(`[clawchats] Installing node-datachannel prebuilt for ${prebuildKey}...`);
215
239
  try {
@@ -218,19 +242,71 @@ async function ensureNativeModules(ctx) {
218
242
  ctx.logger.info('[clawchats] node-datachannel ready.');
219
243
  }
220
244
  catch (e) {
221
- // Surface the manual remedy: the service import fails moments later with an
222
- // opaque "Cannot find module '../../../build/Release/node_datachannel.node'",
223
- // which says nothing about what to actually do.
224
- ctx.logger.error(`[clawchats] Failed to install prebuilt: ${e.message}\n` +
225
- ` To fix manually:\n mkdir -p ${path.dirname(targetPath)}\n` +
226
- ` cp ${prebuiltPath} ${targetPath}`);
245
+ // Say what to do: the import fails moments later with an opaque
246
+ // "Cannot find module '../../../build/Release/node_datachannel.node'".
247
+ throw new Error(`could not install the WebRTC binary (${e.message}). To fix manually: ` +
248
+ `mkdir -p ${path.dirname(targetPath)} && cp ${prebuiltPath} ${targetPath}`);
227
249
  }
228
250
  }
251
+ /**
252
+ * Service entry point. Returns at once: the gateway kills a service whose start() has not
253
+ * settled within ~5 s, and the real startup can take far longer (waiting for the user to run
254
+ * setup, loading the native WebRTC module on a slow box, the signaling handshake).
255
+ */
229
256
  async function startClawChats(ctx, api) {
230
257
  _stopRequested = false;
258
+ _serviceError = '';
259
+ _startupRun = runClawChats(ctx, api).catch((e) => {
260
+ _serviceState = 'failed';
261
+ _serviceError = e?.message || String(e);
262
+ ctx.logger.error(`ClawChats failed to start: ${_serviceError}`);
263
+ });
264
+ }
265
+ /**
266
+ * The local status endpoint `openclaw clawchats status` queries. Started first thing, so status
267
+ * can say "waiting for setup" or why startup failed, not just "offline".
268
+ */
269
+ function startHealthEndpoint(ctx) {
270
+ if (healthServer)
271
+ return;
272
+ healthServer = http.createServer((req, res) => {
273
+ if (req.url === '/status' && req.method === 'GET') {
274
+ res.writeHead(200, { 'Content-Type': 'application/json' });
275
+ res.end(JSON.stringify({
276
+ version: PLUGIN_VERSION,
277
+ pid: process.pid,
278
+ uptime: process.uptime(),
279
+ state: _serviceState,
280
+ error: _serviceError || undefined,
281
+ gateway: { connected: app?.gatewayClient?.connected ?? false },
282
+ signaling: { connected: signaling?.isConnected ?? false },
283
+ clients: { active: connectedClients.size },
284
+ }));
285
+ }
286
+ else {
287
+ res.writeHead(404);
288
+ res.end();
289
+ }
290
+ });
291
+ healthServer.listen(0, '127.0.0.1', () => {
292
+ const addr = healthServer.address();
293
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
294
+ fs.writeFileSync(RUNTIME_FILE, JSON.stringify({
295
+ pid: process.pid,
296
+ healthPort: addr.port,
297
+ startedAt: new Date().toISOString(),
298
+ }, null, 2), { mode: 0o600 });
299
+ ctx.logger.info(`Health endpoint on 127.0.0.1:${addr.port}`);
300
+ });
301
+ }
302
+ const SETUP_HINT = 'ClawChats is installed but not set up yet. Next step: open https://app.clawchats.ai, sign in, ' +
303
+ 'and follow "Connect a gateway" — it gives you a command like `openclaw clawchats setup <token>` to run here.';
304
+ async function runClawChats(ctx, api) {
305
+ startHealthEndpoint(ctx);
231
306
  let config = loadConfig();
232
307
  if (!config) {
233
- ctx.logger.info('ClawChats not configured. Waiting for setup...');
308
+ _serviceState = 'waiting-setup';
309
+ ctx.logger.info(SETUP_HINT);
234
310
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
235
311
  while (!config && !_stopRequested) {
236
312
  await new Promise(r => setTimeout(r, 2000));
@@ -240,16 +316,19 @@ async function startClawChats(ctx, api) {
240
316
  return;
241
317
  ctx.logger.info('Setup detected — connecting to ClawChats...');
242
318
  }
319
+ _serviceState = 'starting';
320
+ GATEWAY_WS_URL = resolveGatewayWsUrl(api.config);
243
321
  // 1. Resolve gateway token: runtime API → config file → error
244
322
  const gwCfg = api.config;
245
323
  const gwAuth = gwCfg?.['gateway']?.['auth'];
246
324
  const gatewayToken = gwAuth?.['token'] || config.gatewayToken || '';
247
325
  if (!gatewayToken) {
248
- ctx.logger.error('No gateway token available. Re-run: openclaw clawchats setup <token>');
249
- return;
326
+ throw new Error('no gateway token available (the gateway config has no gateway.auth.token). Re-run: openclaw clawchats setup <token>');
250
327
  }
251
328
  // 3. Ensure native modules are built (OpenClaw installs with --ignore-scripts)
252
329
  await ensureNativeModules(ctx);
330
+ if (_stopRequested)
331
+ return;
253
332
  // 4. Import server.js and create app instance with plugin paths
254
333
  const dataDir = path.join(ctx.stateDir, 'clawchats', 'data');
255
334
  // Dynamic import of server.js (plain JS, no type declarations)
@@ -272,7 +351,7 @@ async function startClawChats(ctx, api) {
272
351
  openaiApiKey: (() => {
273
352
  // Resolve OpenAI API key: openclaw config → env var
274
353
  try {
275
- const oc = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.openclaw', 'openclaw.json'), 'utf8'));
354
+ const oc = JSON.parse(fs.readFileSync(gatewayConfigPath(), 'utf8'));
276
355
  const fromConfig = oc?.skills?.entries?.['openai-whisper-api']?.apiKey;
277
356
  if (fromConfig)
278
357
  return fromConfig;
@@ -341,6 +420,10 @@ async function startClawChats(ctx, api) {
341
420
  });
342
421
  // 6. Initialize WebRTC peer manager (lazy import — native module must be built first)
343
422
  const { WebRTCPeerManager } = await import('./webrtc-peer.js');
423
+ if (_stopRequested) {
424
+ teardownRuntime();
425
+ return;
426
+ }
344
427
  webrtcPeer = new WebRTCPeerManager();
345
428
  webrtcPeer.on('datachannel', (dc, connectionId) => {
346
429
  ctx.logger.info(`Browser connected via DataChannel: ${connectionId}`);
@@ -440,40 +523,39 @@ async function startClawChats(ctx, api) {
440
523
  webrtcPeer.on('ice-candidate-local', (data) => {
441
524
  signaling?.sendIceCandidate(data.connectionId, data.candidate);
442
525
  });
443
- await signaling.connect();
444
- // 7. Start health endpoint for CLI status queries
445
- healthServer = http.createServer((req, res) => {
446
- if (req.url === '/status' && req.method === 'GET') {
447
- res.writeHead(200, { 'Content-Type': 'application/json' });
448
- res.end(JSON.stringify({
449
- version: PLUGIN_VERSION,
450
- pid: process.pid,
451
- uptime: process.uptime(),
452
- gateway: { connected: app?.gatewayClient?.connected ?? false },
453
- signaling: { connected: signaling?.isConnected ?? false },
454
- clients: { active: connectedClients.size },
455
- }));
456
- }
457
- else {
458
- res.writeHead(404);
459
- res.end();
460
- }
461
- });
462
- healthServer.listen(0, '127.0.0.1', () => {
463
- const addr = healthServer.address();
464
- fs.mkdirSync(CONFIG_DIR, { recursive: true });
465
- fs.writeFileSync(RUNTIME_FILE, JSON.stringify({
466
- pid: process.pid,
467
- healthPort: addr.port,
468
- startedAt: new Date().toISOString(),
469
- }, null, 2), { mode: 0o600 });
470
- ctx.logger.info(`Health endpoint on 127.0.0.1:${addr.port}`);
471
- });
526
+ // The first connection can fail (offline, firewall, server restart); the client keeps retrying with
527
+ // backoff on its own, so that is a state to report, not a failed start.
528
+ try {
529
+ await signaling.connect();
530
+ }
531
+ catch (e) {
532
+ ctx.logger.warn(`Can't reach the ClawChats server yet (${e.message}); retrying in the background.`);
533
+ }
534
+ if (_stopRequested) {
535
+ teardownRuntime();
536
+ return;
537
+ }
538
+ if (_stopRequested) {
539
+ teardownRuntime();
540
+ return;
541
+ }
542
+ _serviceState = 'running';
472
543
  ctx.logger.info('ClawChats service started');
473
544
  }
474
545
  async function stopClawChats(ctx) {
475
546
  _stopRequested = true;
547
+ _serviceState = 'stopped';
476
548
  ctx.logger.info('ClawChats service stopping...');
549
+ // Let a startup that is mid-flight notice the stop and unwind; never wait long for it.
550
+ if (_startupRun) {
551
+ await Promise.race([_startupRun, new Promise(r => { setTimeout(r, 3000).unref?.(); })]);
552
+ _startupRun = null;
553
+ }
554
+ teardownRuntime();
555
+ ctx.logger.info('ClawChats service stopped');
556
+ }
557
+ /** Releases everything a started service holds. Safe to call more than once. */
558
+ function teardownRuntime() {
477
559
  // 0. Tear down health endpoint
478
560
  if (healthServer) {
479
561
  healthServer.close();
@@ -502,7 +584,6 @@ async function stopClawChats(ctx) {
502
584
  // 4. Close SQLite databases
503
585
  app?.shutdown();
504
586
  app = null;
505
- ctx.logger.info('ClawChats service stopped');
506
587
  }
507
588
  // ---------------------------------------------------------------------------
508
589
  // ---------------------------------------------------------------------------
@@ -847,6 +928,14 @@ function broadcastToClients(msg) {
847
928
  function formatStatus() {
848
929
  const lines = [];
849
930
  lines.push(`ClawChats Plugin v${PLUGIN_VERSION}`);
931
+ if (_serviceState === 'waiting-setup') {
932
+ lines.push(SETUP_HINT);
933
+ return lines.join('\n');
934
+ }
935
+ if (_serviceState === 'failed') {
936
+ lines.push(`Failed to start: ${_serviceError || 'unknown error'}`);
937
+ return lines.join('\n');
938
+ }
850
939
  lines.push(`Gateway: ${app?.gatewayClient?.connected ? 'connected' : 'disconnected'}`);
851
940
  lines.push(`Signaling: ${signaling?.isConnected ? 'connected' : 'disconnected'}`);
852
941
  lines.push(`Clients: ${connectedClients.size}`);
@@ -878,7 +967,7 @@ async function handleSetup(token, options = {}) {
878
967
  // Read gateway token from OpenClaw config
879
968
  let gatewayToken = '';
880
969
  try {
881
- const openclawConfigPath = path.join(os.homedir(), '.openclaw', 'openclaw.json');
970
+ const openclawConfigPath = gatewayConfigPath();
882
971
  const openclawConfig = JSON.parse(fs.readFileSync(openclawConfigPath, 'utf8'));
883
972
  gatewayToken = openclawConfig.gateway?.auth?.token || openclawConfig.auth?.token || openclawConfig.token || '';
884
973
  }
@@ -1214,7 +1303,7 @@ async function handleReauth() {
1214
1303
  }
1215
1304
  async function handleExportHistory(api, mode) {
1216
1305
  if (mode !== undefined && mode !== 'check') {
1217
- console.error(`Unknown option "${mode}". Use: ocplatform clawchats export-history [check]`);
1306
+ console.error(`Unknown option "${mode}". Use: openclaw clawchats export-history [check]`);
1218
1307
  process.exitCode = 1;
1219
1308
  return;
1220
1309
  }
@@ -1222,11 +1311,11 @@ async function handleExportHistory(api, mode) {
1222
1311
  const gw = gwCfg?.['gateway'];
1223
1312
  const token = gw?.['auth']?.['token'] || loadConfig()?.gatewayToken || '';
1224
1313
  if (!token) {
1225
- console.error('No gateway token found. Is ClawChats set up? (ocplatform clawchats setup <token>)');
1314
+ console.error('No gateway token found. Is ClawChats set up? (openclaw clawchats setup <token>)');
1226
1315
  process.exitCode = 1;
1227
1316
  return;
1228
1317
  }
1229
- const port = gw?.['port'] || 18789;
1318
+ const port = gw?.['port'] || DEFAULT_GATEWAY_PORT;
1230
1319
  // @ts-expect-error — server/ is plain JS with no .d.ts
1231
1320
  const serverModule = await import('../server/history-export.js');
1232
1321
  try {
@@ -1258,12 +1347,16 @@ async function handleImportDates() {
1258
1347
  async function handleStatus() {
1259
1348
  // CLI runs in a separate process — module-level vars are null here.
1260
1349
  // Query the live service via the health endpoint instead.
1350
+ const configured = loadConfig() !== null;
1261
1351
  let runtime;
1262
1352
  try {
1263
1353
  runtime = JSON.parse(fs.readFileSync(RUNTIME_FILE, 'utf8'));
1264
1354
  }
1265
1355
  catch {
1266
- console.log('ClawChats: offline (service not running)');
1356
+ console.log('ClawChats: the service is not running.');
1357
+ console.log(configured
1358
+ ? ' The gateway starts it with the plugin. Check: openclaw plugins inspect connector — then openclaw plugins reload connector'
1359
+ : ` ${SETUP_HINT}`);
1267
1360
  return;
1268
1361
  }
1269
1362
  // Verify PID is alive
@@ -1271,7 +1364,7 @@ async function handleStatus() {
1271
1364
  process.kill(runtime.pid, 0);
1272
1365
  }
1273
1366
  catch {
1274
- console.log('ClawChats: offline (stale runtime file)');
1367
+ console.log('ClawChats: the service is not running (stale runtime file).');
1275
1368
  try {
1276
1369
  fs.unlinkSync(RUNTIME_FILE);
1277
1370
  }
@@ -1291,13 +1384,26 @@ async function handleStatus() {
1291
1384
  });
1292
1385
  const status = JSON.parse(body);
1293
1386
  console.log(`ClawChats Plugin v${status.version}`);
1387
+ if (status.state === 'waiting-setup') {
1388
+ console.log('State: waiting for setup');
1389
+ console.log(` ${SETUP_HINT}`);
1390
+ return;
1391
+ }
1392
+ if (status.state === 'failed') {
1393
+ console.log('State: failed to start');
1394
+ console.log(` ${status.error || 'unknown error'}`);
1395
+ console.log(' After fixing it: openclaw plugins reload connector');
1396
+ return;
1397
+ }
1398
+ if (status.state === 'starting')
1399
+ console.log('State: starting');
1294
1400
  console.log(`Uptime: ${Math.floor(status.uptime)}s`);
1295
1401
  console.log(`Gateway: ${status.gateway.connected ? 'connected' : 'disconnected'}`);
1296
1402
  console.log(`Signaling: ${status.signaling.connected ? 'connected' : 'disconnected'}`);
1297
1403
  console.log(`Clients: ${status.clients.active}`);
1298
1404
  }
1299
1405
  catch {
1300
- console.log('ClawChats: offline (could not reach service)');
1406
+ console.log('ClawChats: the service is running but did not answer (could not reach it).');
1301
1407
  }
1302
1408
  }
1303
1409
  async function handleReset() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.44",
3
+ "version": "0.1.46",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
package/server/config.js CHANGED
@@ -5,6 +5,18 @@ import { fileURLToPath } from 'node:url';
5
5
 
6
6
  export const HOME = os.homedir();
7
7
 
8
+ /** The gateway's state directory: OPENCLAW_STATE_DIR (profiles, custom installs), else ~/.openclaw. */
9
+ export const STATE_DIR = process.env.OPENCLAW_STATE_DIR || path.join(HOME, '.openclaw');
10
+
11
+ /** Where the gateway's config file may be, most specific first. */
12
+ export function gatewayConfigCandidates() {
13
+ return [
14
+ process.env.OPENCLAW_CONFIG_PATH,
15
+ path.join(STATE_DIR, 'openclaw.json'),
16
+ '/etc/openclaw/openclaw.json',
17
+ ].filter(Boolean);
18
+ }
19
+
8
20
  // Resolve __dirname for ESM (esbuild inlines this correctly)
9
21
  const __filename = fileURLToPath(import.meta.url);
10
22
  const __dirname = path.dirname(__filename);
@@ -30,7 +42,7 @@ export const AUTH_TOKEN = parseConfigField('authToken') || '';
30
42
  // (that's the browser's external-facing URL and would cause a routing loop through Caddy)
31
43
  // Note: GATEWAY_WS_URL env var is read by the plugin host (src/index.ts) and passed via createApp().
32
44
  export function discoverGatewayWsUrl() {
33
- for (const cfgPath of [path.join(HOME, '.openclaw', 'openclaw.json'), '/etc/openclaw/openclaw.json']) {
45
+ for (const cfgPath of gatewayConfigCandidates()) {
34
46
  try {
35
47
  const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
36
48
  const port = raw.gateway?.port || raw.port;
@@ -44,11 +56,11 @@ export const GATEWAY_WS_URL = discoverGatewayWsUrl();
44
56
 
45
57
  // Agent workspace dir (relative /api/file paths resolve against it): openclaw config → default.
46
58
  export function discoverWorkspaceDir() {
47
- for (const cfgPath of [path.join(HOME, '.openclaw', 'openclaw.json'), '/etc/openclaw/openclaw.json']) {
59
+ for (const cfgPath of gatewayConfigCandidates()) {
48
60
  try {
49
61
  const ws = JSON.parse(fs.readFileSync(cfgPath, 'utf8')).agents?.defaults?.workspace;
50
62
  if (ws) return ws;
51
63
  } catch { /* try next */ }
52
64
  }
53
- return path.join(HOME, '.openclaw', 'workspace');
65
+ return path.join(STATE_DIR, 'workspace');
54
66
  }
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import os from 'node:os';
4
3
  import { send } from '../util/http.js';
4
+ import { STATE_DIR } from '../config.js';
5
5
 
6
6
  /**
7
7
  * List available OpenClaw agents.
@@ -9,7 +9,7 @@ import { send } from '../util/http.js';
9
9
  */
10
10
  export function handleAgents(req, res) {
11
11
  try {
12
- const agentsDir = path.join(os.homedir(), '.openclaw', 'agents');
12
+ const agentsDir = path.join(STATE_DIR, 'agents');
13
13
  const agents = fs.readdirSync(agentsDir, { withFileTypes: true })
14
14
  .filter(e => e.isDirectory())
15
15
  .map(e => e.name);
package/server/gateway.js CHANGED
@@ -102,7 +102,7 @@ export class GatewayClient {
102
102
  this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events']) }));
103
103
  return;
104
104
  }
105
- if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); this.onConnected?.(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seed().catch(e => console.warn(`[lens] seed failed: ${e.message}`)); }
105
+ if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); this.onConnected?.(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seedWithRetry(); }
106
106
  // Session events arrive through the connector's own subscription; the lens filters them
107
107
  // for the browser (session.message only for chats a browser subscribed to).
108
108
  if (msg.type === 'event' && (msg.event === 'sessions.changed' || msg.event === 'session.message')) {
@@ -206,17 +206,39 @@ export class SessionLens {
206
206
  return isUtilityKey(key) || this.isVisible(key) || !!this.team?.isWorkKey(key);
207
207
  }
208
208
 
209
- /** Seed `hidden` from a full roster so partial events of child sessions stay hidden. */
209
+ /** Seed `hidden` from a full roster so partial events of child sessions stay hidden. With the
210
+ * whole roster in hand, also drop ClawChats data (bookmarks etc.) of sessions deleted while
211
+ * the connector wasn't listening for `sessions.changed`. */
210
212
  async seed() {
211
213
  if (!this.request) return;
212
- let offset = 0, rows = 0;
214
+ let offset = 0, rows = 0, complete = false;
215
+ const live = new Set();
213
216
  for (let page = 0; page < 50; page++) {
214
217
  const res = await this.request('sessions.list', { archived: 'all', limit: 1000, offset }, 60000);
215
- for (const row of res?.sessions || []) { this.observe(row.key, row); rows++; }
216
- if (!res?.hasMore || res.nextOffset == null) break;
218
+ for (const row of res?.sessions || []) { this.observe(row.key, row); live.add(row.key); rows++; }
219
+ if (!res?.hasMore || res.nextOffset == null) { complete = true; break; }
217
220
  offset = res.nextOffset;
218
221
  }
219
222
  this.log.info?.(`[lens] seeded from ${rows} sessions (${this.hidden.size} hidden chat-shaped)`);
223
+ if (complete && live.size && this.extras?.pruneThreadExtras) {
224
+ const dropped = this.extras.pruneThreadExtras(live);
225
+ if (dropped) {
226
+ this.log.info?.(`[lens] dropped bookmarks/extras of ${dropped} deleted sessions`);
227
+ this.broadcast(JSON.stringify({ type: 'clawchats', event: 'bookmarks-changed' }));
228
+ }
229
+ }
230
+ }
231
+
232
+ /** seed(), retried: right after a plugin reload the gateway can briefly fail sessions.list
233
+ * (PluginInstanceUnavailableError), and a missed seed also skips the extras prune. */
234
+ async seedWithRetry(tries = 4, delayMs = 5000) {
235
+ for (let i = 1; ; i++) {
236
+ try { return await this.seed(); } catch (e) {
237
+ this.log.warn?.(`[lens] seed failed (${i}/${tries}): ${e.message}`);
238
+ if (i >= tries) return;
239
+ await new Promise(r => setTimeout(r, delayMs));
240
+ }
241
+ }
220
242
  }
221
243
 
222
244
  // ── Gateway → browser ───────────────────────────────────────────────
@@ -232,8 +254,9 @@ export class SessionLens {
232
254
  if (payload.reason === 'patch' && this.team?.onSessionPatched) {
233
255
  this.team.onSessionPatched(key).catch(e => this.log.warn?.(`[lens] team patch: ${e.message}`));
234
256
  }
235
- if (!this.observe(key, payload.session || payload)) return null;
257
+ // Before the visibility check: a deleted session's bookmarks go even if the lens had it hidden.
236
258
  if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
259
+ if (!this.observe(key, payload.session || payload)) return null;
237
260
  const out = trimEvent(payload);
238
261
  if (payload.reason !== 'delete') this._withParent(key, out.session || out);
239
262
  return { type: 'event', event: 'sessions.changed', payload: out };
@@ -101,6 +101,48 @@ test('group rename/delete move project styles only on success', () => {
101
101
  assert.deepEqual(calls, [['rename', 'A', 'B'], ['delete', 'C'], ['thread', CHAT]]);
102
102
  });
103
103
 
104
+ test('delete drops extras even for a hidden session', () => {
105
+ const calls = [];
106
+ const { l } = lens({ deleteThreadExtras: k => calls.push(k) });
107
+ l.sessionsChanged({ sessionKey: CHILD, reason: 'create', parentSessionKey: CHAT });
108
+ assert.equal(l.sessionsChanged({ sessionKey: CHILD, reason: 'delete' }), null);
109
+ assert.deepEqual(calls, [CHILD]);
110
+ });
111
+
112
+ test('seed prunes extras of sessions missing from a complete roster', async () => {
113
+ const pruned = [];
114
+ const sent = [];
115
+ const pages = [{ sessions: [{ key: CHAT }], hasMore: true, nextOffset: 1 }, { sessions: [{ key: DISCORD }], hasMore: false }];
116
+ const l = new SessionLens({ broadcast: d => sent.push(JSON.parse(d)), request: async () => pages.shift(), logger: { info() {} },
117
+ extras: { pruneThreadExtras: keys => { pruned.push([...keys]); return 1; } } });
118
+ await l.seed();
119
+ assert.deepEqual(pruned, [[CHAT, DISCORD]]);
120
+ assert.deepEqual(sent, [{ type: 'clawchats', event: 'bookmarks-changed' }]);
121
+
122
+ // A failed or empty roster prunes nothing.
123
+ const l2 = new SessionLens({ broadcast() {}, request: async () => ({ sessions: [] }), logger: { info() {} },
124
+ extras: { pruneThreadExtras: () => { throw new Error('must not prune'); } } });
125
+ await l2.seed();
126
+ const l3 = new SessionLens({ broadcast() {}, request: async () => { throw new Error('down'); }, logger: { info() {} },
127
+ extras: { pruneThreadExtras: () => { throw new Error('must not prune'); } } });
128
+ await assert.rejects(l3.seed());
129
+ });
130
+
131
+ test('seedWithRetry retries a failed roster', async () => {
132
+ let calls = 0;
133
+ const pruned = [];
134
+ const l = new SessionLens({ broadcast() {}, logger: { info() {}, warn() {} },
135
+ request: async () => { if (++calls < 3) throw new Error('PluginInstanceUnavailableError'); return { sessions: [{ key: CHAT }] }; },
136
+ extras: { pruneThreadExtras: keys => { pruned.push([...keys]); return 0; } } });
137
+ await l.seedWithRetry(4, 1);
138
+ assert.equal(calls, 3);
139
+ assert.deepEqual(pruned, [[CHAT]]);
140
+ let n = 0;
141
+ const l2 = new SessionLens({ broadcast() {}, logger: { info() {}, warn() {} }, request: async () => { n++; throw new Error('down'); } });
142
+ await l2.seedWithRetry(2, 1);
143
+ assert.equal(n, 2);
144
+ });
145
+
104
146
  test('trimRow keeps only allow-listed fields', () => {
105
147
  assert.deepEqual(trimRow({ key: 'k', unread: true, participants: [], thinkingOptions: [] }), { key: 'k', unread: true });
106
148
  });
@@ -130,6 +130,15 @@ export function createExtrasStore(getGlobalDb) {
130
130
  db().prepare('DELETE FROM bookmarks WHERE session_key = ?').run(sessionKey);
131
131
  },
132
132
 
133
+ /** Drop per-session data of sessions not in `liveKeys` (deleted while the connector wasn't
134
+ * listening). Returns how many sessions were dropped. */
135
+ pruneThreadExtras(liveKeys) {
136
+ const keys = db().prepare('SELECT session_key FROM thread_extras UNION SELECT session_key FROM bookmarks').all().map(r => r.session_key);
137
+ const gone = keys.filter(k => !liveKeys.has(k));
138
+ for (const k of gone) this.deleteThreadExtras(k);
139
+ return gone.length;
140
+ },
141
+
133
142
  /** All bookmarks, newest first. */
134
143
  listBookmarks() {
135
144
  return db().prepare('SELECT * FROM bookmarks ORDER BY created_at DESC').all().map(bookmarkRow);
@@ -66,4 +66,12 @@ test('bookmarks: add is idempotent per message, rename, delete, dropped with the
66
66
  assert.equal(extras.deleteBookmark('b4'), false);
67
67
  extras.deleteThreadExtras('agent:main:x');
68
68
  assert.deepEqual(extras.listBookmarks(), []);
69
+
70
+ // Sessions deleted while the connector wasn't listening: dropped against the live roster.
71
+ extras.addBookmark('b5', { sessionKey: 'agent:main:live', messageId: 'm1' });
72
+ extras.addBookmark('b6', { sessionKey: 'agent:main:gone', messageId: 'm1' });
73
+ extras.setThreadExtra('agent:main:gone2', 'intel', { a: 1 });
74
+ assert.equal(extras.pruneThreadExtras(new Set(['agent:main:live'])), 2);
75
+ assert.deepEqual(extras.listBookmarks().map(b => b.id), ['b5']);
76
+ assert.equal(extras.pruneThreadExtras(new Set(['agent:main:live'])), 0);
69
77
  });