@clawchatsai/connector 0.1.35 → 0.1.37

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
package/server/index.js CHANGED
@@ -289,6 +289,9 @@ export function createApp(config = {}) {
289
289
  if (room && body.discuss !== undefined) {
290
290
  try { room = team.setDiscuss(p.room, body.discuss); } catch (e) { return sendError(res, 400, e.message); }
291
291
  }
292
+ if (room && body.mentionOnly !== undefined) {
293
+ try { room = team.setMentionOnly(p.room, body.mentionOnly); } catch (e) { return sendError(res, 400, e.message); }
294
+ }
292
295
  if (room && body.rounds !== undefined) {
293
296
  try { room = team.setRounds(p.room, body.rounds); } catch (e) { return sendError(res, 400, e.message); }
294
297
  }
@@ -298,16 +301,16 @@ export function createApp(config = {}) {
298
301
  const { personId, history } = await parseBody(req);
299
302
  if (typeof personId !== 'string' || !personId) return sendError(res, 400, 'personId is required');
300
303
  try {
301
- const room = await team.addPerson(p.room, personId, { history });
304
+ const room = await team.addPerson(p.room, personId, { history, quietAgents: true });
302
305
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
303
306
  } catch (e) { return sendError(res, 400, e.message); }
304
307
  }
305
308
  if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/people/:personId'))) {
306
- const room = team.removePerson(p.room, p.personId);
309
+ const room = await team.removePerson(p.room, p.personId);
307
310
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat you host');
308
311
  }
309
312
  if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/leave'))) {
310
- try { return send(res, 200, { room: await team.leave(p.room) }); }
313
+ try { return send(res, 200, { room: await team.leave(p.room, await parseBody(req).catch(() => ({}))) }); }
311
314
  catch (e) { return sendError(res, 400, e.message); }
312
315
  }
313
316
  if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
@@ -320,7 +323,7 @@ export function createApp(config = {}) {
320
323
  }
321
324
  if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/agents/:agentId'))) {
322
325
  try {
323
- const room = team.removeAgent(p.room, p.agentId);
326
+ const room = await team.removeAgent(p.room, p.agentId);
324
327
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
325
328
  } catch (e) { return sendError(res, 400, e.message); }
326
329
  }
