@clawchatsai/connector 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.34",
3
+ "version": "0.1.36",
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
@@ -247,7 +247,7 @@ export function createApp(config = {}) {
247
247
  if (method === 'GET' && urlPath === '/api/sharing') {
248
248
  // Enabled once the signal server has sharing on for this account (it then sends share lists).
249
249
  if (!sharing?.serverEnabled) return send(res, 200, { enabled: false, shares: [], remoteAgents: [] });
250
- return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents() });
250
+ return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents(), contacts: sharing.contacts(), me: sharing.gatewayId?.() || null });
251
251
  }
252
252
  if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/approve'))) {
253
253
  if (!sharing) return sendError(res, 404, 'Sharing is not available');
@@ -286,17 +286,35 @@ export function createApp(config = {}) {
286
286
  if ((p = matchRoute(method, urlPath, 'PATCH /api/team/:room'))) {
287
287
  const body = await parseBody(req);
288
288
  let room = team.room(p.room);
289
- if (room && body.discuss !== undefined) room = team.setDiscuss(p.room, body.discuss);
289
+ if (room && body.discuss !== undefined) {
290
+ try { room = team.setDiscuss(p.room, body.discuss); } catch (e) { return sendError(res, 400, e.message); }
291
+ }
290
292
  if (room && body.rounds !== undefined) {
291
293
  try { room = team.setRounds(p.room, body.rounds); } catch (e) { return sendError(res, 400, e.message); }
292
294
  }
293
295
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
294
296
  }
297
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/people'))) {
298
+ const { personId, history } = await parseBody(req);
299
+ if (typeof personId !== 'string' || !personId) return sendError(res, 400, 'personId is required');
300
+ try {
301
+ const room = await team.addPerson(p.room, personId, { history });
302
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
303
+ } catch (e) { return sendError(res, 400, e.message); }
304
+ }
305
+ if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/people/:personId'))) {
306
+ const room = team.removePerson(p.room, p.personId);
307
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat you host');
308
+ }
309
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/leave'))) {
310
+ try { return send(res, 200, { room: await team.leave(p.room) }); }
311
+ catch (e) { return sendError(res, 400, e.message); }
312
+ }
295
313
  if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
296
- const { agentId } = await parseBody(req);
314
+ const { agentId, history } = await parseBody(req);
297
315
  if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
298
316
  try {
299
- const room = await team.addAgent(p.room, agentId);
317
+ const room = await team.addAgent(p.room, agentId, { history });
300
318
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
301
319
  } catch (e) { return sendError(res, 400, e.message); }
302
320
  }
