@celljs/ta-channels 4.7.0 → 4.9.0

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/web-src/team.ts DELETED
@@ -1,560 +0,0 @@
1
- import type { TaExtensionHost } from '@celljs/ta-protocol';
2
- import {
3
- type Agent,
4
- type Channel,
5
- type ChannelMessage,
6
- ChannelsUtil,
7
- type Job,
8
- Keys,
9
- NAME,
10
- type Queue,
11
- STOP_NOTE,
12
- SYSTEM,
13
- type Team,
14
- type TeamRequest,
15
- type TeamResult,
16
- USER,
17
- } from './channels-util';
18
-
19
- /** What the team needs of ta serve: its sessions and the data of this package. */
20
- export type TeamHost = Pick<
21
- TaExtensionHost,
22
- | 'getServerInfo'
23
- | 'sessionCwd'
24
- | 'listSessions'
25
- | 'openSession'
26
- | 'setSessionName'
27
- | 'prompt'
28
- | 'getState'
29
- | 'getLastAssistantText'
30
- | 'getExtensionData'
31
- | 'setExtensionData'
32
- | 'onExtensionData'
33
- >;
34
-
35
- export interface TeamOptions {
36
- pollMs: number;
37
- /** How long an agent may take for one answer. */
38
- timeoutMs: number;
39
- /** How long a result waits for the page that asked. */
40
- resultMs: number;
41
- }
42
-
43
- /** What a round has led to in this process, for whoever waits for it. */
44
- interface Waiting {
45
- replies: ChannelMessage[];
46
- waiters: ((replies: ChannelMessage[]) => void)[];
47
- }
48
-
49
- /**
50
- * The agents and channels, in ta serve: the only writer of the team, the messages and the queue. Pages ask
51
- * it with `requests/<id>` in the data of the package; ta's tools call it in the process. Every answer an
52
- * agent owes is a job in `queue` until it is posted: a job whose answer is in the channel already is not
53
- * asked again, so that a restart goes on where it stopped and repeats nothing.
54
- *
55
- * A message goes to the agents it names (or the lead), each agent one message at a time; their answers go
56
- * on to whom they name, within the limits of ChannelsUtil.limit. Where the agents are stopped, the channel
57
- * says so in one line once the round is over.
58
- */
59
- export class TeamService {
60
- protected team: Team = ChannelsUtil.emptyTeam();
61
- protected queue: Queue = { jobs: [], rounds: {} };
62
- protected working: Record<string, string[]> = {};
63
- protected readonly messages = new Map<string, ChannelMessage[]>();
64
- protected readonly reading = new Map<string, Promise<ChannelMessage[]>>();
65
- /** One message at a time per agent. */
66
- protected readonly agents = new Map<string, Promise<unknown>>();
67
- protected readonly started = new Set<string>();
68
- protected readonly waiting = new Map<string, Waiting>();
69
- protected readonly handling = new Set<string>();
70
- /** By agent id: its session being found or opened, so that a page and a job never open it twice. */
71
- protected readonly opening = new Map<string, Promise<string>>();
72
- protected readonly settling = new Set<string>();
73
- protected readonly options: TeamOptions;
74
- protected disposed = false;
75
- protected unlisten?: () => void;
76
-
77
- constructor(
78
- protected readonly host: TeamHost,
79
- options: Partial<TeamOptions> = {},
80
- ) {
81
- this.options = { pollMs: 300, timeoutMs: 15 * 60 * 1000, resultMs: 60 * 1000, ...options };
82
- }
83
-
84
- get state(): Team {
85
- return this.team;
86
- }
87
-
88
- /** Reads the data, answers the pages, and goes on with the jobs left from before. */
89
- async start(): Promise<void> {
90
- this.team = (await this.get<Team>(Keys.TEAM)) ?? ChannelsUtil.emptyTeam();
91
- await this.pinDirectories();
92
- this.queue = (await this.get<Queue>(Keys.QUEUE)) ?? { jobs: [], rounds: {} };
93
- await this.set(Keys.WORKING, null);
94
- this.unlisten = this.host.onExtensionData((name, key) => {
95
- if (name === NAME && key.startsWith(Keys.REQUESTS)) {
96
- void this.request(key.slice(Keys.REQUESTS.length));
97
- }
98
- });
99
- for (const job of this.queue.jobs) {
100
- this.run(job);
101
- }
102
- for (const round of Object.keys(this.queue.rounds)) {
103
- await this.settle(round);
104
- }
105
- }
106
-
107
- /** Stops taking work; what is unanswered stays in the queue for the next start. */
108
- dispose(): void {
109
- this.disposed = true;
110
- this.unlisten?.();
111
- }
112
-
113
- /** Without a directory, it works in that of ta serve now, and stays there when the server's changes. */
114
- async createAgent(input: { name: unknown; role: unknown; cwd?: unknown; face?: unknown }): Promise<Agent> {
115
- const cwd = ChannelsUtil.directory(input.cwd) ?? (await this.host.getServerInfo()).cwd;
116
- const { team, agent } = ChannelsUtil.addAgent(this.team, { ...input, cwd });
117
- await this.saveTeam(team);
118
- return agent;
119
- }
120
-
121
- async createChannel(input: { name: unknown; members: unknown; topic?: unknown }): Promise<Channel> {
122
- const { team, channel } = ChannelsUtil.addChannel(this.team, input);
123
- await this.saveTeam(team);
124
- return channel;
125
- }
126
-
127
- async addMembers(input: { channel: unknown; members: unknown }): Promise<{ channel: Channel; added: Agent[] }> {
128
- const { team, channel, added } = ChannelsUtil.addMembers(this.team, input);
129
- if (added.length > 0) {
130
- await this.saveTeam(team);
131
- }
132
- return { channel, added };
133
- }
134
-
135
- async changeMember(input: { channel: unknown; agent: unknown; change: unknown }): Promise<Channel> {
136
- const { team, channel } = ChannelsUtil.changeMember(this.team, input);
137
- await this.saveTeam(team);
138
- return channel;
139
- }
140
-
141
- async updateChannel(input: { channel: unknown; name?: unknown; topic?: unknown; pinned?: unknown }): Promise<Channel> {
142
- const { team, channel } = ChannelsUtil.updateChannel(this.team, input);
143
- await this.saveTeam(team);
144
- return channel;
145
- }
146
-
147
- /** The channel and its messages go; what its agents are answering now is not posted. */
148
- async deleteChannel(ref: unknown): Promise<Channel> {
149
- const { team, channel } = ChannelsUtil.removeChannel(this.team, ref);
150
- await this.saveTeam(team);
151
- await this.forget(channel);
152
- return channel;
153
- }
154
-
155
- /** Its name, face, role or directory; an open session takes the new name at once, the rest when it opens again. */
156
- async updateAgent(input: { agent: unknown; name?: unknown; role?: unknown; face?: unknown; cwd?: unknown }): Promise<Agent> {
157
- // No directory is the server's of now: an agent keeps one of its own.
158
- const cwd = input.cwd === undefined ? undefined : (ChannelsUtil.directory(input.cwd) ?? (await this.host.getServerInfo()).cwd);
159
- const { team, agent, before } = ChannelsUtil.updateAgent(this.team, cwd === undefined ? input : { ...input, cwd });
160
- await this.saveTeam(team);
161
- if (agent.name !== before.name && agent.sessionFile) {
162
- const open = (await this.host.listSessions()).find(session => session.sessionFile === agent.sessionFile);
163
- if (open) {
164
- await this.host.setSessionName(open.sessionId, agent.name).catch(() => undefined);
165
- }
166
- }
167
- return agent;
168
- }
169
-
170
- /** The agent goes, with what it was still to answer and the channels it was alone in; its session file stays. */
171
- async deleteAgent(ref: unknown): Promise<Agent> {
172
- const { team, agent, channels } = ChannelsUtil.removeAgent(this.team, ref);
173
- await this.saveTeam(team);
174
- for (const channel of channels) {
175
- await this.forget(channel);
176
- }
177
- this.queue = { ...this.queue, jobs: this.queue.jobs.filter(job => job.agentId !== agent.id) };
178
- await this.set(Keys.QUEUE, this.queue);
179
- for (const round of Object.keys(this.queue.rounds)) {
180
- await this.settle(round);
181
- }
182
- return agent;
183
- }
184
-
185
- /** What the server keeps of a channel that went: its messages, who answers there, its rounds. */
186
- protected async forget(channel: Channel): Promise<void> {
187
- this.messages.delete(channel.id);
188
- this.reading.delete(channel.id);
189
- await this.set(Keys.messages(channel.id), null);
190
- const { [channel.id]: _gone, ...working } = this.working;
191
- this.working = working;
192
- await this.set(Keys.WORKING, working);
193
- this.queue = { ...this.queue, jobs: this.queue.jobs.filter(job => job.channelId !== channel.id) };
194
- await this.set(Keys.QUEUE, this.queue);
195
- // Who waits for a round there hears that it ended.
196
- for (const [round, entry] of Object.entries(this.queue.rounds)) {
197
- if (entry.channelId === channel.id) {
198
- await this.settle(round);
199
- }
200
- }
201
- }
202
-
203
- /** The agent answers next in a new session, without what it was told before; the old one stays among the sessions. */
204
- async resetAgent(ref: unknown): Promise<Agent> {
205
- const { team, agent } = ChannelsUtil.resetAgent(this.team, ref);
206
- await this.saveTeam(team);
207
- return agent;
208
- }
209
-
210
- /** Pages show the channel. */
211
- async focus(channelId: string): Promise<void> {
212
- await this.set(Keys.FOCUS, { channelId, at: Date.now() });
213
- }
214
-
215
- /**
216
- * Posts a message and hands it on. `done` resolves once nobody answers anymore, with the answers and the
217
- * line of the channel if it stopped the agents.
218
- */
219
- async post(channelRef: string, author: string, text: string): Promise<{ channel: Channel; message: ChannelMessage; done: Promise<ChannelMessage[]> }> {
220
- const channel = ChannelsUtil.findChannel(this.team, channelRef);
221
- if (!channel) {
222
- const known = this.team.channels.map(other => `#${other.name}`).join(', ') || 'none yet';
223
- throw new Error(`No channel is named ${channelRef}. The channels: ${known}.`);
224
- }
225
- if (!text.trim()) {
226
- throw new Error('The message is empty.');
227
- }
228
- const message = await this.append(channel.id, { id: ChannelsUtil.newId('message'), author, text: text.trim(), at: Date.now() });
229
- const done = new Promise<ChannelMessage[]>(resolve => this.waitingFor(message.id).waiters.push(resolve));
230
- await this.handOn(channel, message, 0, message.id);
231
- await this.settle(message.id);
232
- return { channel, message, done };
233
- }
234
-
235
- /** A request of a page: done once, answered as `results/<id>`. */
236
- protected async request(id: string): Promise<void> {
237
- if (this.handling.has(id) || this.disposed) {
238
- return;
239
- }
240
- this.handling.add(id);
241
- try {
242
- const request = await this.get<TeamRequest>(Keys.request(id));
243
- if (!request) {
244
- return;
245
- }
246
- let result: TeamResult;
247
- try {
248
- result = { ok: true, value: await this.handle(request) };
249
- } catch (error) {
250
- result = { ok: false, error: error instanceof Error ? error.message : String(error) };
251
- }
252
- await this.set(Keys.result(id), result);
253
- await this.set(Keys.request(id), null);
254
- // A page that closed meanwhile never takes it.
255
- const timer = setTimeout(() => void this.set(Keys.result(id), null).catch(() => undefined), this.options.resultMs);
256
- (timer as { unref?(): void }).unref?.();
257
- } finally {
258
- this.handling.delete(id);
259
- }
260
- }
261
-
262
- protected async handle(request: TeamRequest): Promise<unknown> {
263
- switch (request.kind) {
264
- case 'createAgent':
265
- return this.createAgent(request);
266
- case 'createChannel':
267
- return this.createChannel(request);
268
- case 'addMembers':
269
- return (await this.addMembers(request)).channel;
270
- case 'changeMember':
271
- return this.changeMember(request);
272
- case 'deleteChannel':
273
- return this.deleteChannel(request.channel);
274
- case 'updateChannel':
275
- return this.updateChannel(request);
276
- case 'resetAgent':
277
- return this.resetAgent(request.agent);
278
- case 'updateAgent':
279
- return this.updateAgent(request);
280
- case 'deleteAgent':
281
- return this.deleteAgent(request.agent);
282
- case 'post':
283
- return (await this.post(String(request.channel ?? ''), USER, String(request.text ?? ''))).message;
284
- case 'openAgent': {
285
- const agent = ChannelsUtil.findAgent(this.team, String(request.agent ?? ''));
286
- if (!agent) {
287
- throw new Error(`No agent is ${String(request.agent)}.`);
288
- }
289
- return { sessionId: await this.session(agent) };
290
- }
291
- default:
292
- throw new Error('The page asked for something the server does not do; reload the page.');
293
- }
294
- }
295
-
296
- /** Adds the jobs of the agents a message reaches, as far as the limits of the round let it. */
297
- protected async handOn(channel: Channel, message: ChannelMessage, hops: number, round: string): Promise<void> {
298
- const current = this.queue.rounds[round]?.round ?? ChannelsUtil.newRound();
299
- // After a restart a message may be handed on again: not to whom has it already, or answered it.
300
- const messages = await this.messagesOf(channel.id);
301
- const targets = ChannelsUtil.targets(this.team, channel, message).filter(
302
- agentId =>
303
- !this.queue.jobs.some(job => job.messageId === message.id && job.agentId === agentId) &&
304
- !messages.some(item => item.replyTo === message.id && item.author === agentId),
305
- );
306
- const limited = ChannelsUtil.limit(current, targets, hops);
307
- const jobs: Job[] = limited.allowed.map(agentId => ({
308
- id: ChannelsUtil.newId('job'),
309
- channelId: channel.id,
310
- messageId: message.id,
311
- agentId,
312
- hops,
313
- round,
314
- }));
315
- this.queue = {
316
- jobs: [...this.queue.jobs, ...jobs],
317
- rounds: { ...this.queue.rounds, [round]: { channelId: channel.id, round: limited.round } },
318
- };
319
- await this.set(Keys.QUEUE, this.queue);
320
- for (const job of jobs) {
321
- this.run(job);
322
- }
323
- }
324
-
325
- protected run(job: Job): void {
326
- if (this.started.has(job.id)) {
327
- return;
328
- }
329
- this.started.add(job.id);
330
- const next = (this.agents.get(job.agentId) ?? Promise.resolve())
331
- .catch(() => undefined)
332
- .then(() => this.work(job))
333
- .catch(error => console.error(`${NAME}: ${error instanceof Error ? error.message : error}`));
334
- this.agents.set(job.agentId, next);
335
- }
336
-
337
- protected async work(job: Job): Promise<void> {
338
- if (this.disposed) {
339
- return;
340
- }
341
- const channel = this.team.channels.find(candidate => candidate.id === job.channelId);
342
- const messages = await this.messagesOf(job.channelId);
343
- const message = messages.find(candidate => candidate.id === job.messageId);
344
- // Answered before a restart: not asked again.
345
- let reply = messages.find(candidate => candidate.replyTo === job.messageId && candidate.author === job.agentId);
346
- if (!reply && channel && message) {
347
- reply = await this.answer(channel, message, job.agentId);
348
- }
349
- if (this.disposed) {
350
- return;
351
- }
352
- if (reply) {
353
- this.waitingFor(job.round).replies.push(reply);
354
- if (!reply.failed && channel) {
355
- await this.handOn(channel, reply, job.hops + 1, job.round);
356
- }
357
- }
358
- this.queue = { ...this.queue, jobs: this.queue.jobs.filter(other => other.id !== job.id) };
359
- await this.set(Keys.QUEUE, this.queue);
360
- await this.settle(job.round);
361
- }
362
-
363
- /** Ends a round nobody answers in anymore: the line of the channel if it stopped the agents, once. */
364
- protected async settle(round: string): Promise<void> {
365
- const entry = this.queue.rounds[round];
366
- // Jobs that end together all come here: one ends the round.
367
- if (!entry || this.settling.has(round) || this.queue.jobs.some(job => job.round === round)) {
368
- return;
369
- }
370
- this.settling.add(round);
371
- try {
372
- await this.end(round, entry);
373
- } finally {
374
- this.settling.delete(round);
375
- }
376
- }
377
-
378
- protected async end(round: string, entry: Queue['rounds'][string]): Promise<void> {
379
- const waiting = this.waitingFor(round);
380
- if (entry.round.stopped) {
381
- const said = (await this.messagesOf(entry.channelId)).find(item => item.author === SYSTEM && item.replyTo === round);
382
- waiting.replies.push(
383
- said ??
384
- (await this.append(entry.channelId, {
385
- id: ChannelsUtil.newId('message'),
386
- author: SYSTEM,
387
- text: STOP_NOTE,
388
- at: Date.now(),
389
- replyTo: round,
390
- })),
391
- );
392
- }
393
- const { [round]: _ended, ...rounds } = this.queue.rounds;
394
- this.queue = { ...this.queue, rounds };
395
- await this.set(Keys.QUEUE, this.queue);
396
- this.waiting.delete(round);
397
- for (const resolve of waiting.waiters) {
398
- resolve(waiting.replies);
399
- }
400
- }
401
-
402
- protected waitingFor(round: string): Waiting {
403
- let waiting = this.waiting.get(round);
404
- if (!waiting) {
405
- waiting = { replies: [], waiters: [] };
406
- this.waiting.set(round, waiting);
407
- }
408
- return waiting;
409
- }
410
-
411
- /** The answer of one agent, posted to the channel; a failure is posted too, as such. */
412
- protected async answer(channel: Channel, message: ChannelMessage, agentId: string): Promise<ChannelMessage> {
413
- await this.setWorking(channel.id, agentId, true);
414
- let text: string;
415
- let failed = false;
416
- try {
417
- text = await this.ask(channel, message, agentId);
418
- } catch (error) {
419
- text = error instanceof Error ? error.message : String(error);
420
- failed = true;
421
- } finally {
422
- await this.setWorking(channel.id, agentId, false);
423
- }
424
- return this.append(channel.id, { id: ChannelsUtil.newId('message'), author: agentId, text, at: Date.now(), replyTo: message.id, failed });
425
- }
426
-
427
- protected async ask(channel: Channel, message: ChannelMessage, agentId: string): Promise<string> {
428
- const agent = this.team.agents.find(candidate => candidate.id === agentId);
429
- if (!agent) {
430
- throw new Error(`The agent ${agentId} is gone.`);
431
- }
432
- const sessionId = await this.session(agent);
433
- const before = await this.host.getState(sessionId);
434
- const history = await this.messagesOf(channel.id);
435
- const input = { clientMessageId: `${message.id}:${agent.id}`, message: ChannelsUtil.prompt(this.team, channel, history, message, agent) };
436
- await this.host.prompt(sessionId, input);
437
- await this.settled(sessionId, before.messageCount);
438
- const { text } = await this.host.getLastAssistantText(sessionId);
439
- if (!text?.trim()) {
440
- throw new Error(`${agent.name} gave no answer.`);
441
- }
442
- return text.trim();
443
- }
444
-
445
- /**
446
- * Agents made before each kept a directory followed the server's: each gets the one its conversation
447
- * works in (from its session file), or the server's of now when it has none yet.
448
- */
449
- protected async pinDirectories(): Promise<void> {
450
- const loose = this.team.agents.filter(agent => !agent.cwd);
451
- if (loose.length === 0) {
452
- return;
453
- }
454
- const serverCwd = (await this.host.getServerInfo()).cwd;
455
- const pinned = new Map<string, string>();
456
- for (const agent of loose) {
457
- pinned.set(agent.id, (agent.sessionFile && (await this.host.sessionCwd(agent.sessionFile))) || serverCwd);
458
- }
459
- await this.saveTeam({ ...this.team, agents: this.team.agents.map(agent => (pinned.has(agent.id) ? { ...agent, cwd: pinned.get(agent.id) } : agent)) });
460
- }
461
-
462
- /** The open session of the agent, or its file opened again, or a new one, whose file is kept at once. */
463
- protected session(agent: Agent): Promise<string> {
464
- let opening = this.opening.get(agent.id);
465
- if (!opening) {
466
- opening = this.openSession(agent).finally(() => this.opening.delete(agent.id));
467
- this.opening.set(agent.id, opening);
468
- }
469
- return opening;
470
- }
471
-
472
- protected async openSession(agent: Agent): Promise<string> {
473
- if (agent.sessionFile) {
474
- const open = (await this.host.listSessions()).find(session => session.sessionFile === agent.sessionFile);
475
- if (open) {
476
- return open.sessionId;
477
- }
478
- }
479
- const cwd = agent.cwd ?? (await this.host.getServerInfo()).cwd;
480
- const options = { cwd, appendSystemPrompt: ChannelsUtil.systemPrompt(agent), group: NAME };
481
- if (agent.sessionFile) {
482
- try {
483
- return (await this.host.openSession({ ...options, sessionFile: agent.sessionFile })).sessionId;
484
- } catch {
485
- // The file is gone: the agent starts over.
486
- }
487
- }
488
- const { sessionId } = await this.host.openSession(options);
489
- await this.host.setSessionName(sessionId, agent.name);
490
- const { sessionFile } = await this.host.getState(sessionId);
491
- if (sessionFile) {
492
- await this.saveTeam({ ...this.team, agents: this.team.agents.map(other => (other.id === agent.id ? { ...other, sessionFile } : other)) });
493
- }
494
- return sessionId;
495
- }
496
-
497
- /** Waits until the run ended with more messages than before. */
498
- protected async settled(sessionId: string, before: number): Promise<void> {
499
- const start = Date.now();
500
- for (;;) {
501
- const state = await this.host.getState(sessionId);
502
- if (!state.isStreaming && state.pendingMessageCount === 0 && state.messageCount > before) {
503
- return;
504
- }
505
- if (Date.now() - start > this.options.timeoutMs) {
506
- throw new Error('No answer in time; the agent may still be working in its session.');
507
- }
508
- await new Promise(resolve => setTimeout(resolve, this.options.pollMs));
509
- }
510
- }
511
-
512
- protected messagesOf(channelId: string): Promise<ChannelMessage[]> {
513
- const known = this.messages.get(channelId);
514
- if (known) {
515
- return Promise.resolve(known);
516
- }
517
- let reading = this.reading.get(channelId);
518
- if (!reading) {
519
- reading = this.get<ChannelMessage[]>(Keys.messages(channelId)).then(stored => {
520
- const messages = this.messages.get(channelId) ?? stored ?? [];
521
- this.messages.set(channelId, messages);
522
- return messages;
523
- });
524
- this.reading.set(channelId, reading);
525
- }
526
- return reading;
527
- }
528
-
529
- protected async append(channelId: string, message: ChannelMessage): Promise<ChannelMessage> {
530
- // An answer that comes after its channel was deleted is not kept.
531
- if (!this.team.channels.some(channel => channel.id === channelId)) {
532
- return message;
533
- }
534
- await this.messagesOf(channelId);
535
- // Read after the wait: answers of several agents come in together.
536
- const messages = ChannelsUtil.append(this.messages.get(channelId) ?? [], message);
537
- this.messages.set(channelId, messages);
538
- await this.set(Keys.messages(channelId), messages);
539
- return message;
540
- }
541
-
542
- protected async saveTeam(team: Team): Promise<void> {
543
- this.team = team;
544
- await this.set(Keys.TEAM, team);
545
- }
546
-
547
- protected async setWorking(channelId: string, agentId: string, on: boolean): Promise<void> {
548
- const others = (this.working[channelId] ?? []).filter(id => id !== agentId);
549
- this.working = { ...this.working, [channelId]: on ? [...others, agentId] : others };
550
- await this.set(Keys.WORKING, this.working);
551
- }
552
-
553
- protected async get<T>(key: string): Promise<T | undefined> {
554
- return ((await this.host.getExtensionData(NAME, key)) ?? undefined) as T | undefined;
555
- }
556
-
557
- protected set(key: string, value: unknown): Promise<void> {
558
- return this.host.setExtensionData(NAME, key, value);
559
- }
560
- }
@@ -1,66 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { type Agent, type ChannelMessage, ChannelsUtil, SYSTEM, USER } from './channels-util';
3
- import { RoomUtil } from './room';
4
- import { SidebarUtil } from './views';
5
-
6
- const agent = (name: string, cwd?: string): Agent => ({ id: name, name, role: 'x', mark: 'X', cwd, createdAt: 0 });
7
-
8
- describe('SidebarUtil', () => {
9
- it('shows the time today, the day this year, and the date before', () => {
10
- const now = new Date(2026, 10, 10, 18, 0);
11
- expect(SidebarUtil.time(new Date(2026, 10, 10, 9, 5).getTime(), 'en-US', now)).toBe('09:05');
12
- expect(SidebarUtil.time(new Date(2026, 10, 9, 9, 5).getTime(), 'en-US', now)).toBe('11/9');
13
- expect(SidebarUtil.time(new Date(2025, 0, 2).getTime(), 'en-US', now)).toBe('1/2/25');
14
- expect(SidebarUtil.time(undefined, 'en-US', now)).toBe('');
15
- });
16
-
17
- it('groups agents by their directory, the server one for those without, and matches a search', () => {
18
- const groups = SidebarUtil.byDirectory([agent('a'), agent('b', '/w/docs'), agent('c')], '/w/cell');
19
- expect(groups.map(group => [SidebarUtil.folder(group.cwd), group.agents.map(item => item.name)])).toEqual([
20
- ['cell', ['a', 'c']],
21
- ['docs', ['b']],
22
- ]);
23
- expect(SidebarUtil.matches(' Rev ', 'reviewer', undefined)).toBe(true);
24
- expect(SidebarUtil.matches('qa', 'reviewer', 'You review.')).toBe(false);
25
- expect(SidebarUtil.matches('', 'anything')).toBe(true);
26
- });
27
- });
28
- describe('RoomUtil', () => {
29
- const at = (minutes: number) => Date.UTC(2026, 10, 10, 9) + minutes * 60000;
30
- const say = (id: string, author: string, minutes: number): ChannelMessage => ({ id, author, text: id, at: at(minutes) });
31
-
32
- it('starts a run with a face and a name per author, and a line with the time after a pause', () => {
33
- const rows = RoomUtil.rows([
34
- say('a', USER, 0),
35
- say('b', 'agent-pm', 1),
36
- say('c', 'agent-pm', 2),
37
- say('d', 'agent-dev', 3),
38
- say('e', 'agent-dev', 10),
39
- say('f', SYSTEM, 11),
40
- say('g', 'agent-dev', 12),
41
- say('h', 'agent-dev', 40),
42
- ]);
43
- expect(rows.map(row => [row.message.id, row.first, row.separator])).toEqual([
44
- ['a', true, true],
45
- ['b', true, false],
46
- ['c', false, false],
47
- ['d', true, false],
48
- ['e', true, false],
49
- ['f', true, false],
50
- ['g', true, false],
51
- ['h', true, true],
52
- ]);
53
- });
54
- });
55
-
56
- describe('ChannelsUtil.markMentions', () => {
57
- const agents = [agent('dev'), agent('dev-lead'), agent('设计')];
58
-
59
- it('sets the names of agents in bold, the longer name first, not in code nor in other words', () => {
60
- expect(ChannelsUtil.markMentions('@dev-lead and @dev, @设计 please', agents)).toBe('**@dev-lead** and **@dev**, **@设计** please');
61
- expect(ChannelsUtil.markMentions('mail me@dev.io or @devops', agents)).toBe('mail me@dev.io or @devops');
62
- expect(ChannelsUtil.markMentions('run `@dev` and\n```\n@dev\n```\n@dev', agents)).toBe('run `@dev` and\n```\n@dev\n```\n**@dev**');
63
- expect(ChannelsUtil.markMentions('**@dev** already', agents)).toBe('**@dev** already');
64
- expect(ChannelsUtil.markMentions('@dev', [])).toBe('@dev');
65
- });
66
- });