@clawchatsai/connector 0.1.36 → 0.1.38

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.
@@ -11,6 +11,7 @@ const AGENTS = [{ id: 'main', identity: {} }, { id: 'dev', identity: { name: 'De
11
11
  function harness(reply, { preparedTitle = 'Team title', titler = null, remote = null, agents = AGENTS } = {}) {
12
12
  const sessions = new Map(); // key -> [{ role, content, timestamp, __m: { id } }]
13
13
  const calls = [];
14
+ const labels = new Map(); // session key -> label
14
15
  let clock = 1_000, seq = 0;
15
16
  const events = [];
16
17
  let team;
@@ -18,10 +19,16 @@ function harness(reply, { preparedTitle = 'Team title', titler = null, remote =
18
19
  calls.push({ method, params });
19
20
  switch (method) {
20
21
  case 'agents.list': return { agents };
21
- case 'sessions.create': sessions.set(params.key, []); return { ok: true, key: params.key };
22
- case 'sessions.describe': return { session: { key: params.key } };
22
+ case 'sessions.create': case 'sessions.patch': {
23
+ // Labels are unique per gateway, as on the real one.
24
+ if (params.label && [...labels].some(([k, l]) => l === params.label && k !== params.key)) throw new Error(`label already in use: ${params.label}`);
25
+ if (method === 'sessions.create') sessions.set(params.key, []);
26
+ if (params.label) labels.set(params.key, params.label);
27
+ return { ok: true, key: params.key };
28
+ }
29
+ case 'sessions.describe': return { session: { key: params.key, ...(labels.has(params.key) ? { label: labels.get(params.key) } : {}) } };
23
30
  case 'sessions.title.prepare': return { title: preparedTitle };
24
- case 'sessions.patch': case 'sessions.delete': return { ok: true };
31
+ case 'sessions.delete': labels.delete(params.key); return { ok: true };
25
32
  case 'chat.inject': {
26
33
  const id = `m${++seq}`;
27
34
  sessions.get(params.sessionKey).push({ role: 'assistant', content: [{ type: 'text', text: `[${params.label}]\n\n${params.message}` }], timestamp: ++clock, __m: { id } });
@@ -55,7 +62,7 @@ function harness(reply, { preparedTitle = 'Team title', titler = null, remote =
55
62
  team = new TeamCoordinator({ store: createTeamStore(() => db), request, titler, remote, broadcast: d => events.push(JSON.parse(d)), logger: { warn() {}, error() {} } });
56
63
  const room = key => (sessions.get(key) || []).map(m => m.content[0].text);
57
64
  const settle = async () => { for (let i = 0; i < 50; i++) await new Promise(r => setImmediate(r)); for (const c of team._chains.values()) await c; };
58
- return { team, calls, room, settle, events, sessions };
65
+ return { team, calls, room, settle, events, sessions, labels };
59
66
  }
60
67
 
61
68
  test('parsing helpers', () => {
@@ -82,7 +89,7 @@ test('create, open message: everyone asked, silent agents stay out of the room',
82
89
  await h.settle();
83
90
  assert.deepEqual(h.room(roomKey), ['[Houman]\n\nwhat is 2+2?', '[Dev]\n\ndev answer']);
84
91
  const r = h.team.room(roomKey);
85
- assert.deepEqual(Object.values(r.authors), [{ type: 'user', agentId: null }, { type: 'agent', agentId: 'dev' }]);
92
+ assert.deepEqual(Object.values(r.authors), [{ type: 'user', agentId: null }, { type: 'agent', agentId: 'dev', via: 'owner' }]);
86
93
  assert.equal(r.agents.every(a => a.workKey), true);
87
94
  assert.equal(h.calls.filter(c => c.method === 'chat.send').length, 2);
88
95
  assert.equal(h.team.isWorkKey(r.agents[0].workKey), true);
@@ -179,6 +186,27 @@ test('converting an existing chat keeps it as the agent working session; delete
179
186
  assert.ok(h.calls.some(c => c.method === 'sessions.delete' && c.params.key === devWork));
180
187
  });
181
188
 
189
+ test('converting a titled chat: the team chat takes the title; undoing or deleting gives it back', async () => {
190
+ const h = harness(agent => `${agent} ok`);
191
+ const source = 'agent:atlas:dashboard:titled-chat';
192
+ h.sessions.set(source, []);
193
+ h.labels.set(source, 'My chat');
194
+ const { roomKey } = await h.team.createRoom({ sourceKey: source, agentIds: ['dev'], label: 'My chat' });
195
+ assert.equal(h.labels.get(roomKey), 'My chat');
196
+ assert.match(h.labels.get(source), /^My chat · before team chat /);
197
+ assert.equal(await h.team.unconvert(roomKey), source);
198
+ assert.equal(h.labels.get(source), 'My chat');
199
+
200
+ // Deleting the team chat (the gateway already removed its session) also hands the title back.
201
+ const again = (await h.team.createRoom({ sourceKey: source, agentIds: ['dev'], label: 'My chat' })).roomKey;
202
+ assert.notEqual(h.labels.get(source), 'My chat');
203
+ h.labels.delete(again);
204
+ new SessionLens({ broadcast() {}, team: h.team }).sessionsChanged({ sessionKey: again, reason: 'delete' });
205
+ await new Promise(r => setTimeout(r, 0));
206
+ await new Promise(r => setTimeout(r, 0));
207
+ assert.equal(h.labels.get(source), 'My chat');
208
+ });
209
+
182
210
  test('unconvert: back to the original chat; only converted rooms', async () => {
183
211
  const h = harness(agent => `${agent} ok`);
184
212
  const source = 'agent:atlas:dashboard:orig';
@@ -214,9 +242,9 @@ test('a team chat needs two agents; removing down to one is refused', async () =
214
242
  const h = harness(() => 'x');
215
243
  await assert.rejects(h.team.createRoom({ agentIds: ['dev'] }), /at least two/);
216
244
  const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
217
- assert.throws(() => h.team.removeAgent(roomKey, 'dev'), /at least two/);
245
+ await assert.rejects(h.team.removeAgent(roomKey, 'dev'), /at least two/);
218
246
  await h.team.addAgent(roomKey, 'main');
219
- assert.deepEqual(h.team.removeAgent(roomKey, 'dev').agents.map(a => a.agentId), ['atlas', 'main']);
247
+ assert.deepEqual((await h.team.removeAgent(roomKey, 'dev')).agents.map(a => a.agentId), ['atlas', 'main']);
220
248
  });
221
249
 
222
250
  test('stop: a partial reply is posted marked stopped; a reply that finished anyway is posted', async () => {
@@ -449,6 +477,51 @@ test("authority comes from who asked: an agent answering someone else's agent ru
449
477
  assert.match(h.room(roomKey).at(-1), /^\[Dev\]\n\n\*Dev isn't shared with Kamil, so it doesn't answer Kamil's agents\.\*$/);
450
478
  });
451
479
 
480
+ test("one agent, two sessions (its own, and the guest one for someone else's agent): each gets what the other saw and said", async () => {
481
+ const forPrompts = [];
482
+ const remote = {
483
+ remoteAgents: () => [{ agentId: 'peer:sh1:jarvis', name: 'Jarvis · Kamil', ownerName: 'Kamil' }],
484
+ turn: async () => ({ state: 'final', text: '@dev walk me through your deploy loop' }),
485
+ abort: async () => {},
486
+ actingForName: () => 'Kamil',
487
+ laneFor: who => (who === 'peer:sh1:jarvis' ? 'guest:sh1' : null),
488
+ localTurnFor: async (localId, remoteId, args) => {
489
+ forPrompts.push(args.message);
490
+ return { state: 'final', text: forPrompts.length === 1 ? 'Not without Houman saying so.' : 'Here is the loop: deploy, test, screenshot.' };
491
+ },
492
+ };
493
+ const ownPrompts = [];
494
+ const h = harness((agent, prompt) => { if (agent === 'dev') ownPrompts.push(prompt); return agent === 'dev' ? (ownPrompts.length === 1 ? 'hi' : 'Go ahead and walk Jarvis through it.') : 'NO_REPLY'; }, { remote });
495
+ const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis'] });
496
+ h.team.setDiscuss(roomKey, true);
497
+
498
+ await h.team.send(roomKey, { text: '@dev hi', userLabel: 'Houman' });
499
+ await h.settle();
500
+ // Jarvis asks dev: dev answers in its guest session, acting for Kamil.
501
+ await h.team.send(roomKey, { text: '@Jarvis-Kamil ask dev about the deploy loop', userLabel: 'Houman' });
502
+ await h.settle();
503
+ assert.equal(forPrompts.length, 1);
504
+ assert.match(forPrompts[0], /\[Jarvis · Kamil\][^\n]*\n> @dev walk me through your deploy loop/);
505
+ assert.match(forPrompts[0], /\[Houman\]: @dev hi/, 'the guest session starts with what came before it');
506
+
507
+ // The owner says "proceed": its own session gets the request it never saw and what it said in the other one.
508
+ await h.team.send(roomKey, { text: '@dev proceed', userLabel: 'Houman' });
509
+ await h.settle();
510
+ const own = ownPrompts.at(-1);
511
+ assert.match(own, /> @dev walk me through your deploy loop/);
512
+ assert.match(own, /\[Dev \(you, answering for Kamil\)\]: Not without Houman saying so\./);
513
+ assert.match(own, /\[Houman\]: @dev proceed/);
514
+ assert.ok(!/\[Dev \(you[^\]]*\)\]: hi/.test(own), 'what it said in the same session is not repeated');
515
+
516
+ // Jarvis asks again: the guest session now gets the owner's go-ahead, marked as its own words.
517
+ await h.team.send(roomKey, { text: '@Jarvis-Kamil ask dev again', userLabel: 'Houman' });
518
+ await h.settle();
519
+ const guest = forPrompts.at(-1);
520
+ assert.match(guest, /\[Houman\]: @dev proceed/);
521
+ assert.match(guest, /\[Dev \(you, for your owner\)\]: Go ahead and walk Jarvis through it\./);
522
+ assert.ok(!/Not without Houman saying so/.test(guest), 'its own earlier guest reply is not repeated');
523
+ });
524
+
452
525
  test('rounds: a per-room host setting, validated', async () => {
453
526
  let n = 0;
454
527
  const h = harness(agent => `@${agent === 'dev' ? 'Atlas' : 'Dev'} reply ${++n}`);
@@ -476,17 +549,22 @@ test('rounds: a per-room host setting, validated', async () => {
476
549
  function twoGateways({ devShared = true } = {}) {
477
550
  const forCalls = [];
478
551
  const sides = {};
552
+ const net = { connected: true, jarvisShared: true };
479
553
  const mk = (self, other, name) => ({
480
554
  gatewayId: () => self,
481
555
  selfName: () => name,
482
- contact: gw => (gw === other ? { personId: other, name: other === 'gwK' ? 'Kamil' : 'Houman', email: null } : null),
556
+ hasShareWith: gw => net.connected && gw === other,
557
+ labelOf: (id, full) => String(full || '').split(/\s+/)[0],
558
+ guestSessionOf: () => null,
559
+ funnelOf: (email, name) => `Shared with ${name}`,
560
+ contact: gw => (net.connected && gw === other ? { personId: other, name: other === 'gwK' ? 'Kamil' : 'Houman', email: null } : null),
483
561
  personRequest: async (gw, method, params) => {
484
562
  if (gw !== other) throw Object.assign(new Error('not connected'), { code: 'not_connected' });
485
563
  return sides[other].team.onRoom(method, JSON.parse(JSON.stringify(params)), self);
486
564
  },
487
565
  ownerOf: id => (String(id).startsWith('peer:sh1:') && self === 'gwH' ? 'gwK' : null),
488
566
  ownsShare: shareId => shareId === 'sh1' && self === 'gwK',
489
- remoteAgents: () => (self === 'gwH' ? [{ agentId: 'peer:sh1:jarvis-guest', name: 'Jarvis · Kamil', ownerName: 'Kamil' }] : []),
567
+ remoteAgents: () => (self === 'gwH' && net.jarvisShared ? [{ agentId: 'peer:sh1:jarvis-guest', name: 'Jarvis · Kamil', ownerName: 'Kamil' }] : []),
490
568
  turn: async () => ({ state: 'final', text: 'guest jarvis here' }),
491
569
  abort: async () => {},
492
570
  actingForName: () => 'Kamil',
@@ -507,7 +585,7 @@ function twoGateways({ devShared = true } = {}) {
507
585
  for (const c of sides.gwK.team._syncChains?.values() || []) await c.catch(() => {});
508
586
  }
509
587
  };
510
- return { H: sides.gwH, K: sides.gwK, settle, forCalls };
588
+ return { H: sides.gwH, K: sides.gwK, settle, forCalls, net };
511
589
  }
512
590
 
513
591
  test('people: a person gets a live copy, posts back, their own agent runs on their gateway, removal ends it', async () => {
@@ -524,7 +602,7 @@ test('people: a person gets a live copy, posts back, their own agent runs on the
524
602
  assert.equal(copy.replica.hostName, 'Houman Satarian');
525
603
  assert.ok(K.room(copy.roomKey).some(t => t.endsWith('before kamil joins')));
526
604
  assert.deepEqual(copy.people.map(p => [p.name, !!p.host, !!p.me]), [['Houman Satarian', true, false], ['Kamil', false, true]]);
527
- assert.ok(copy.agents.find(a => a.agentId === 'peer:sh1:jarvis-guest').mine, 'Kamil sees Jarvis as his own agent');
605
+ assert.ok(copy.agents.find(a => a.agentId === 'gwK:jarvis-guest').mine, 'Kamil sees Jarvis as his own agent');
528
606
  assert.ok(K.events.some(e => e.event === 'team-invited'));
529
607
 
530
608
  // Kamil asks his own Jarvis: it runs at full strength on Kamil's gateway; Houman's never runs it.
@@ -554,7 +632,7 @@ test('people: a person gets a live copy, posts back, their own agent runs on the
554
632
  assert.ok(Object.values(H.team.room(roomKey).authors).some(a => a.agentId === 'dev' && a.actingFor === 'Kamil'));
555
633
 
556
634
  // Houman removes Kamil: Jarvis leaves with him, the copy ends, sending fails.
557
- H.team.removePerson(roomKey, 'gwK');
635
+ await H.team.removePerson(roomKey, 'gwK');
558
636
  await settle();
559
637
  assert.ok(!H.team.room(roomKey).agents.some(a => a.agentId === 'peer:sh1:jarvis-guest'));
560
638
  assert.equal(K.team.room(copy.roomKey).replica.ended, 'removed');
@@ -604,3 +682,324 @@ test('a chat turned into a team chat: agents added later get its earlier history
604
682
  const main = h.team.store.getRoom(roomKey).members.find(m => m.agentId === 'main');
605
683
  assert.equal(await h.team._earlier(h.team.store.getRoom(roomKey), main), '');
606
684
  });
685
+
686
+ // ── Rooms behave like Discord: one log, membership changes access, never the view ────────────────
687
+
688
+ const lines = (h, key) => h.room(key).map(t => splitLabel(t)).map(m => `${m.label}: ${m.body}`);
689
+
690
+ test('a chat created with someone\'s agent brings its owner in (create, convert, add: one rule)', async () => {
691
+ const { H, K, settle } = twoGateways();
692
+ const created = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'] });
693
+ assert.deepEqual(created.people.map(p => p.personId), ['gwK']);
694
+ await settle();
695
+ assert.ok(K.team.rooms().find(r => r.replica), 'Kamil has a copy straight away, not only his agent\'s session');
696
+
697
+ const { H: H2, K: K2, settle: settle2 } = twoGateways();
698
+ H2.sessions.set('agent:main:dashboard:orig', []);
699
+ const converted = await H2.team.createRoom({ sourceKey: 'agent:main:dashboard:orig', agentIds: ['peer:sh1:jarvis-guest'] });
700
+ assert.deepEqual(converted.people.map(p => p.personId), ['gwK']);
701
+ await settle2();
702
+ assert.ok(K2.team.rooms().find(r => r.replica));
703
+ });
704
+
705
+ test('a chat with only people: the agent stays quiet unless @mentioned', async () => {
706
+ const { H, K, settle } = twoGateways();
707
+ const room = await H.team.createRoom({ personIds: ['gwK'], mentionOnly: true });
708
+ assert.equal(room.mentionOnly, true);
709
+ assert.deepEqual(room.people.map(p => p.personId), ['gwK']);
710
+ assert.equal(room.agents.length, 1, 'one agent of this gateway anchors the room');
711
+ await H.team.send(room.roomKey, { text: 'hey Kamil, just us', userLabel: 'Houman' });
712
+ await settle();
713
+ assert.equal(H.calls.filter(c => c.method === 'chat.send').length, 0, 'no agent ran');
714
+ const copy = K.team.rooms().find(r => r.replica);
715
+ assert.ok(K.room(copy.roomKey).some(t => t.endsWith('hey Kamil, just us')));
716
+ // Kamil answers; still nobody else runs. Then an @mention wakes the agent.
717
+ await K.team.send(copy.roomKey, { text: 'hi Houman' });
718
+ await settle();
719
+ assert.equal(H.calls.filter(c => c.method === 'chat.send').length, 0);
720
+ await H.team.send(room.roomKey, { text: '@main what time is it', userLabel: 'Houman' });
721
+ await settle();
722
+ assert.equal(H.calls.filter(c => c.method === 'chat.send').length, 1);
723
+ // The setting is the host's, and it travels to the copy.
724
+ assert.equal(K.team.room(copy.roomKey).mentionOnly, true);
725
+ H.team.setMentionOnly(room.roomKey, false);
726
+ assert.equal(H.team.room(room.roomKey).mentionOnly, false);
727
+ });
728
+
729
+ test('adding the first person from the popover turns "agents reply only when @mentioned" on; later adds and create-time adds leave it', async () => {
730
+ const { H, K, settle } = twoGateways();
731
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
732
+ assert.equal(H.team.room(roomKey).mentionOnly, false);
733
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all', quietAgents: true });
734
+ await settle();
735
+ assert.equal(H.team.room(roomKey).mentionOnly, true, 'first other person: agents go quiet');
736
+ assert.equal(K.team.rooms().find(r => r.replica).mentionOnly, true, 'and the copy knows');
737
+ H.team.setMentionOnly(roomKey, false);
738
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all', quietAgents: true });
739
+ assert.equal(H.team.room(roomKey).mentionOnly, false, 'the host\'s later choice is kept');
740
+
741
+ const plain = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
742
+ await H.team.addPerson(plain.roomKey, 'gwK', { history: 'all' });
743
+ assert.equal(H.team.room(plain.roomKey).mentionOnly, false, 'create-time adds decide for themselves');
744
+ });
745
+
746
+ test("someone's agent answering on its owner's copy and through the host: each session gets what it said in the other", async () => {
747
+ const { H, K, settle } = twoGateways();
748
+ const hostAsks = [];
749
+ H.team.remote.turn = async (agentId, args) => { hostAsks.push(args.message); return { state: 'final', text: 'guest jarvis here' }; };
750
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'] });
751
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
752
+ await settle();
753
+ const copy = K.team.rooms().find(r => r.replica);
754
+
755
+ // Kamil asks his own Jarvis on his copy: it answers in Kamil's own session.
756
+ await K.team.send(copy.roomKey, { text: '@Jarvis-Kamil here are four questions' });
757
+ await settle();
758
+ assert.ok(H.room(roomKey).includes('[Jarvis · Kamil]\n\njarvis full on kamil'));
759
+
760
+ // Houman asks Jarvis: the session Kamil's gateway runs for Houman is told what Jarvis said in the other.
761
+ await H.team.send(roomKey, { text: '@Jarvis-Kamil did you send those questions?', userLabel: 'Houman' });
762
+ await settle();
763
+ const asked = hostAsks.at(-1);
764
+ assert.match(asked, /\[Kamil\]: @Jarvis-Kamil here are four questions/, 'it sees Kamil\'s ask too');
765
+ assert.match(asked, /\[Jarvis · Kamil \(you, for your owner\)\]: jarvis full on kamil/);
766
+
767
+ // Back on Kamil's copy, his Jarvis is told what it said through the host, marked as its own.
768
+ const kPrompts = () => K.calls.filter(c => c.method === 'chat.send' && c.params.sessionKey.startsWith('agent:jarvis:')).map(c => c.params.message);
769
+ await K.team.send(copy.roomKey, { text: '@Jarvis-Kamil and now?' });
770
+ await settle();
771
+ const own = kPrompts().at(-1);
772
+ assert.match(own, /\(you, in another session\)\]: guest jarvis here/);
773
+ assert.ok(!/jarvis full on kamil/.test(own), 'what it said in this session is not repeated');
774
+ });
775
+
776
+ test("people can ask the host's agent by the name their copy shows: @dev-HoumanSatarian, @dev-Houman, @dev", async () => {
777
+ const { H, K, settle, forCalls } = twoGateways();
778
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
779
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
780
+ await settle();
781
+ const copy = K.team.rooms().find(r => r.replica);
782
+ for (const name of ['dev-HoumanSatarian', 'dev-Houman', 'dev']) {
783
+ const before = forCalls.length;
784
+ await K.team.send(copy.roomKey, { text: `@${name} ping` });
785
+ await settle();
786
+ assert.deepEqual(forCalls.slice(before).map(c => c.localId), ['dev'], `@${name} reaches dev, and only dev`);
787
+ }
788
+ });
789
+
790
+ test("their chats are filed under 'Shared with <host>'; a renamed agent reaches the copies without a new message", async () => {
791
+ const { H, K, settle } = twoGateways();
792
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
793
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
794
+ await settle();
795
+ const copy = K.team.rooms().find(r => r.replica);
796
+ const made = K.calls.find(c => c.method === 'sessions.create' && c.params.key === copy.roomKey).params;
797
+ assert.equal(made.category, 'Shared with Houman');
798
+
799
+ // A copy made before copies had a project is filed once, on the next sync.
800
+ const fresh = K.calls.length;
801
+ K.team._copiesFiled = new Set();
802
+ await H.team.send(roomKey, { text: 'hello', userLabel: 'Houman' });
803
+ await settle();
804
+ assert.ok(K.calls.slice(fresh).some(c => c.method === 'sessions.describe' && c.params.key === copy.roomKey));
805
+
806
+ await H.team.refreshNames(); // remembers the current names
807
+ const dev = AGENTS.find(a => a.id === 'dev');
808
+ dev.identity.name = 'Devon';
809
+ try {
810
+ assert.deepEqual(await H.team.refreshNames(), ['dev']);
811
+ await settle();
812
+ const names = K.team.room(copy.roomKey).agents.map(a => a.name);
813
+ assert.ok(names.some(n => n.startsWith('Devon · ')), `copy shows the new name: ${names}`);
814
+ } finally { dev.identity.name = 'Dev'; }
815
+ });
816
+
817
+ test("someone else's messages raise a badge on the room or its copy (chat.inject doesn't); your own don't", async () => {
818
+ const { H, K, settle } = twoGateways();
819
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
820
+ const unreadOf = (G, key) => G.calls.filter(c => c.method === 'sessions.patch' && c.params.key === key && c.params.unread === true).length;
821
+ await H.team.send(roomKey, { text: 'before kamil', userLabel: 'Houman' });
822
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
823
+ await settle();
824
+ const copy = K.team.rooms().find(r => r.replica);
825
+ assert.ok(unreadOf(K, copy.roomKey) >= 1, "a new chat's copy arrives unread");
826
+
827
+ const hostBefore = unreadOf(H, roomKey), copyBefore = unreadOf(K, copy.roomKey);
828
+ await H.team.send(roomKey, { text: 'host speaks', userLabel: 'Houman' });
829
+ await settle();
830
+ assert.ok(unreadOf(K, copy.roomKey) > copyBefore, 'what the host and its agents say is new on the copy');
831
+
832
+ const hostMid = unreadOf(H, roomKey);
833
+ await K.team.send(copy.roomKey, { text: '@dev from kamil' });
834
+ await settle();
835
+ assert.ok(unreadOf(H, roomKey) > hostMid, "a person's message raises a badge on the room they're in");
836
+ assert.ok(hostMid >= hostBefore);
837
+ });
838
+
839
+ test('the timeline says who joined and left, the same on both sides; agents never see those lines', async () => {
840
+ const { H, K, settle } = twoGateways();
841
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
842
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
843
+ await H.team.send(roomKey, { text: '@dev hello', userLabel: 'Houman' });
844
+ await settle();
845
+ const copy = K.team.rooms().find(r => r.replica);
846
+ assert.ok(lines(H, roomKey).includes('System: Kamil joined'));
847
+ assert.ok(lines(K, copy.roomKey).includes('System: Kamil joined'), 'Kamil\'s copy has the same line');
848
+ assert.ok(Object.values(K.team.room(copy.roomKey).authors).some(a => a.type === 'system'));
849
+ const devPrompt = H.calls.find(c => c.method === 'chat.send' && c.params.sessionKey.startsWith('agent:dev:')).params.message;
850
+ assert.ok(!/joined/.test(devPrompt), 'system lines are not part of what agents are told');
851
+
852
+ await H.team.removePerson(roomKey, 'gwK');
853
+ await settle();
854
+ assert.ok(lines(H, roomKey).includes('System: Kamil was removed'));
855
+ // The removed person keeps the room as it was, plus how it ended: a read-only archive.
856
+ assert.ok(K.room(copy.roomKey).some(t => t.endsWith('hello')), 'history kept');
857
+ assert.ok(lines(K, copy.roomKey).includes('System: Kamil was removed'));
858
+ assert.equal(lines(K, copy.roomKey).filter(l => /removed/.test(l)).length, 1, 'one line for one event');
859
+ assert.equal(K.team.room(copy.roomKey).replica.ended, 'removed');
860
+ assert.ok(!K.calls.some(c => c.method === 'sessions.delete'), 'nothing deleted');
861
+ // Nothing about the copy changed for the people still in the room.
862
+ assert.equal(H.team.room(roomKey).people.length, 0);
863
+ });
864
+
865
+ test('a copy shows entries at the time they were sent, and host and guest agents named `main` never collide', async () => {
866
+ const { H, K, settle } = twoGateways();
867
+ const { roomKey } = await H.team.createRoom({ agentIds: ['main', 'peer:sh1:jarvis-guest'] });
868
+ await H.team.send(roomKey, { text: '@main say hi', userLabel: 'Houman' });
869
+ await settle();
870
+ const hostAuthors = H.team.room(roomKey).authors;
871
+ const copy = K.team.rooms().find(r => r.replica);
872
+ const copyAuthors = K.team.room(copy.roomKey).authors;
873
+ const hostTs = Object.values(await H.team._roomEntries(roomKey).then(es => es.map(e => e.ts)));
874
+ const copyTs = Object.values(copyAuthors).map(a => a.ts).filter(Boolean).sort();
875
+ assert.deepEqual(copyTs, [...hostTs].sort(), 'original times');
876
+ // Houman's `main` answered on Houman's gateway. Kamil's own `main` exists too (his default agent) and must not claim that line.
877
+ const hostMain = Object.entries(copyAuthors).find(([, a]) => a.type === 'agent' && a.ownerId === 'gwH');
878
+ assert.ok(hostMain, 'Houman\'s main is recorded under its owner');
879
+ assert.notEqual(hostMain[1].agentId, 'main');
880
+ // Kamil asks his Jarvis: it is told about Houman\'s main reply (not filtered out as its own).
881
+ await K.team.send(copy.roomKey, { text: '@Jarvis-Kamil what did main say?' });
882
+ await settle();
883
+ const prompt = K.calls.filter(c => c.method === 'chat.send' && c.params.sessionKey.startsWith('agent:jarvis:')).at(-1).params.message;
884
+ assert.match(prompt, /main/);
885
+ assert.ok(Object.keys(hostAuthors).length > 0);
886
+ });
887
+
888
+ test('a person takes only their own agent out of a room; the host does not need to be asked', async () => {
889
+ const { H, K, settle } = twoGateways();
890
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'] });
891
+ await settle();
892
+ const copy = K.team.rooms().find(r => r.replica);
893
+ await assert.rejects(K.team.leave(copy.roomKey, { agentId: copy.agents.find(a => !a.mine).agentId }), /Not your agent/);
894
+ const mine = copy.agents.find(a => a.mine);
895
+ await K.team.leave(copy.roomKey, { agentId: mine.agentId });
896
+ await settle();
897
+ const room = H.team.room(roomKey);
898
+ assert.ok(!room.agents.some(a => a.agentId === 'peer:sh1:jarvis-guest'));
899
+ assert.deepEqual(room.people.map(p => p.personId), ['gwK'], 'Kamil stays');
900
+ assert.ok(lines(H, roomKey).some(l => /^System: Jarvis · Kamil left$/.test(l)));
901
+ assert.equal(K.team.room(copy.roomKey).replica.ended, null, 'his copy is still live');
902
+ });
903
+
904
+ test('@mentions in an agent\'s reply get the mentioned agent one answer, with a hard stop', async () => {
905
+ // dev always answers by mentioning atlas, atlas always mentions dev back: it must stop.
906
+ const h = harness(agent => (agent === 'dev' ? 'over to @Atlas' : 'back to @Dev'));
907
+ const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
908
+ await h.team.send(roomKey, { text: '@dev start', userLabel: 'H' });
909
+ await h.settle();
910
+ const sends = h.calls.filter(c => c.method === 'chat.send').length;
911
+ assert.ok(sends >= 2, 'atlas answered the mention');
912
+ assert.ok(sends <= 4, `bounded, not endless (${sends})`);
913
+ // A reply that names nobody ends the chain.
914
+ const h2 = harness(agent => `${agent} done`);
915
+ const r2 = await h2.team.createRoom({ agentIds: ['dev', 'atlas'] });
916
+ await h2.team.send(r2.roomKey, { text: '@dev go', userLabel: 'H' });
917
+ await h2.settle();
918
+ assert.equal(h2.calls.filter(c => c.method === 'chat.send').length, 1);
919
+ });
920
+
921
+ test('connections ending: people and agents leave the rooms, copies end as archives', async () => {
922
+ const { H, K, settle, net } = twoGateways();
923
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest', 'atlas'] });
924
+ await H.team.send(roomKey, { text: 'before', userLabel: 'Houman' });
925
+ await settle();
926
+ const copy = K.team.rooms().find(r => r.replica);
927
+
928
+ // Kamil stops sharing Jarvis only: the agent leaves, Kamil stays.
929
+ net.jarvisShared = false;
930
+ await H.team._reconcileNow();
931
+ await settle();
932
+ assert.ok(!H.team.room(roomKey).agents.some(a => a.agentId === 'peer:sh1:jarvis-guest'));
933
+ assert.deepEqual(H.team.room(roomKey).people.map(p => p.personId), ['gwK']);
934
+ assert.ok(lines(H, roomKey).includes('System: Jarvis · Kamil is no longer shared'));
935
+ assert.equal(K.team.room(copy.roomKey).replica.ended, null);
936
+
937
+ // The whole connection ends: Kamil leaves Houman's room; on Kamil's side the copy is kept, read-only.
938
+ net.connected = false;
939
+ await H.team._reconcileNow();
940
+ await K.team._reconcileNow();
941
+ assert.deepEqual(H.team.room(roomKey).people, []);
942
+ assert.ok(lines(H, roomKey).includes('System: Kamil is no longer connected'));
943
+ const kc = K.team.room(copy.roomKey);
944
+ assert.equal(kc.replica.ended, 'disconnected');
945
+ assert.ok(K.room(copy.roomKey).some(t => t.endsWith('before')), 'history kept');
946
+ assert.ok(lines(K, copy.roomKey).includes("System: You're no longer connected with Houman Satarian"));
947
+ await assert.rejects(K.team.send(copy.roomKey, { text: 'hello?' }), /no longer connected/);
948
+ });
949
+
950
+ test('ending or undoing a chat with people turns their copies into archives', async () => {
951
+ const { H, K, settle } = twoGateways();
952
+ H.sessions.set('agent:main:dashboard:orig2', []);
953
+ const { roomKey } = await H.team.createRoom({ sourceKey: 'agent:main:dashboard:orig2', agentIds: ['peer:sh1:jarvis-guest'] });
954
+ await H.team.send(roomKey, { text: 'before the end', userLabel: 'Houman' });
955
+ await settle();
956
+ const copy = K.team.rooms().find(r => r.replica);
957
+ await H.team.unconvert(roomKey);
958
+ await settle();
959
+ const kc = K.team.room(copy.roomKey);
960
+ assert.equal(kc.replica.ended, 'deleted');
961
+ assert.ok(K.room(copy.roomKey).some(t => t.endsWith('before the end')));
962
+ assert.ok(lines(K, copy.roomKey).includes('System: Houman Satarian ended this chat'));
963
+ });
964
+
965
+ test('a copy has no label until the host\'s chat has a title, then follows it', async () => {
966
+ const { H, K, settle } = twoGateways();
967
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'] });
968
+ await settle();
969
+ const copy = K.team.rooms().find(r => r.replica);
970
+ assert.equal(K.labels.get(copy.roomKey), undefined, 'untitled: the app names it after who is in it');
971
+ H.labels.set(roomKey, 'Trip plans');
972
+ await H.team.send(roomKey, { text: 'more', userLabel: 'Houman' });
973
+ await settle();
974
+ assert.equal(K.labels.get(copy.roomKey), 'Trip plans · Houman Satarian');
975
+ H.labels.set(roomKey, 'Trip plans v2');
976
+ await H.team.send(roomKey, { text: 'again', userLabel: 'Houman' });
977
+ await settle();
978
+ assert.equal(K.labels.get(copy.roomKey), 'Trip plans v2 · Houman Satarian');
979
+ });
980
+
981
+ test('names that clash: a converted chat\'s earlier answers carry the full host name, like the agents list does', async () => {
982
+ const { H, K, settle } = twoGateways();
983
+ H.team.remote.labelOf = () => 'Houman Satarian'; // another Houman is in the picture
984
+ H.sessions.set('agent:main:dashboard:orig', [
985
+ { role: 'user', content: [{ type: 'text', text: 'what is the code word?' }], timestamp: 1, __m: { id: 'o1' } },
986
+ { role: 'assistant', content: [{ type: 'text', text: 'marmot' }], timestamp: 2, __m: { id: 'o2' } },
987
+ ]);
988
+ await H.team.createRoom({ sourceKey: 'agent:main:dashboard:orig', agentIds: ['peer:sh1:jarvis-guest'] });
989
+ await settle();
990
+ const copy = K.team.rooms().find(r => r.replica);
991
+ assert.ok(lines(K, copy.roomKey).includes('main · Houman Satarian: marmot'), lines(K, copy.roomKey).join(' | '));
992
+ });
993
+
994
+ test('a host renaming the chat reaches the copies without anyone sending a message', async () => {
995
+ const { H, K, settle } = twoGateways();
996
+ const { roomKey } = await H.team.createRoom({ personIds: ['gwK'], mentionOnly: true, label: 'First title' });
997
+ await settle();
998
+ const copy = K.team.rooms().find(r => r.replica);
999
+ const label = () => K.labels.get(copy.roomKey);
1000
+ assert.equal(label(), 'First title · Houman Satarian');
1001
+ H.labels.set(roomKey, 'Second title');
1002
+ await H.team.onSessionPatched(roomKey);
1003
+ await settle();
1004
+ assert.equal(label(), 'Second title · Houman Satarian');
1005
+ });