@@ -34,7 +34,7 @@ export const defangLocalPaths = text => text
34
34
  .replace(/(^|[\s"'`(])(?=(?:\.\.?\/|[~/]|[A-Za-z]:[\\/])[^\s"'`()[\]]*\.[A-Za-z0-9])/g, '$1\u200b');
35
35
  const GUEST_NOTE = name => `(Shared session: you are answering ${name}'s team chat on behalf of your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
36
36
  // The same agent in its owner's own team chat, answering another person's agent (localTurnFor).
37
- const ACTING_FOR_NOTE = name => `(Shared session: in your owner's team chat, you are answering ${name}'s agent, so you act for ${name}, not for your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
37
+ const ACTING_FOR_NOTE = (name, byPerson) => `(Shared session: in your owner's team chat, you are answering ${byPerson ? name : `${name}'s agent`}, so you act for ${name}, not for your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
38
38
 
39
39
  const today = () => new Date().toISOString().slice(0, 10);
40
40
  /** A name that came from the other side, safe to show and to use as a chat label (no brackets, newlines, controls). */
@@ -94,12 +94,14 @@ 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
+ const first = !this.serverEnabled;
97
98
  this.serverEnabled = true;
98
99
  this._shares = Array.isArray(shares) ? shares : [];
99
100
  const live = new Set(this._shares.filter(s => s.status === 'active').map(s => s.id));
100
101
  for (const [shareId, link] of this._links) if (!live.has(shareId)) { link.close(); this._links.delete(shareId); }
101
102
  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);
102
103
  this._changed();
104
+ if (first) setImmediate(() => { try { this.onFirstShares?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } });
103
105
  }
104
106
 
105
107
  /** The signal server says a share ended (revoke/decline): stop at once. */
@@ -260,11 +262,97 @@ export class SharingManager {
260
262
  this._served.add(link);
261
263
  link.on('closed', () => this._served.delete(link));
262
264
  link.handle('agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] }));
263
- link.handle('turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false }, emit)); // only localTurnFor sets it
265
+ link.handle('turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false, byPerson: false }, emit)); // only localTurnFor sets these
264
266
  link.handle('abort', async p => this._guestAbort(shareId, p?.turnId));
267
+ this._wireRooms(link, requesterGatewayId);
265
268
  return link;
266
269
  }
267
270
 
271
+ /**
272
+ * Team chats with people (specs/sharing-people.md) travel over whichever link the two gateways
273
+ * have, in either direction: the room host pushes its room to members (room.sync), members post,
274
+ * leave and ask for a fresh copy (room.post / room.leave / room.fetch). `onRoom` (TeamCoordinator)
275
+ * decides; it gets the other side's gateway id, which the link authenticated.
276
+ */
277
+ _wireRooms(link, otherGatewayId) {
278
+ for (const method of ['room.sync', 'room.post', 'room.leave', 'room.fetch']) {
279
+ link.handle(method, async p => {
280
+ if (!this.onRoom) throw Object.assign(new Error('team chats are not available'), { code: 'unavailable' });
281
+ return this.onRoom(method, p || {}, otherGatewayId);
282
+ });
283
+ }
284
+ const ready = () => { try { this.onPeerReady?.(otherGatewayId); } catch (e) { this.log.warn?.(`[sharing] peer ready: ${e.message}`); } };
285
+ if (link.ready) setImmediate(ready); else link.once('ready', ready);
286
+ }
287
+
288
+ // ── People (contacts) ──────────────────────────────────────────────
289
+
290
+ /** The other person of a share, as this side sees them: { gatewayId, name, email }. */
291
+ _other(s) {
292
+ const p = s.as === 'owner' ? s.requester : s.owner;
293
+ return { gatewayId: p?.gatewayId || null, name: cleanName(p?.name || p?.email, 60) || 'Someone', email: p?.email || null };
294
+ }
295
+
296
+ /**
297
+ * People this gateway is connected with (an active share either way), by their gateway id:
298
+ * [{ personId, name, email, shareIds }]. A team chat here can include any of them.
299
+ */
300
+ contacts() {
301
+ const out = new Map();
302
+ for (const s of this._shares) {
303
+ if (s.status !== 'active') continue;
304
+ if (s.as === 'requester' && !this._verifiedGrant(s)) continue;
305
+ if (s.as === 'owner' && !this._grant(s.id)) continue;
306
+ const o = this._other(s);
307
+ if (!o.gatewayId) continue;
308
+ const c = out.get(o.gatewayId) || { personId: o.gatewayId, name: o.name, email: o.email, shareIds: [] };
309
+ c.shareIds.push(s.id);
310
+ out.set(o.gatewayId, c);
311
+ }
312
+ return [...out.values()];
313
+ }
314
+
315
+ contact(personId) { return this.contacts().find(c => c.personId === personId) || null; }
316
+
317
+ /** The gateway id of whoever owns a shared agent ('peer:<share>:<agent>'), or null. */
318
+ ownerOf(remoteAgentId) {
319
+ const id = SharingManager.parseRemoteId(remoteAgentId);
320
+ return (id && this._shares.find(s => s.id === id.shareId && s.as === 'requester')?.owner?.gatewayId) || null;
321
+ }
322
+
323
+ /** Whether this gateway owns (granted) that share. */
324
+ ownsShare(shareId) { return !!this._grant(shareId); }
325
+
326
+ /** This gateway's person, as the others see them (from any share). */
327
+ selfName() {
328
+ for (const s of this._shares) {
329
+ const me = s.as === 'owner' ? s.owner : s.requester;
330
+ if (me?.name || me?.email) return cleanName(me.name || me.email, 60);
331
+ }
332
+ return null;
333
+ }
334
+
335
+ /** An open link with that person's gateway (either direction), else dial one this side may open. */
336
+ async _personLink(personId) {
337
+ for (const [shareId, link] of this._links) {
338
+ const s = this._shares.find(x => x.id === shareId);
339
+ if (link.ready && !link.closed && s && this._other(s).gatewayId === personId) return link;
340
+ }
341
+ for (const link of this._served) {
342
+ if (link.ready && !link.closed && this._grant(link.shareId)?.grant.requesterGatewayId === personId) return link;
343
+ }
344
+ const dial = this._shares.find(s => s.as === 'requester' && s.status === 'active' && s.owner?.gatewayId === personId && this._verifiedGrant(s));
345
+ if (!dial) throw Object.assign(new Error(`Can't reach them until they're online`), { code: 'unreachable' });
346
+ return this._link(dial.id);
347
+ }
348
+
349
+ /** Call a room method on a person's gateway. */
350
+ async personRequest(personId, method, params, { timeoutMs = 60_000 } = {}) {
351
+ if (!this.contact(personId)) throw Object.assign(new Error('Not connected with them'), { code: 'not_connected' });
352
+ const link = await this._personLink(personId);
353
+ return link.request(method, params, { timeoutMs });
354
+ }
355
+
268
356
  /** Run one guest turn in this gateway's session for (share, room, agent); stream text back. */
269
357
  async _guestTurn(shareId, p, emit) {
270
358
  const g = this._grant(shareId);
@@ -322,7 +410,7 @@ export class SharingManager {
322
410
  try {
323
411
  if (!this._grant(shareId)) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' }); // revoked while setting up
324
412
  await this.request('chat.send', {
325
- sessionKey, message: defangLocalPaths(`${(p.inOwnerRoom ? ACTING_FOR_NOTE : GUEST_NOTE)(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
413
+ sessionKey, message: defangLocalPaths(`${p.inOwnerRoom ? ACTING_FOR_NOTE(name, p.byPerson) : GUEST_NOTE(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
326
414
  timeoutMs: TURN_TIMEOUT_MS, suppressCommandInterpretation: true,
327
415
  expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
328
416
  }, 30_000);
@@ -444,6 +532,7 @@ export class SharingManager {
444
532
  await new Promise((resolve, reject) => { link.once('ready', resolve); link.once('closed', () => reject(new Error(`Couldn't reach ${firstName(s.owner)}'s gateway`))); });
445
533
  this._links.set(shareId, link);
446
534
  link.on('closed', () => { if (this._links.get(shareId) === link) this._links.delete(shareId); });
535
+ this._wireRooms(link, s.owner?.gatewayId);
447
536
  return link;
448
537
  })().finally(() => this._linking.delete(shareId));
449
538
  this._linking.set(shareId, p);
@@ -468,11 +557,18 @@ export class SharingManager {
468
557
  * active share where they asked for this gateway's agents, matched by their gateway (else email).
469
558
  * Returns { shareId, grant } or null when this gateway shares nothing with them.
470
559
  */
471
- _grantToOwnerOf(remoteAgentId) {
472
- const id = SharingManager.parseRemoteId(remoteAgentId);
473
- const theirs = id && this._shares.find(s => s.id === id.shareId && s.as === 'requester');
474
- if (!theirs) return null;
475
- const gw = theirs.owner?.gatewayId, email = String(theirs.owner?.email || '').toLowerCase();
560
+ _grantToOwnerOf(who) {
561
+ // `who`: another person's agent ('peer:<share>:<agent>') or a person ('person:<gateway id>').
562
+ let gw, email;
563
+ if (String(who || '').startsWith('person:')) {
564
+ gw = who.slice('person:'.length);
565
+ email = String(this.contact(gw)?.email || '').toLowerCase();
566
+ } else {
567
+ const id = SharingManager.parseRemoteId(who);
568
+ const theirs = id && this._shares.find(s => s.id === id.shareId && s.as === 'requester');
569
+ if (!theirs) return null;
570
+ gw = theirs.owner?.gatewayId; email = String(theirs.owner?.email || '').toLowerCase();
571
+ }
476
572
  const candidates = this._shares.filter(s => s.as === 'owner' && s.status === 'active');
477
573
  const mine = candidates.find(s => gw && s.requester?.gatewayId === gw)
478
574
  || candidates.find(s => email && String(s.requester?.email || '').toLowerCase() === email);
@@ -499,7 +595,7 @@ export class SharingManager {
499
595
  const guestId = findGuestAgent(agents, localAgentId)?.id;
500
596
  const shared = g.grant.agents.find(a => a.id === guestId) || g.grant.agents.find(a => a.id === localAgentId);
501
597
  if (!shared) return null;
502
- return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true },
598
+ return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true, byPerson: String(remoteAgentId).startsWith('person:') },
503
599
  (event, data) => { if (event === 'delta' && typeof data === 'string') onDelta?.(data); });
504
600
  }
505
601
 
@@ -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);
@@ -178,7 +231,9 @@ export class SessionLens {
178
231
  }
179
232
  if (!this.observe(key, payload.session || payload)) return null;
180
233
  if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
181
- return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) };
234
+ const out = trimEvent(payload);
235
+ if (payload.reason !== 'delete') this._withParent(key, out.session || out);
236
+ return { type: 'event', event: 'sessions.changed', payload: out };
182
237
  }
183
238
 
184
239
  /** `session.message` (live transcript entry). Forwarded only for watched visible chats. */
@@ -271,9 +326,11 @@ export class SessionLens {
271
326
  let legacy = null;
272
327
  try { legacy = this.extras?.getLegacyCreatedAt?.(); } catch (e) { this.log.warn?.(`[lens] legacy dates: ${e.message}`); }
273
328
  const out = [];
329
+ // Learn the whole page first: a child may be listed before its parent.
330
+ for (const row of rows || []) if (row) this.observe(row.key, row);
274
331
  for (const row of rows || []) {
275
- if (!row || !this.observe(row.key, row)) continue;
276
- const trimmed = trimRow(row);
332
+ if (!row || !this.isVisible(row.key)) continue;
333
+ const trimmed = this._withParent(row.key, trimRow(row));
277
334
  if (!trimmed.createdAt && legacy?.has(row.key)) trimmed.createdAt = legacy.get(row.key);
278
335
  out.push(trimmed);
279
336
  }
@@ -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,51 @@ 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
+ });
@@ -10,18 +10,26 @@
10
10
  // team_entries author of each injected room entry (the transcript only has a "[Label]" prefix);
11
11
  // acting_for = whose request an agent answered when it wasn't its owner's ("Kamil")
12
12
  // team_rooms.rounds follow-up rounds per human message when agents discuss (host setting)
13
+ // team_members.history 'all' (default: a first turn also gets the chat's earlier history) or 'now'
14
+ // team_people people in a room this gateway hosts (specs/sharing-people.md): a contact, by their
15
+ // gateway id; history_from = the oldest entry time they may see (0 = everything)
16
+ // team_rooms.host_* a live copy of someone else's room (this gateway is a member, not the host):
17
+ // host_gateway_id/host_room/host_name; replica_json = the host's members and people
18
+ // team_mirror host entry id -> local message id in a live copy (each host entry injected once)
13
19
 
14
20
  const DISCUSS_ROUNDS = 3; // default; each room can set 1..MAX_ROUNDS
15
21
  const MAX_ROUNDS = 10;
16
22
 
17
- function roomRow(r, members) {
23
+ function roomRow(r, members, people = []) {
18
24
  return {
19
25
  roomKey: r.room_key,
20
26
  discuss: !!r.discuss,
21
27
  rounds: r.rounds || DISCUSS_ROUNDS,
22
28
  sourceKey: r.source_key || null,
23
29
  createdAt: r.created_at,
24
- members: members.map(m => ({ agentId: m.agent_id, workKey: m.work_key || null, seenAt: m.seen_at || 0 })),
30
+ members: members.map(m => ({ agentId: m.agent_id, workKey: m.work_key || null, seenAt: m.seen_at || 0, history: m.history || 'all' })),
31
+ people: people.map(p => ({ personId: p.person_id, name: p.name, email: p.email || null, historyFrom: p.history_from || 0 })),
32
+ ...(r.host_gateway_id ? { host: { gatewayId: r.host_gateway_id, roomId: r.host_room, name: r.host_name || 'Someone', ended: r.host_ended || null, ...JSON.parse(r.replica_json || '{}') } } : {}),
25
33
  };
26
34
  }
27
35
 
@@ -37,11 +45,18 @@ export function createTeamStore(getGlobalDb) {
37
45
  g.exec(`CREATE TABLE IF NOT EXISTS team_entries (room_key TEXT NOT NULL, message_id TEXT NOT NULL, author_type TEXT NOT NULL, agent_id TEXT, created_at INTEGER NOT NULL, PRIMARY KEY (room_key, message_id))`);
38
46
  if (!g.prepare('PRAGMA table_info(team_entries)').all().some(c => c.name === 'acting_for')) g.exec('ALTER TABLE team_entries ADD COLUMN acting_for TEXT');
39
47
  if (!g.prepare('PRAGMA table_info(team_rooms)').all().some(c => c.name === 'rounds')) g.exec('ALTER TABLE team_rooms ADD COLUMN rounds INTEGER');
48
+ const cols = t => new Set(g.prepare(`PRAGMA table_info(${t})`).all().map(c => c.name));
49
+ if (!cols('team_members').has('history')) g.exec('ALTER TABLE team_members ADD COLUMN history TEXT');
50
+ const rc = cols('team_rooms');
51
+ 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`);
52
+ 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
+ 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))`);
40
54
  ready = true;
41
55
  }
42
56
  return g;
43
57
  }
44
58
  const members = roomKey => db().prepare('SELECT * FROM team_members WHERE room_key = ? AND removed = 0 ORDER BY position').all(roomKey);
59
+ const people = roomKey => db().prepare('SELECT * FROM team_people WHERE room_key = ? AND removed = 0 ORDER BY added_at').all(roomKey);
45
60
 
46
61
  return {
47
62
  DISCUSS_ROUNDS,
@@ -49,11 +64,11 @@ export function createTeamStore(getGlobalDb) {
49
64
 
50
65
  getRoom(roomKey) {
51
66
  const r = db().prepare('SELECT * FROM team_rooms WHERE room_key = ?').get(roomKey);
52
- return r ? roomRow(r, members(roomKey)) : null;
67
+ return r ? roomRow(r, members(roomKey), people(roomKey)) : null;
53
68
  },
54
69
 
55
70
  listRooms() {
56
- return db().prepare('SELECT * FROM team_rooms ORDER BY created_at').all().map(r => roomRow(r, members(r.room_key)));
71
+ return db().prepare('SELECT * FROM team_rooms ORDER BY created_at').all().map(r => roomRow(r, members(r.room_key), people(r.room_key)));
57
72
  },
58
73
 
59
74
  /** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
@@ -69,14 +84,63 @@ export function createTeamStore(getGlobalDb) {
69
84
  return this.getRoom(roomKey);
70
85
  },
71
86
 
72
- /** Adds an agent at the end (an agent removed earlier comes back with its session). Returns false if the room is unknown. */
73
- addMember(roomKey, agentId) {
87
+ /**
88
+ * Adds an agent at the end (an agent removed earlier comes back with its session). Returns false if
89
+ * the room is unknown. history 'now': it starts from the newest entry, without the earlier chat.
90
+ */
91
+ addMember(roomKey, agentId, { history = 'all', seenAt = 0 } = {}) {
74
92
  if (!this.getRoom(roomKey)) return false;
75
93
  const pos = db().prepare('SELECT COALESCE(MAX(position), -1) + 1 AS p FROM team_members WHERE room_key = ?').get(roomKey).p;
76
- db().prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position) VALUES (?, ?, NULL, 0, ?) ON CONFLICT(room_key, agent_id) DO UPDATE SET removed = 0, position = excluded.position WHERE removed = 1').run(roomKey, agentId, pos);
94
+ db().prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position, history) VALUES (?, ?, NULL, ?, ?, ?) ON CONFLICT(room_key, agent_id) DO UPDATE SET removed = 0, position = excluded.position WHERE removed = 1')
95
+ .run(roomKey, agentId, seenAt, pos, history === 'now' ? 'now' : 'all');
77
96
  return true;
78
97
  },
79
98
 
99
+ /** A person joins a room this gateway hosts (or comes back). historyFrom: oldest entry time they see. */
100
+ addPerson(roomKey, { personId, name, email = null, historyFrom = 0 }) {
101
+ if (!this.getRoom(roomKey)) return false;
102
+ db().prepare(`INSERT INTO team_people (room_key, person_id, name, email, history_from, added_at) VALUES (?, ?, ?, ?, ?, ?)
103
+ ON CONFLICT(room_key, person_id) DO UPDATE SET removed = 0, name = excluded.name, email = excluded.email, history_from = excluded.history_from WHERE removed = 1`)
104
+ .run(roomKey, personId, String(name).slice(0, 100), email, historyFrom, Date.now());
105
+ return true;
106
+ },
107
+
108
+ removePerson(roomKey, personId) {
109
+ db().prepare('UPDATE team_people SET removed = 1 WHERE room_key = ? AND person_id = ?').run(roomKey, personId);
110
+ },
111
+
112
+ /** Every room a person is in (this gateway hosting). */
113
+ roomsWithPerson(personId) {
114
+ return db().prepare('SELECT room_key FROM team_people WHERE person_id = ? AND removed = 0').all(personId).map(r => r.room_key);
115
+ },
116
+
117
+ // ── Live copies (this gateway is a member of someone else's room) ──
118
+
119
+ /** The local copy of a host's room, or null. */
120
+ replicaFor(hostGatewayId, hostRoom) {
121
+ return db().prepare('SELECT room_key FROM team_rooms WHERE host_gateway_id = ? AND host_room = ?').get(hostGatewayId, hostRoom)?.room_key || null;
122
+ },
123
+
124
+ createReplica(roomKey, { hostGatewayId, hostRoom, hostName }) {
125
+ const now = Date.now();
126
+ db().prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at, host_gateway_id, host_room, host_name, replica_json) VALUES (?, 0, NULL, ?, ?, ?, ?, ?, ?)')
127
+ .run(roomKey, now, now, hostGatewayId, hostRoom, String(hostName).slice(0, 100), '{}');
128
+ },
129
+
130
+ /** The host's view of its room: { members: [{ agentId, name, ownerGatewayId? }], people: [...], title, discuss }. */
131
+ setReplica(roomKey, { hostName, view, ended }) {
132
+ db().prepare('UPDATE team_rooms SET host_name = COALESCE(?, host_name), replica_json = COALESCE(?, replica_json), host_ended = ?, updated_at = ? WHERE room_key = ?')
133
+ .run(hostName ? String(hostName).slice(0, 100) : null, view ? JSON.stringify(view) : null, ended || null, Date.now(), roomKey);
134
+ },
135
+
136
+ mirrored(roomKey, hostEntryId) {
137
+ return !!db().prepare('SELECT 1 FROM team_mirror WHERE room_key = ? AND host_entry_id = ?').get(roomKey, hostEntryId);
138
+ },
139
+
140
+ recordMirror(roomKey, hostEntryId, messageId) {
141
+ db().prepare('INSERT OR REPLACE INTO team_mirror (room_key, host_entry_id, message_id) VALUES (?, ?, ?)').run(roomKey, hostEntryId, messageId);
142
+ },
143
+
80
144
  /** Takes an agent out of the room; its working session stays hidden (reused if it's added back). */
81
145
  removeMember(roomKey, agentId) {
82
146
  db().prepare('UPDATE team_members SET removed = 1 WHERE room_key = ? AND agent_id = ?').run(roomKey, agentId);
@@ -104,6 +168,8 @@ export function createTeamStore(getGlobalDb) {
104
168
  const g = db();
105
169
  g.prepare('DELETE FROM team_members WHERE room_key = ?').run(roomKey);
106
170
  g.prepare('DELETE FROM team_entries WHERE room_key = ?').run(roomKey);
171
+ g.prepare('DELETE FROM team_people WHERE room_key = ?').run(roomKey);
172
+ g.prepare('DELETE FROM team_mirror WHERE room_key = ?').run(roomKey);
107
173
  g.prepare('DELETE FROM team_rooms WHERE room_key = ?').run(roomKey);
108
174
  return work;
109
175
  },
@@ -119,16 +185,22 @@ export function createTeamStore(getGlobalDb) {
119
185
  return new Set(db().prepare('SELECT work_key FROM team_members WHERE work_key IS NOT NULL').all().map(r => r.work_key));
120
186
  },
121
187
 
188
+ /**
189
+ * type 'user' (this gateway's own person), 'person' (someone else; agentId holds their person id
190
+ * and actingFor their name), or 'agent' (actingFor: whose request it answered, if not its owner's).
191
+ */
122
192
  recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null }) {
123
193
  db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at, acting_for) VALUES (?, ?, ?, ?, ?, ?)')
124
- .run(roomKey, messageId, type === 'user' ? 'user' : 'agent', agentId, Date.now(), actingFor);
194
+ .run(roomKey, messageId, ['user', 'person'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor);
125
195
  },
126
196
 
127
- /** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } } */
197
+ /** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } | { type: 'person', personId, name } } */
128
198
  authors(roomKey) {
129
199
  const out = {};
130
200
  for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for FROM team_entries WHERE room_key = ?').all(roomKey)) {
131
- out[r.message_id] = { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}) };
201
+ 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 } : {}) };
132
204
  }
133
205
  return out;
134
206
  },