@@ -94,6 +94,7 @@ export class SharingManager {
94
94
 
95
95
  /** `share-list` from the signal server. Ends links/grants for shares that are gone. */
96
96
  setShares(shares) {
97
+ this._nameCache = null;
97
98
  const first = !this.serverEnabled;
98
99
  this.serverEnabled = true;
99
100
  this._shares = Array.isArray(shares) ? shares : [];
@@ -102,14 +103,43 @@ export class SharingManager {
102
103
  for (const s of this._localGrants()) if (!live.has(s.share_id) && !this._shares.some(x => x.id === s.share_id && x.status === 'pending')) this._revokeLocal(s.share_id);
103
104
  this._changed();
104
105
  if (first) setImmediate(() => { try { this.onFirstShares?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } });
106
+ this._sharesChanged();
107
+ this._presenceTick();
105
108
  }
106
109
 
110
+ /**
111
+ * Presence: a gateway that asked for someone's agents is the one that can open the link to them, so
112
+ * it keeps one open (and re-opens it when it drops). Without that, a room host that only *granted*
113
+ * shares couldn't reach its people until they happened to use an agent: copies would sit unsent.
114
+ * Retries back off per share (15 s up to 10 min); a failed dial costs nothing.
115
+ */
116
+ _presenceTick() {
117
+ clearTimeout(this._presenceTimer);
118
+ if (!this.serverEnabled || this._closed) return;
119
+ for (const s of this._shares) {
120
+ if (s.as !== 'requester' || s.status !== 'active' || !this._verifiedGrant(s)) continue;
121
+ const cur = this._links.get(s.id);
122
+ const b = (this._backoff ??= new Map());
123
+ if ((cur?.ready && !cur.closed) || this._linking.has(s.id)) { b.delete(s.id); continue; }
124
+ const st = b.get(s.id) || { next: 0, wait: 15_000 };
125
+ if (Date.now() < st.next) continue;
126
+ b.set(s.id, { next: Date.now() + st.wait, wait: Math.min(st.wait * 2, 10 * 60_000) });
127
+ this._link(s.id).then(() => b.delete(s.id)).catch(e => this.log.info?.(`[sharing] presence ${s.id}: ${e.message}`));
128
+ }
129
+ this._presenceTimer = setTimeout(() => this._presenceTick(), 15_000);
130
+ this._presenceTimer.unref?.();
131
+ }
132
+
133
+ /** Team chats follow the connection: people and agents of an ended share leave their rooms. */
134
+ _sharesChanged() { try { this.onSharesChanged?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } }
135
+
107
136
  /** The signal server says a share ended (revoke/decline): stop at once. */
108
137
  onShareRevoked(shareId) {
109
138
  this._revokeLocal(shareId);
110
139
  this._links.get(shareId)?.close();
111
140
  this._links.delete(shareId);
112
141
  this._changed();
142
+ this._sharesChanged();
113
143
  }
114
144
 
115
145
  _changed() { this.broadcast(JSON.stringify({ type: 'clawchats', event: 'sharing-changed' })); }
@@ -207,7 +237,7 @@ export class SharingManager {
207
237
  if (!s) throw new Error('No such request');
208
238
  if (!s.requester?.pubKey || !s.requester?.gatewayId) throw new Error("The requester's gateway hasn't connected with sharing support yet");
209
239
  const list = (Array.isArray(agents) ? agents : []).filter(a => a && typeof a.id === 'string' && a.id).map(a => ({ id: a.id, name: String(a.name || a.id).slice(0, 80) }));
210
- if (!list.length) throw new Error('Pick at least one agent');
240
+ // No agents is fine: a connection can be just for chatting (team chats with people).
211
241
  if (!ACCESS_MODES[access]) throw new Error('Unknown access level');
212
242
  // A changed grant keeps the requester key it was first approved for: the signal server can't swap it.
213
243
  const prev = this._db().prepare('SELECT grant_json FROM peer_grants WHERE share_id = ?').get(shareId);
@@ -314,6 +344,43 @@ export class SharingManager {
314
344
 
315
345
  contact(personId) { return this.contacts().find(c => c.personId === personId) || null; }
316
346
 
347
+ /** Whether any share (either direction, verified or not) is active with that gateway. */
348
+ hasShareWith(gatewayId) {
349
+ return this._shares.some(s => s.status === 'active' && this._other(s).gatewayId === gatewayId);
350
+ }
351
+
352
+ /**
353
+ * How a person's name shows next to their agents ("Jarvis · Kamil"): the first name, or the full
354
+ * name when two people here (this gateway's person included) share a first name.
355
+ */
356
+ labelOf(gatewayId, fullName) {
357
+ const first = n => cleanName(String(n || '').trim().split(/[\s@]/)[0], 30) || 'Someone';
358
+ // Everyone known here by id (cached: remoteAgents() calls this per agent, and contacts() verifies grants).
359
+ if (!this._nameCache || Date.now() - this._nameCache.at > 5000) {
360
+ const known = new Map();
361
+ for (const c of this.contacts()) known.set(c.personId, c.name);
362
+ if (this.gatewayId?.()) known.set(this.gatewayId(), this.selfName() || '');
363
+ this._nameCache = { at: Date.now(), known };
364
+ }
365
+ const people = new Map(this._nameCache.known);
366
+ if (gatewayId && fullName) people.set(gatewayId, fullName);
367
+ const mine = first(fullName);
368
+ const clash = [...people].some(([id, n]) => id !== gatewayId && first(n).toLowerCase() === mine.toLowerCase());
369
+ return clash ? cleanName(fullName, 60) || mine : mine;
370
+ }
371
+
372
+ /** The room (and who asked) behind a guest session of this gateway, or null. */
373
+ guestSessionOf(key) {
374
+ if (!this._guestKeys) {
375
+ this._guestKeys = new Map();
376
+ for (const r of this._db().prepare('SELECT share_id, room_id, session_key FROM peer_sessions').all()) {
377
+ const g = this._grant(r.share_id);
378
+ if (g?.grant.requesterGatewayId) this._guestKeys.set(r.session_key, { requesterGatewayId: g.grant.requesterGatewayId, roomId: r.room_id, shareId: r.share_id });
379
+ }
380
+ }
381
+ return this._guestKeys.get(key) || null;
382
+ }
383
+
317
384
  /** The gateway id of whoever owns a shared agent ('peer:<share>:<agent>'), or null. */
318
385
  ownerOf(remoteAgentId) {
319
386
  const id = SharingManager.parseRemoteId(remoteAgentId);
@@ -451,6 +518,7 @@ export class SharingManager {
451
518
  await create(`${name} · ${roomTitle} · ${tag}-${crypto.randomBytes(2).toString('hex')}`);
452
519
  }
453
520
  db.prepare('INSERT OR REPLACE INTO peer_sessions (share_id, room_id, agent_id, session_key) VALUES (?, ?, ?, ?)').run(shareId, roomId, agentId, key);
521
+ this._guestKeys = null;
454
522
  return key;
455
523
  }
456
524
 
@@ -506,7 +574,7 @@ export class SharingManager {
506
574
  for (const s of this._shares) {
507
575
  const grant = this._verifiedGrant(s);
508
576
  if (!grant) continue;
509
- const owner = firstName(s.owner);
577
+ const owner = this.labelOf(s.owner?.gatewayId, s.owner?.name || s.owner?.email) || firstName(s.owner);
510
578
  for (const a of grant.agents) {
511
579
  if (typeof a?.id !== 'string' || !a.id || a.id.length > 100) continue;
512
580
  out.push({ agentId: `peer:${s.id}:${a.id}`, name: `${cleanName(a.name || a.id) || 'Agent'} · ${owner}`, ownerName: owner, shareId: s.id, remoteId: a.id });
@@ -611,6 +679,8 @@ export class SharingManager {
611
679
  }
612
680
 
613
681
  close() {
682
+ this._closed = true;
683
+ clearTimeout(this._presenceTimer);
614
684
  for (const l of this._links.values()) l.close();
615
685
  for (const l of this._served) l.close();
616
686
  this._links.clear();
@@ -422,3 +422,29 @@ test('a peer request cannot pick the owner-room note', async () => {
422
422
  await link.request('turn', { turnId: 't1', agentId: 'jarvis-guest', roomId: 'r', message: 'hi', inOwnerRoom: true }, { timeoutMs: 5000 });
423
423
  assert.match(s.ownerCalls.find(c => c.method === 'chat.send').params.message, /you are answering Houman S's team chat/);
424
424
  });
425
+
426
+ test('presence: the side that asked keeps a link open, so the side that granted can reach it (room copies)', async () => {
427
+ const s = setup();
428
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
429
+ s.activate();
430
+ for (let i = 0; i < 20 && !s.req._links.get('sh1')?.ready; i++) await new Promise(r => setTimeout(r, 25));
431
+ assert.ok(s.req._links.get('sh1')?.ready, 'requester dialled without anyone using an agent');
432
+ // The owner can now call the requester over that link (what room.sync does).
433
+ let got = null;
434
+ s.req._links.get('sh1').handle('room.sync', async p => { got = p; return { ok: true }; });
435
+ const res = await s.owner.personRequest('gwH', 'room.sync', { roomId: 'r1' });
436
+ assert.deepEqual(res, { ok: true });
437
+ assert.equal(got.roomId, 'r1');
438
+ s.req.close(); s.owner.close();
439
+ });
440
+
441
+ test('names next to agents: first name, full name when two people here share it', () => {
442
+ const s = setup();
443
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
444
+ s.activate();
445
+ assert.equal(s.req.labelOf('gwK', 'Kamil Gronowski'), 'Kamil');
446
+ // This gateway's own person is "Houman S": another Houman next to their agents shows in full, and so does ours.
447
+ assert.equal(s.req.labelOf('gwX', 'Houman Test'), 'Houman Test');
448
+ assert.equal(s.req.labelOf('gwH', 'Houman S'), 'Houman', 'a person never clashes with themselves');
449
+ s.req.close(); s.owner.close();
450
+ });
@@ -16,11 +16,18 @@
16
16
  // `agent:<id>:<project>:chat:<id>` (legacy ClawChats). Everything else is hidden.
17
17
  // Team chat working sessions (server/team.js) are hidden too, but their run events are
18
18
  // forwarded: the room shows each agent's reply streaming.
19
+ //
20
+ // Spawned children (sessions_spawn: hidden `agent:<id>:subagent:<id>` runs and `visible: true`
21
+ // dashboard sessions) are visible when their parent chain reaches a visible chat; the browser
22
+ // nests them under it (Control UI session tree). Their rows carry `ccParentKey`, the parent the
23
+ // lens resolved, so the browser never re-derives the placement rule.
19
24
 
20
25
  const DASHBOARD_KEY = /^agent:[^:]+:dashboard:[^:]+$/;
21
26
  const LEGACY_CHAT_KEY = /^agent:[^:]+:[^:]+:chat:[^:]+$/;
22
27
  const UTILITY_MARK = '__clawchats_';
23
28
  const MAIN_SESSION_KEY = /^agent:[^:]+:main$/;
29
+ const SUBAGENT_KEY = /^agent:[^:]+:subagent:[^:]+$/;
30
+ const MAX_CHILD_DEPTH = 8;
24
31
 
25
32
  // Session row fields the browser needs. Anything else stays on the connector side.
26
33
  export const ROW_FIELDS = new Set([
@@ -32,12 +39,14 @@ export const ROW_FIELDS = new Set([
32
39
  'status', 'hasActiveRun', 'activeRunIds', 'lastRunId', 'lastRunError', 'endedAt', 'agentStatus',
33
40
  'model', 'modelProvider', 'thinkingLevel', 'contextTokens', 'totalTokens', 'totalTokensFresh',
34
41
  'inputTokens', 'outputTokens', 'permissionMode', 'workspaceDir', 'contextBudgetStatus', 'fastMode', 'effectiveFastMode',
42
+ 'startedAt', 'runtimeMs', 'ccParentKey',
35
43
  ]);
36
44
 
37
45
  // `sessions.changed` envelope fields (snapshot fields are spread next to these).
38
46
  const EVENT_ENVELOPE = new Set(['sessionKey', 'agentId', 'reason', 'phase', 'ts', 'messageId', 'catalogChanged']);
39
47
 
40
- const LIST_DEFAULTS = { excludeSubagents: true, excludeCron: true, excludeSystem: true };
48
+ // Subagent runs are listed: the lens keeps the ones nested under a visible chat.
49
+ const LIST_DEFAULTS = { excludeSubagents: false, excludeCron: true, excludeSystem: true };
41
50
 
42
51
  export function isUtilityKey(key) {
43
52
  return typeof key === 'string' && key.includes(UTILITY_MARK);
@@ -47,6 +56,18 @@ export function isCandidateKey(key) {
47
56
  return typeof key === 'string' && !isUtilityKey(key) && (DASHBOARD_KEY.test(key) || LEGACY_CHAT_KEY.test(key));
48
57
  }
49
58
 
59
+ /** Keys that can be a nested child: chat-shaped sessions and subagent runs. */
60
+ function isChildCandidateKey(key) {
61
+ return isCandidateKey(key) || (typeof key === 'string' && SUBAGENT_KEY.test(key));
62
+ }
63
+
64
+ /** The parent a hidden row nests under (Control UI resolveUiSessionNavigationParentKey), if any. */
65
+ function nestingParent(row) {
66
+ if (row.kind === 'global' || row.kind === 'unknown' || row.kind === 'group') return null;
67
+ const parent = row.parentSessionKey || row.spawnedBy;
68
+ return typeof parent === 'string' && parent && !MAIN_SESSION_KEY.test(parent) ? parent : null;
69
+ }
70
+
50
71
  // ── Visibility: port of the Control UI sidebar rule ──────────────────
51
72
  // ui/src/components/app-sidebar-session-parent.ts resolveSidebarSessionParentKey
52
73
  // ui/src/lib/sessions/navigation.ts sessionMatchesVisibleSessionScope
@@ -127,6 +148,7 @@ export class SessionLens {
127
148
  this.team = team;
128
149
  this.log = logger;
129
150
  this.hidden = new Set(); // candidate-shaped keys a row revealed as not a user chat
151
+ this.parents = new Map(); // child key -> parent key (nested children; visible when the chain reaches a chat)
130
152
  this.pending = new Map(); // browser req id -> { method, params }
131
153
  // Chats a browser opened with sessions.messages.subscribe (Control UI: one per selected
132
154
  // chat). session.message is forwarded only for these. subscriptionId -> session key.
@@ -137,17 +159,48 @@ export class SessionLens {
137
159
 
138
160
  /** Learn from a (possibly partial) row; returns whether the session is visible. */
139
161
  observe(key, row) {
140
- if (!isCandidateKey(key)) return false;
141
- const verdict = rowVerdict(row);
142
- if (verdict === true) this.hidden.add(key);
143
- else if (verdict === false) this.hidden.delete(key);
162
+ if (!isChildCandidateKey(key)) return false;
163
+ const verdict = SUBAGENT_KEY.test(key) ? true : rowVerdict(row);
164
+ if (verdict === true) {
165
+ this.hidden.add(key);
166
+ const parent = row && typeof row === 'object' && 'kind' in row ? nestingParent(row) : undefined;
167
+ if (parent) this.parents.set(key, parent);
168
+ else if (parent === null) this.parents.delete(key);
169
+ } else if (verdict === false) {
170
+ this.hidden.delete(key);
171
+ this.parents.delete(key);
172
+ }
144
173
  return this.isVisible(key);
145
174
  }
146
175
 
147
176
  isVisible(key) {
177
+ return this._isTopLevel(key) || !!this.parentOf(key);
178
+ }
179
+
180
+ _isTopLevel(key) {
148
181
  return isCandidateKey(key) && !this.hidden.has(key) && !this.team?.isWorkKey(key);
149
182
  }
150
183
 
184
+ /** The parent a visible nested child shows under, or null (not a child, or its chain never reaches a chat). */
185
+ parentOf(key) {
186
+ const parent = this.parents.get(key);
187
+ if (!parent || this.team?.isWorkKey(key)) return null;
188
+ let cur = parent;
189
+ for (let depth = 0; depth < MAX_CHILD_DEPTH; depth++) {
190
+ if (this._isTopLevel(cur)) return parent;
191
+ cur = this.parents.get(cur);
192
+ if (!cur || cur === key) return null;
193
+ }
194
+ return null;
195
+ }
196
+
197
+ /** Row/event fields plus the resolved parent link of a nested child. */
198
+ _withParent(key, out) {
199
+ const parent = this.parentOf(key);
200
+ if (parent) out.ccParentKey = parent;
201
+ return out;
202
+ }
203
+
151
204
  /** chat/agent run events: visible chats, team chat working sessions, utility sessions. */
152
205
  forwardsRunEvent(key) {
153
206
  return isUtilityKey(key) || this.isVisible(key) || !!this.team?.isWorkKey(key);
@@ -176,9 +229,14 @@ export class SessionLens {
176
229
  if (payload.reason === 'delete' && this.team) {
177
230
  try { this.team.onSessionDeleted(key); } catch (e) { this.log.warn?.(`[lens] team delete: ${e.message}`); }
178
231
  }
232
+ if (payload.reason === 'patch' && this.team?.onSessionPatched) {
233
+ this.team.onSessionPatched(key).catch(e => this.log.warn?.(`[lens] team patch: ${e.message}`));
234
+ }
179
235
  if (!this.observe(key, payload.session || payload)) return null;
180
236
  if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
181
- return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) };
237
+ const out = trimEvent(payload);
238
+ if (payload.reason !== 'delete') this._withParent(key, out.session || out);
239
+ return { type: 'event', event: 'sessions.changed', payload: out };
182
240
  }
183
241
 
184
242
  /** `session.message` (live transcript entry). Forwarded only for watched visible chats. */
@@ -271,9 +329,11 @@ export class SessionLens {
271
329
  let legacy = null;
272
330
  try { legacy = this.extras?.getLegacyCreatedAt?.(); } catch (e) { this.log.warn?.(`[lens] legacy dates: ${e.message}`); }
273
331
  const out = [];
332
+ // Learn the whole page first: a child may be listed before its parent.
333
+ for (const row of rows || []) if (row) this.observe(row.key, row);
274
334
  for (const row of rows || []) {
275
- if (!row || !this.observe(row.key, row)) continue;
276
- const trimmed = trimRow(row);
335
+ if (!row || !this.isVisible(row.key)) continue;
336
+ const trimmed = this._withParent(row.key, trimRow(row));
277
337
  if (!trimmed.createdAt && legacy?.has(row.key)) trimmed.createdAt = legacy.get(row.key);
278
338
  out.push(trimmed);
279
339
  }
@@ -20,7 +20,7 @@ test('key shapes', () => {
20
20
  assert.equal(isCandidateKey(k), false, k);
21
21
  });
22
22
 
23
- test('child sessions stay hidden once a row revealed them, even for partial events', () => {
23
+ test('a child of an unresolved parent stays hidden, even for partial events', () => {
24
24
  const { l } = lens();
25
25
  assert.equal(l.sessionsChanged({ sessionKey: CHILD, reason: 'create', parentSessionKey: CHAT, label: 'x' }), null);
26
26
  assert.equal(l.sessionsChanged({ sessionKey: CHILD, phase: 'message', ts: 1 }), null);
@@ -47,7 +47,7 @@ test('run events: visible chats and utility sessions only', () => {
47
47
  test('browser sessions.list gets defaults and a filtered, trimmed response', () => {
48
48
  const { l } = lens();
49
49
  const out = JSON.parse(l.outbound(JSON.stringify({ type: 'req', id: 'r1', method: 'sessions.list', params: { limit: 50 } })));
50
- assert.deepEqual(out.params, { excludeSubagents: true, excludeCron: true, excludeSystem: true, limit: 50 });
50
+ assert.deepEqual(out.params, { excludeSubagents: false, excludeCron: true, excludeSystem: true, limit: 50 });
51
51
  assert.ok(l.ownsResponse('r1'));
52
52
  const res = l.response({ type: 'res', id: 'r1', ok: true, payload: {
53
53
  ts: 1, count: 4, totalCount: 4, hasMore: false, nextOffset: null, owners: [{}],
@@ -140,8 +140,8 @@ test('forks of chats are chats (edit/regen branches)', () => {
140
140
  assert.ok(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:f1', reason: 'create', kind: 'direct', forkSource: { sessionKey: LEGACY, sessionId: 's' } }));
141
141
  // fork of a dashboard chat: inherits the main link
142
142
  assert.ok(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:f2', reason: 'create', kind: 'direct', createdVia: 'operator', parentSessionKey: 'agent:main:main', spawnDepth: 0, forkSource: { sessionKey: CHAT, sessionId: 's' } }));
143
- // a fork nested under another chat is still a child
144
- assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:f3', reason: 'create', kind: 'direct', parentSessionKey: CHAT, forkSource: { sessionKey: LEGACY, sessionId: 's' } }), null); // parent is not the fork source
143
+ // a fork nested under another chat is still a child: shown nested under that chat
144
+ assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:f3', reason: 'create', kind: 'direct', parentSessionKey: CHAT, forkSource: { sessionKey: LEGACY, sessionId: 's' } }).payload.ccParentKey, CHAT); // parent is not the fork source
145
145
  });
146
146
 
147
147
  test('sessions.fork branches (parent = source chat) are top-level chats', () => {
@@ -150,7 +150,8 @@ test('sessions.fork branches (parent = source chat) are top-level chats', () =>
150
150
  assert.ok(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:br', reason: 'create', kind: 'direct', createdVia: 'operator', parentSessionKey: SRC, forkedFromParent: true, forkSource: { sessionKey: SRC, sessionId: 's', entryId: 'e' } }));
151
151
  assert.ok(l.forwardsRunEvent('agent:main:dashboard:br'));
152
152
  // a child whose parent is a chat but that is not a fork of it stays nested
153
- assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:kid', reason: 'create', kind: 'direct', parentSessionKey: SRC }), null);
153
+ assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:kid', reason: 'create', kind: 'direct', parentSessionKey: SRC }).payload.ccParentKey, SRC);
154
+ assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:br', reason: 'patch', label: 'x' }).payload.ccParentKey, undefined); // the branch itself is top level
154
155
  // fork of a channel session is not a chat
155
156
  assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:br2', reason: 'create', kind: 'direct', parentSessionKey: DISCORD, forkSource: { sessionKey: DISCORD } }), null);
156
157
  });
@@ -177,3 +178,59 @@ test('listed rows without createdAt get the legacy creation time; gateway values
177
178
  ] } });
178
179
  assert.deepEqual(res.payload.sessions.map(s => s.createdAt), [111, 999]);
179
180
  });
181
+
182
+ const RUN = 'agent:main:subagent:run1';
183
+
184
+ test('spawned children of a visible chat are visible, nested via ccParentKey', () => {
185
+ const { l } = lens();
186
+ l.observe(CHAT, { key: CHAT, kind: 'direct', createdVia: 'operator', parentSessionKey: 'agent:main:main', spawnDepth: 0 });
187
+ // hidden run (subagent key)
188
+ const f = l.sessionsChanged({ sessionKey: RUN, reason: 'create', session: { key: RUN, kind: 'direct', spawnedBy: CHAT, parentSessionKey: CHAT, spawnDepth: 1, label: 'Review', owner: {} } });
189
+ assert.deepEqual(f.payload.session, { key: RUN, kind: 'direct', label: 'Review', ccParentKey: CHAT });
190
+ // later partial events keep the link
191
+ assert.equal(l.sessionsChanged({ sessionKey: RUN, phase: 'message', ts: 2 }).payload.ccParentKey, CHAT);
192
+ assert.ok(l.forwardsRunEvent(RUN));
193
+ // visible spawn (dashboard key)
194
+ const V = 'agent:main:dashboard:vis';
195
+ assert.ok(l.sessionsChanged({ sessionKey: V, reason: 'create', kind: 'direct', createdVia: 'spawn', spawnedBy: CHAT, parentSessionKey: CHAT, spawnDepth: 1 }));
196
+ assert.equal(l.parentOf(V), CHAT);
197
+ // grandchild through a run
198
+ const G = 'agent:main:subagent:run2';
199
+ assert.equal(l.sessionsChanged({ sessionKey: G, reason: 'create', kind: 'direct', spawnedBy: RUN, spawnDepth: 2 }).payload.ccParentKey, RUN);
200
+ });
201
+
202
+ test('children outside ClawChats chats stay hidden', () => {
203
+ const { l } = lens();
204
+ assert.equal(l.sessionsChanged({ sessionKey: RUN, reason: 'create', kind: 'direct', spawnedBy: 'agent:main:main', parentSessionKey: 'agent:main:main', spawnDepth: 1 }), null);
205
+ assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:subagent:d', reason: 'create', kind: 'direct', spawnedBy: DISCORD, spawnDepth: 1 }), null);
206
+ assert.equal(l.forwardsRunEvent(RUN), false);
207
+ // parent chat hidden (e.g. group kind) -> its children too
208
+ l.observe(CHAT, { key: CHAT, kind: 'group' });
209
+ assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:subagent:e', reason: 'create', kind: 'direct', spawnedBy: CHAT, spawnDepth: 1 }), null);
210
+ // a cycle never resolves
211
+ l.observe('agent:main:subagent:x', { kind: 'direct', spawnedBy: 'agent:main:subagent:y' });
212
+ l.observe('agent:main:subagent:y', { kind: 'direct', spawnedBy: 'agent:main:subagent:x' });
213
+ assert.equal(l.parentOf('agent:main:subagent:x'), null);
214
+ });
215
+
216
+ test('list responses keep children whose parent is listed later on the page', () => {
217
+ const { l } = lens();
218
+ l.outbound(JSON.stringify({ type: 'req', id: 'c1', method: 'sessions.list', params: {} }));
219
+ const res = l.response({ type: 'res', id: 'c1', ok: true, payload: { sessions: [
220
+ { key: RUN, kind: 'direct', spawnedBy: CHAT, parentSessionKey: CHAT, spawnDepth: 1, label: 'r', runtimeMs: 5, startedAt: 1 },
221
+ { key: CHAT, kind: 'direct', createdVia: 'operator', parentSessionKey: 'agent:main:main', spawnDepth: 0, label: 'c' },
222
+ { key: 'agent:main:subagent:other', kind: 'direct', spawnedBy: 'agent:main:main', spawnDepth: 1 },
223
+ ] } });
224
+ assert.deepEqual(res.payload.sessions, [
225
+ { key: RUN, kind: 'direct', label: 'r', runtimeMs: 5, startedAt: 1, ccParentKey: CHAT },
226
+ { key: CHAT, kind: 'direct', label: 'c' },
227
+ ]);
228
+ });
229
+
230
+ test('a patched session tells the team coordinator (a renamed room reaches its copies)', async () => {
231
+ const patched = [];
232
+ const { l } = lens({});
233
+ l.team = { isWorkKey: () => false, onSessionPatched: async key => { patched.push(key); } };
234
+ l.sessionsChanged({ sessionKey: CHAT, reason: 'patch', label: 'New name' });
235
+ assert.deepEqual(patched, [CHAT]);
236
+ });
@@ -16,6 +16,9 @@
16
16
  // team_rooms.host_* a live copy of someone else's room (this gateway is a member, not the host):
17
17
  // host_gateway_id/host_room/host_name; replica_json = the host's members and people
18
18
  // team_mirror host entry id -> local message id in a live copy (each host entry injected once)
19
+ // team_entries.host_ts/owner_id/ref a mirrored entry's original time, its agent's owner and room-wide agent ref
20
+ // team_entries author_type 'system': a line like "Kamil joined" (same on every screen)
21
+ // team_rooms.mention_only agents answer only when @mentioned (human chats with silent agents)
19
22
 
20
23
  const DISCUSS_ROUNDS = 3; // default; each room can set 1..MAX_ROUNDS
21
24
  const MAX_ROUNDS = 10;
@@ -24,6 +27,7 @@ function roomRow(r, members, people = []) {
24
27
  return {
25
28
  roomKey: r.room_key,
26
29
  discuss: !!r.discuss,
30
+ mentionOnly: !!r.mention_only,
27
31
  rounds: r.rounds || DISCUSS_ROUNDS,
28
32
  sourceKey: r.source_key || null,
29
33
  createdAt: r.created_at,
@@ -49,6 +53,11 @@ export function createTeamStore(getGlobalDb) {
49
53
  if (!cols('team_members').has('history')) g.exec('ALTER TABLE team_members ADD COLUMN history TEXT');
50
54
  const rc = cols('team_rooms');
51
55
  for (const c of ['host_gateway_id', 'host_room', 'host_name', 'host_ended', 'replica_json']) if (!rc.has(c)) g.exec(`ALTER TABLE team_rooms ADD COLUMN ${c} TEXT`);
56
+ if (!rc.has('mention_only')) g.exec('ALTER TABLE team_rooms ADD COLUMN mention_only INTEGER NOT NULL DEFAULT 0');
57
+ const ec = cols('team_entries');
58
+ if (!ec.has('host_ts')) g.exec('ALTER TABLE team_entries ADD COLUMN host_ts INTEGER');
59
+ if (!ec.has('owner_id')) g.exec('ALTER TABLE team_entries ADD COLUMN owner_id TEXT');
60
+ if (!ec.has('ref')) g.exec('ALTER TABLE team_entries ADD COLUMN ref TEXT');
52
61
  g.exec(`CREATE TABLE IF NOT EXISTS team_people (room_key TEXT NOT NULL, person_id TEXT NOT NULL, name TEXT NOT NULL, email TEXT, history_from INTEGER NOT NULL DEFAULT 0, added_at INTEGER NOT NULL, removed INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (room_key, person_id))`);
53
62
  g.exec(`CREATE TABLE IF NOT EXISTS team_mirror (room_key TEXT NOT NULL, host_entry_id TEXT NOT NULL, message_id TEXT, PRIMARY KEY (room_key, host_entry_id))`);
54
63
  ready = true;
@@ -72,12 +81,12 @@ export function createTeamStore(getGlobalDb) {
72
81
  },
73
82
 
74
83
  /** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
75
- createRoom(roomKey, memberList, { discuss = false, sourceKey = null } = {}) {
84
+ createRoom(roomKey, memberList, { discuss = false, sourceKey = null, mentionOnly = false } = {}) {
76
85
  const g = db();
77
86
  const now = Date.now();
78
87
  g.exec('BEGIN');
79
88
  try {
80
- g.prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(roomKey, discuss ? 1 : 0, sourceKey, now, now);
89
+ g.prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at, mention_only) VALUES (?, ?, ?, ?, ?, ?)').run(roomKey, discuss ? 1 : 0, sourceKey, now, now, mentionOnly ? 1 : 0);
81
90
  memberList.forEach((m, i) => g.prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position) VALUES (?, ?, ?, ?, ?)').run(roomKey, m.agentId, m.workKey || null, m.seenAt || 0, i));
82
91
  g.exec('COMMIT');
83
92
  } catch (e) { g.exec('ROLLBACK'); throw e; }
@@ -158,6 +167,10 @@ export function createTeamStore(getGlobalDb) {
158
167
  db().prepare('UPDATE team_rooms SET discuss = ?, updated_at = ? WHERE room_key = ?').run(discuss ? 1 : 0, Date.now(), roomKey);
159
168
  },
160
169
 
170
+ setMentionOnly(roomKey, on) {
171
+ db().prepare('UPDATE team_rooms SET mention_only = ?, updated_at = ? WHERE room_key = ?').run(on ? 1 : 0, Date.now(), roomKey);
172
+ },
173
+
161
174
  setRounds(roomKey, rounds) {
162
175
  db().prepare('UPDATE team_rooms SET rounds = ?, updated_at = ? WHERE room_key = ?').run(rounds, Date.now(), roomKey);
163
176
  },
@@ -189,18 +202,22 @@ export function createTeamStore(getGlobalDb) {
189
202
  * type 'user' (this gateway's own person), 'person' (someone else; agentId holds their person id
190
203
  * and actingFor their name), or 'agent' (actingFor: whose request it answered, if not its owner's).
191
204
  */
192
- recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null }) {
193
- db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at, acting_for) VALUES (?, ?, ?, ?, ?, ?)')
194
- .run(roomKey, messageId, ['user', 'person'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor);
205
+ recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null, ts = null, ownerId = null, ref = null }) {
206
+ db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at, acting_for, host_ts, owner_id, ref) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
207
+ .run(roomKey, messageId, ['user', 'person', 'system'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor, ts || null, ownerId, ref);
195
208
  },
196
209
 
197
- /** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } | { type: 'person', personId, name } } */
210
+ /**
211
+ * { [messageId]: { type: 'user'|'agent'|'system', agentId, actingFor?, ts?, ownerId?, ref? } | { type: 'person', personId, name } }
212
+ * ts: the entry's original time when this is a copy of someone else's room.
213
+ */
198
214
  authors(roomKey) {
199
215
  const out = {};
200
- for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for FROM team_entries WHERE room_key = ?').all(roomKey)) {
216
+ for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for, host_ts, owner_id, ref FROM team_entries WHERE room_key = ?').all(roomKey)) {
217
+ const extra = { ...(r.host_ts ? { ts: r.host_ts } : {}), ...(r.owner_id ? { ownerId: r.owner_id } : {}), ...(r.ref ? { ref: r.ref } : {}) };
201
218
  out[r.message_id] = r.author_type === 'person'
202
- ? { type: 'person', personId: r.agent_id, name: r.acting_for }
203
- : { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}) };
219
+ ? { type: 'person', personId: r.agent_id, name: r.acting_for, ...extra }
220
+ : { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}), ...extra };
204
221
  }
205
222
  return out;
206
223
  },