A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Start the members one group message calls at the same time
Fei2411119ad678f0d1
diff --git a/docs/plans/2026-10-07-group-chat.md b/docs/plans/2026-10-07-group-chat.mdindex f3771049..10ed2b4f 100644--- a/docs/plans/2026-10-07-group-chat.md+++ b/docs/plans/2026-10-07-group-chat.md@@ -7,7 +7,7 @@群聊是多个 Bot 一起工作的主要方式,有两个根本难题:-1. **协调。** 早期让成员并行写、发出前再检查新消息,连报数都会乱:模型会沿用乱掉的数字硬发。把排序交给模型做不好。结论是 **群里一次只有一个人说话**,每个成员开口前读到的都是最新的群。+1. **协调。** 早期让成员并行写、发出前再检查新消息,连报数都会乱:模型会沿用乱掉的数字硬发。把排序交给模型做不好。所以讨论(全员轮流的普通消息)**一次只有一个人说话**,每个成员开口前读到的都是最新的群。但派活不能排队:一条消息点了几个人,他们要同时开工,否则群聊就失去了多个 Bot 一起干活的意义。2. **成本。** 每叫一个成员,就要带上它整个会话的上下文跑一次模型。成本随发言人数线性增长,系数很大。所以默认少叫人:普通消息先给管理员,由它决定点谁。另外,成员在群里接到长任务时,不能让用户面对一个静止的页面(「黑盒」),也不能让做完的结果丢掉。@@ -21,7 +21,11 @@- **全员轮流**:普通消息由每个成员按顺序回答,管理员第一个。- 没有管理员的群按「全员轮流」回答。- `@名字` 只叫被点名的成员。`@all`、`@everyone`、`@所有人`、`@全体` 叫全员;成员回复里的这几个词只有管理员说才算,防止成员互相叫起一大片。-- 成员按顺序发言:上一个人发完(或跳过)下一个人才开始,每个人看到本轮之前所有人的发言和自己的位置。+- 同一条消息点到的成员同时开工:用户的 `@` 消息、成员回复里点的几个人、`@all`。谁先好谁先发;一起被点的成员看不到彼此这一轮的回答,提示里写明还有谁在同时回答。需要接着别人的结果做时,用接力:先叫一个人,让他做完再 `@` 下一个。+- `@` 一发出来就生效:成员干活中途说的话、最后的回复、Bot 在一轮进行中发的帖,里面点到的人马上开工,不等说话的人干完。+- 一轮进行中用户发的话立刻写进群,交给它该叫的人(管理员模式下是管理员),不排在正在回答的成员后面。+- 一个成员同一时间只回答一个叫它的消息;前一个回答完(或转去后台干活)才开始下一个。+- 全员轮流的普通消息(不带 `@`)仍按顺序:上一个人发完(或跳过)下一个人才开始,每个人看到本轮之前所有人的发言和自己的位置。- 回复里 `@` 了别人,被点的人接着说(接力)。接力次数、每人每轮、每轮总数都没有上限;用户的消息一定有人回应。要停下群里的工作,用户在群详情里点「全部停止」或逐个停。- 每个成员可以跳过(`[PASS]`),不必每轮都说话。@@ -90,3 +94,4 @@- 2026-10-22:去掉群里每人每轮、每轮总数和迟到 10 次的上限;Bot 之间接力到群的上限时暂停,用户点「继续」或发言后接着跑,用户的 @ 一定有人回应(#395)。- 2026-10-29:群的停止按钮一次停掉本群的一轮和所有成员在本群的工作,放在群详情的成员列表标题旁,不放在状态胶囊旁(#592,PR #616)。- 2026-10-30:去掉 Bot 之间接力的上限、群设置里的这一项和「继续」按钮;以前停在上限的叫人在群的下一轮接着跑(#655)。+- 2026-10-30:同一条消息点到的成员同时开工,`@` 一发出来就生效,一轮中用户的话和 Bot 的帖马上交给该叫的人;只有全员轮流的普通消息还按顺序(#726)。diff --git a/ds-bot/client.js b/ds-bot/client.jsindex fe7f5b4d..255db8d8 100644--- a/ds-bot/client.js+++ b/ds-bot/client.js@@ -8529,7 +8529,7 @@ function scanReplies(text, start, replies) {}}function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi, useWork }) {- const [live, setLive] = (0, import_react16.useState)({ replies: [], speaking: null });+ const [live, setLive] = (0, import_react16.useState)({ replies: [], speaking: [] });(0, import_react16.useEffect)(() => {if (done) return void 0;let stop = false;@@ -8542,7 +8542,7 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUiconst key = entry ? JSON.stringify([entry.replies, entry.speaking]) : "";if (entry && key !== seen) {seen = key;- setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null });+ setLive({ replies: entry.replies ?? [], speaking: [entry.speaking ?? []].flat() });}timer = setTimeout(tick, document.hidden ? 5e3 : 1e3);};@@ -8559,9 +8559,11 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUireplies = parsed.replies.length ? parsed.replies : live.replies;broken = parsed.broken;}- const pending = done || !live.speaking ? [] : [live.speaking];- const speakerTool = useWork?.((work) => work.bots?.[live.speaking]?.tool) ?? void 0;- const speakerDoing = useWork?.((work) => work.bots?.[live.speaking]?.tool ? workPhrase(work.bots[live.speaking]) : void 0) ?? void 0;+ const pending = done ? [] : live.speaking;+ const doing = JSON.parse(useWork?.((work) => JSON.stringify(pending.map((id) => {+ const tool = work.bots?.[id]?.tool;+ return tool ? [tool, workPhrase(work.bots[id])] : [];+ }))) ?? "[]");if (replies.length === 0 && pending.length === 0) {return broken ? (0, import_react16.createElement)("div", { className: "bt-group-replies" }, (0, import_react16.createElement)("div", { className: "bt-event" }, t("The group replies could not be shown"))) : null;}@@ -8636,14 +8638,15 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi}return (0, import_react16.createElement)(GroupMessage, { key: `${reply.botId}-${index}`, bot, texts: texts2, room: room2, roster, actions, msgKey: callId ? `${sessionId}:${callId}:${index}` : void 0, useUi, time, duration });}),- pending.map((id) => {+ pending.map((id, at) => {const bot = roster.byId[id];if (!bot) return null;+ const [tool, phrase] = doing[at] ?? [];return (0, import_react16.createElement)("div",{ key: `pending-${id}`, className: "bt-activity" },- (0, import_react16.createElement)(BotMark, { bot, size: 22, state: speakerTool ? toolState(speakerTool) : "thinking" }),- (0, import_react16.createElement)(Shimmer, null, speakerDoing ? `${bot.name} · ${speakerDoing}…` : t("{name} is typing…", { name: bot.name }))+ (0, import_react16.createElement)(BotMark, { bot, size: 22, state: tool ? toolState(tool) : "thinking" }),+ (0, import_react16.createElement)(Shimmer, null, phrase ? `${bot.name} · ${phrase}…` : t("{name} is typing…", { name: bot.name })));}));diff --git a/ds-bot/src/client/cells.js b/ds-bot/src/client/cells.jsindex 1dc43015..834e30d2 100644--- a/ds-bot/src/client/cells.js+++ b/ds-bot/src/client/cells.js@@ -870,7 +870,7 @@ function scanReplies(text, start, replies) {}function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi, useWork }) {- const [live, setLive] = useState({ replies: [], speaking: null })+ const [live, setLive] = useState({ replies: [], speaking: [] })useEffect(() => {if (done) return undefinedlet stop = false@@ -881,7 +881,7 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUiif (stop) returnconst entry = (result ?? []).find(item => item.callId === callId) ?? (result ?? [])[0]const key = entry ? JSON.stringify([entry.replies, entry.speaking]) : ''- if (entry && key !== seen) { seen = key; setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null }) }+ if (entry && key !== seen) { seen = key; setLive({ replies: entry.replies ?? [], speaking: [entry.speaking ?? []].flat() }) }timer = setTimeout(tick, document.hidden ? 5000 : 1000)}void tick()@@ -894,10 +894,13 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUireplies = parsed.replies.length ? parsed.replies : live.repliesbroken = parsed.broken}- // Members speak one at a time, so only the current speaker is typing.- const pending = done || !live.speaking ? [] : [live.speaking]- const speakerTool = useWork?.(work => work.bots?.[live.speaking]?.tool) ?? undefined- const speakerDoing = useWork?.(work => (work.bots?.[live.speaking]?.tool ? workPhrase(work.bots[live.speaking]) : undefined)) ?? undefined+ // Every member answering in the round is typing; what each is doing comes as text,+ // so the cell redraws only when that changes.+ const pending = done ? [] : live.speaking+ const doing = JSON.parse(useWork?.(work => JSON.stringify(pending.map((id) => {+ const tool = work.bots?.[id]?.tool+ return tool ? [tool, workPhrase(work.bots[id])] : []+ }))) ?? '[]')if (replies.length === 0 && pending.length === 0) {// A pruned tool result left nothing to draw; keep a marker row instead of an// empty turn, which reads as a blank gap on a narrow first paint.@@ -951,12 +954,13 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi}return h(GroupMessage, { key: `${reply.botId}-${index}`, bot, texts, room, roster, actions, msgKey: callId ? `${sessionId}:${callId}:${index}` : undefined, useUi, time, duration })}),- pending.map((id) => {+ pending.map((id, at) => {const bot = roster.byId[id]if (!bot) return null+ const [tool, phrase] = doing[at] ?? []return h('div', { key: `pending-${id}`, className: 'bt-activity' },- h(BotMark, { bot: bot, size: 22, state: speakerTool ? toolState(speakerTool) : 'thinking' }),- h(Shimmer, null, speakerDoing ? `${bot.name} · ${speakerDoing}…` : t('{name} is typing…', { name: bot.name })))+ h(BotMark, { bot: bot, size: 22, state: tool ? toolState(tool) : 'thinking' }),+ h(Shimmer, null, phrase ? `${bot.name} · ${phrase}…` : t('{name} is typing…', { name: bot.name })))}))}diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex 31a87212..48e69671 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -226,7 +226,7 @@ export function install(rt) {await rt.load()return ok(await rt.usageView({ timeZone: typeof body.timeZone === 'string' ? body.timeZone.slice(0, 64) : undefined }))case 'room-progress':- return ok([...rt.roomProgress.entries()].filter(([, entry]) => entry.roomId === body.roomId).map(([callId, entry]) => ({ callId, replies: entry.replies, speaking: entry.speaking ?? null })))+ return ok([...rt.roomProgress.entries()].filter(([, entry]) => entry.roomId === body.roomId).map(([callId, entry]) => ({ callId, replies: entry.replies, speaking: entry.slots.filter(slot => slot.status === 'speaking').map(slot => slot.id) })))case 'create-bot': {await rt.bootstrap()const bot = await rt.createBot({ name: body.name, role: body.role, color: body.color, instructions: body.instructions, brief: body.brief, avatar: body.avatar, model: body.model, effort: body.effort, workDir: body.workDir })diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 078987e2..2cf4cebd 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -1,15 +1,16 @@// Group chats: the room log, members' group Sessions, rounds and @mentions, round// reports, and the group tools (group_relay, read_own_chat, read_group_chat).//-// Group chat rounds. A group chat is one shared, ordered conversation, so members-// speak one at a time: a turn starts only after the previous speaker has posted or-// passed, and it shows everything that arrived since that member last looked, plus-// the speaking order and the member's place in it. Nobody answers a room that has-// moved on, and nobody has to count lines to know who went before. A plain message-// goes to every member in roster order, admin first, or to the admin alone in admin-// mode; "@Name" picks members. A reply that @mentions a member calls that member-// next, and the user's own messages are always answered. Bots may call each other-// for as long as the work needs; the user stops a group from its details.+// Group chat rounds. "@Name" calls a member, and the members one message calls start+// at the same time: a call takes effect as soon as the message that makes it is+// posted, whether the user wrote it, a member said it while working, or a Bot posted+// it while the round runs. Each turn shows everything that arrived since that member+// last looked, and who else is answering. A plain message goes to the admin alone in+// admin mode; otherwise every member answers it in turn, admin first, each after the+// one before has posted or passed, so a discussion or a count-off stays in order. A+// member answers one call at a time. The user's own messages are always answered.+// Bots may call each other for as long as the work needs; the user stops a group from+// its details.//// Work does not hold a round up: a member that is still busy with tools a little after// it started, or that is called while still at earlier work, lets the round go on. Its@@ -93,10 +94,10 @@ export const referenceNote = references => (references?.length: '')const ROOM_REPLY = 'Reply with your message for the group, no name prefix: in a discussion, one or two short messages. When you are asked to do something, do it now with your tools. The group does not wait for you and sees what you write while you work: say what you will do, write again only when something matters, and end with the result, never a promise to do it later. Reply [PASS] to stay silent when you have nothing new to add or the message is for someone else.'-const ROOM_CALLS = 'Writing "@Name" calls that member next, to answer or to do what you ask; when it finishes work you gave it, you answer its result. To only mention a member, write its name without "@".'+const ROOM_CALLS = 'Writing "@Name" calls that member at once, to answer or to do what you ask, as soon as your message is posted: call members before you start on your own part. Members called in one message start together and do not see each other\'s replies until they post, so when one needs another\'s result, call the first and ask it to call the next. When a member finishes work you gave it, you answer its result. To only mention a member, write its name without "@".'-const slotLabel = (slot) => {- if (slot.status === 'speaking') return `${slot.name} (you, now)`+const slotLabel = (slot, self) => {+ if (slot.status === 'speaking') return slot === self ? `${slot.name} (you, now)` : `${slot.name} (answering now)`if (slot.status === 'posted') return `${slot.name} (posted)`if (slot.status === 'passed') return `${slot.name} (passed)`if (slot.status === 'missed') return `${slot.name} (no answer)`@@ -226,7 +227,7 @@ export function install(rt) {// Lines from before the round's opening message are kept apart from this round, so// an earlier round (an old count-off, say) never reads as part of the current one.// `files` are the files of the lines shown, which go to the member with the prompt.- function roomPrompt(room, member, round) {+ function roomPrompt(room, member, round, slot) {const peers = room.members.filter(id => id !== member.id).map(rt.botOf).filter(Boolean).map(bot => `${bot.name}${rt.isAdminOf(room, bot.id) ? ' (admin)' : ''}`)const leads = rt.isAdminOf(room, member.id)@@ -234,13 +235,12 @@ export function install(rt) {const earlier = lines.filter(line => line.seq < round.startSeq).slice(-ROOM_EARLIER_MAX)const current = lines.filter(line => line.seq >= round.startSeq)const spokeThisRound = (room.seen[member.id] ?? 0) >= round.startSeq- const index = round.slots.findIndex(slot => slot.status === 'speaking')- const before = index- const after = round.slots.length - index - 1- const members = `Members: the user${peers.length ? `, ${peers.join(', ')}` : ''} and you${leads ? ' (admin)' : ''}. Members speak one at a time; each message is posted before the next speaker starts. ${ROOM_CALLS}`+ const members = `Members: the user${peers.length ? `, ${peers.join(', ')}` : ''} and you${leads ? ' (admin)' : ''}. ${ROOM_CALLS}`const notice = room.notice ? `Group notice (shared instructions for every member):\n${room.notice}` : ''if (round.kickoff) return { text: [members, notice, leads ? adminNote(room) : '', roomKickoff(rt.uiLanguage?.())].filter(Boolean).join('\n\n'), files: [] }- const working = workingIn(room).filter(item => item.bot.id !== member.id)+ // Members answering in this round are named with the round below.+ const answering = new Set(round.slots.filter(other => other.status === 'speaking').map(other => other.id))+ const working = workingIn(room).filter(item => item.bot.id !== member.id && !answering.has(item.bot.id)).map(item => ({ ...item, unread: unreadCount(room, item.bot.id) }))const text = [members,@@ -252,13 +252,33 @@ export function install(rt) {: 'Nothing new in this round since your last message.',round.shown?.includes(member.id) ? '' : referenceNote(round.references),working.length > 0 ? `Still at work on what they were asked; each posts here when done: ${working.map(item => `${item.bot.name} (${minutesSince(item.since)} min${item.unread > 0 ? `, with ${item.unread} group message(s) it has not read yet` : ''})`).join(', ')}.` : '',- `Speaking order for this round: ${round.slots.map(slotLabel).join(' → ')}.`,- `You are number ${index + 1} of ${round.slots.length}. ${before === 0 ? 'Nobody spoke before you' : `${before} went before you`}${after === 0 ? ', and you are the last.' : `; ${after} after you will see your message.`}`,+ ...placeLines(round, slot),ROOM_REPLY,].filter(Boolean).join('\n\n')return { text, files: [...earlier, ...current].flatMap(line => line.files ?? []) }}+ // Where a turn stands in its round: its place in the order when members take turns,+ // or who was called with it and answers at the same time; then the others' latest+ // calls in this round.+ function placeLines(round, slot) {+ const lines = []+ if (slot.ordered) {+ const order = round.slots.filter(other => other.ordered)+ const index = order.indexOf(slot)+ const after = order.length - index - 1+ lines.push(`Members answer this message one at a time: ${order.map(other => slotLabel(other, slot)).join(' → ')}.`,+ `You are number ${index + 1} of ${order.length}. ${index === 0 ? 'Nobody spoke before you' : `${index} went before you`}${after === 0 ? ', and you are the last.' : `; ${after} after you will see your message.`}`)+ } else {+ const together = round.slots.filter(other => other !== slot && other.batch === slot.batch && other.id !== slot.id)+ if (together.length > 0) lines.push(`Called together with you: ${together.map(other => other.name).join(', ')}. You answer at the same time and do not see each other's replies until they post.`)+ }+ const latest = new Map()+ for (const other of round.slots) if (other.id !== slot.id && !(slot.ordered && other.ordered)) latest.set(other.id, other)+ if (latest.size > 0) lines.push(`Also in this round: ${[...latest.values()].map(other => slotLabel(other, slot)).join(', ')}.`)+ return lines+ }+// Members whose turn in this group is running, and since when.const workingIn = room => room.members.flatMap((id) => {const entry = rt.live.get(room.sessions?.[id])@@ -287,8 +307,9 @@ export function install(rt) {// round, or null when the round was stopped. The wait restarts on each event of the// member's Session, so a member at work is never cut off. `by` is the member that// called it, which answers what the turn posts after the round moved on. What the- // member writes before its last step is posted at once and collected in `said`.- async function roomTurn(room, member, sessionId, { text, files }, note, signal, round, by, said = []) {+ // member writes before its last step is posted at once and collected in `said`, and+ // `heard` takes each such line once it is posted.+ async function roomTurn(room, member, sessionId, { text, files }, note, signal, round, by, said = [], heard = () => {}) {if (signal.aborted) return nullconst startedAt = Date.now()const exchangeId = randomUUID()@@ -319,6 +340,7 @@ export function install(rt) {if (isPass(step)) returnsaid.push(step)postInRound(room, round, member, step, Date.now() - startedAt)+ heard(step)}touch()rt.roomWaiters.set(exchangeId, { sessionId, botId: member.id, roomId: room.id, resolve: finish, fail: failure => finish({ failure }), touch, work, say, approval: () => finish({ approval: true }) })@@ -370,33 +392,65 @@ export function install(rt) {if (QUICK_TOOLS.has(tool)) returnfor (const waiter of waitersOf(sessionId)) waiter.work()}+ // The group Session's inbox changed: a running round looks for the user's messages+ // once DSH has finished the change.+ rt.nudgeRoom = (roomId) => {+ for (const round of rt.roomProgress.values()) {+ if (round.roomId === roomId) setImmediate(() => round.nudge?.())+ }+ }- // A called member moves up if it is still waiting, or gets one more turn if it- // already spoke; either way it goes right after slot `index`. `by` is the calling- // member, if a member called.- function callMembers(round, index, callees, note, by) {- let next = index + 1+ // Calls members into a round; the members one call names share a batch. Ordered calls+ // (a plain message everyone answers in turn) go ahead of the ordered calls still+ // waiting, in their own order; the others start as soon as their member is free. A+ // member still waiting is called once, with the newest note: an ordered call moves+ // it up the order, any other call lets it start at once. `by` is the calling member,+ // if a member called.+ function callIn(round, callees, note, by, { ordered = false } = {}) {+ if (callees.length === 0) return+ round.batches = (round.batches ?? 0) + 1+ let lastfor (const peer of callees) {- const waiting = round.slots.findIndex((other, at) => at > index && other.id === peer.id && other.status === 'waiting')- const called = waiting === -1 ? { id: peer.id, name: peer.name, status: 'waiting' } : round.slots.splice(waiting, 1)[0]- called.note = note- if (by === undefined) delete called.by- else called.by = by- round.slots.splice(next, 0, called)- next += 1+ const waiting = round.slots.findIndex(slot => slot.id === peer.id && slot.status === 'waiting')+ const moves = waiting === -1 || (ordered && round.slots[waiting].ordered === true)+ const slot = waiting === -1 ? { id: peer.id, name: peer.name, status: 'waiting' } : round.slots[waiting]+ if (moves && waiting !== -1) round.slots.splice(waiting, 1)+ slot.note = note+ slot.batch = round.batches+ if (by === undefined) delete slot.by+ else slot.by = by+ if (!moves) slot.ordered = false+ else if (!ordered) round.slots.push(slot)+ else {+ slot.ordered = true+ const queue = round.slots.findIndex(other => other.ordered && other.status === 'waiting')+ round.slots.splice(last ? round.slots.indexOf(last) + 1 : queue === -1 ? round.slots.length : queue, 0, slot)+ last = slot+ }}+ round.nudge?.()+ }++ // Whether a waiting call can start now: its member answers nothing else in this+ // round, and an ordered call waits for the ordered calls before it.+ const startable = (round, slot) => {+ if (slot.status !== 'waiting' || round.slots.some(other => other.id === slot.id && other.status === 'speaking')) return false+ if (!slot.ordered) return true+ const at = round.slots.indexOf(slot)+ return round.slots.every((other, index) => !other.ordered || other === slot || (other.status !== 'speaking' && !(other.status === 'waiting' && index < at)))}// LEGACY: groups used to park Bot calls past a relay limit until the user went on.- // Calls still parked from then run in the group's next round, after its opening- // speakers; one already waiting in the round is not queued twice.+ // Calls still parked from then run in the group's next round, with its opening+ // speakers; one already waiting in the round is not called twice.const releaseParked = (room, round) => {const parked = room.paused ?? []delete room.pausedfor (const entry of parked) {if (round.slots.some(slot => slot.id === entry.id && slot.status === 'waiting')) continue+ round.batches = (round.batches ?? 0) + 1round.slots.push({- id: entry.id, name: entry.name, status: 'waiting',+ id: entry.id, name: entry.name, status: 'waiting', batch: round.batches,...(entry.note !== undefined ? { note: entry.note } : {}),...(entry.by !== undefined ? { by: entry.by } : {}),})@@ -419,11 +473,11 @@ export function install(rt) {return lines})- // Messages the user sent while this round is running post into the log before the- // next speaker, so everyone still to speak sees them. The members the message's own- // round would open with answer it next, inside this round. Each message leaves the- // Session's inbox, so it does not open another round when this one ends.- function drainRoomInbox(room, round, index, agent) {+ // Messages the user sent while this round is running post into the log at once, so+ // every turn that starts from now on sees them. The members the message's own round+ // would open with answer it inside this round, as soon as they are free. Each message+ // leaves the Session's inbox, so it does not open another round when this one ends.+ function drainRoomInbox(room, round, agent) {// The greeting's prompt tells the admin the user has not written yet.if (round.kickoff) returnconst lines = waitingLines(agent).filter(line => agent.inbox.remove(line.id))@@ -434,90 +488,53 @@ export function install(rt) {round.replies.push({ kind: 'user', text: line.text, time: Date.now() })const { all, found } = mentionsIn(line.text, members)const note = all || found.length > 0 ? 'the user mentioned you' : 'new message from the user'- callMembers(round, index - 1, openingSpeakers(room, { text: line.text }), note)+ const { speakers, ordered } = openingCall(room, { text: line.text })+ callIn(round, speakers, note, undefined, { ordered })}void rt.save().catch(() => {})}+ // The members a member's message calls: those it names with @, or everyone when the+ // admin writes "@all" (only the admin, so a member cannot set off a storm). A turn+ // calls each member once, however many of its lines name it.+ function callFrom(room, round, member, text, called) {+ const everyone = room.members.map(rt.botOf).filter(Boolean)+ const others = everyone.filter(other => other.id !== member.id)+ const { all, found: named } = mentionsIn(text, everyone)+ const found = named.filter(other => other.id !== member.id)+ const callees = (rt.isAdminOf(room, member.id) && all ? [...found, ...others.filter(other => !found.includes(other))] : found)+ .filter(peer => !called.has(peer.id))+ for (const peer of callees) called.add(peer.id)+ callIn(round, callees, `${member.name} mentioned you`, member.id)+ }++ // A round runs every call that can start, and wakes when a turn ends, a call comes+ // in, the user writes or the round is stopped. It ends when no turn runs and no call+ // or message waits. The inbox check keeps a message sent during the last turn inside+ // this round.async function runRound(room, round, signal, agent) {- // The inbox check keeps a message sent during the last speaker's turn inside- // this round: it drains at the loop's head even once the slots ran out.- for (let index = 0; index < round.slots.length || waitingLines(agent).length > 0; index += 1) {+ const turns = new Set()+ let due = true+ let wake = () => {}+ round.nudge = () => { due = true; wake() }+ signal.addEventListener('abort', round.nudge, { once: true })+ while (!signal.aborted) {+ if (!due) await new Promise((resolve) => { wake = resolve })+ due = falseif (signal.aborted) break- drainRoomInbox(room, round, index, agent)- if (index >= round.slots.length) break- const slot = round.slots[index]- const member = rt.botOf(slot.id)- // Settings may change mid-round, for example when the admin removes someone.- if (member === undefined || !room.members.includes(slot.id)) {- slot.status = 'left'- continue- }- slot.status = 'speaking'- round.speaking = member.id- let session- try {- session = await groupSessionFor(room, member)- } catch (error) {- rt.warn('ds-bot: group Session for %s in %s failed: %s', member.name, room.name, error)- round.speaking = null- slot.status = 'failed'- round.failed.push(member.name)- round.replies.push({ kind: 'failed', botId: member.id, name: member.name, color: member.color, code: 'SESSION', text: String(error?.message ?? error).slice(0, 300), time: Date.now() })- continue- }- if (session === undefined) {- round.speaking = null- slot.status = 'left'- continue- }- await loadGroupLines(room)- const prompt = roomPrompt(room, member, round)- round.shown?.push(member.id)- const text = session.brief === undefined ? prompt.text : `${session.brief}\n\n${prompt.text}`- const said = []- const startedAt = Date.now()- const reply = await roomTurn(room, member, session.id, { text, files: prompt.files }, slot.note ?? 'your turn', signal, round, slot.by, said)- round.speaking = null- const final = typeof reply === 'string' && !isPass(reply) ? reply : undefined- if (reply?.failure !== undefined) {- // Not a pass: the user sees why the member is silent, and the round goes on.- slot.status = 'failed'- round.failed.push(member.name)- const { code, status, message } = reply.failure- round.replies.push({ kind: 'failed', botId: member.id, name: member.name, color: member.color, code, ...(status ? { status } : {}), text: message, time: Date.now() })- } else if (reply?.approval) {- // The member's turn goes on in the background and posts when it ends.- slot.status = 'waiting-approval'- round.replies.push({ kind: 'approval', botId: member.id, name: member.name, color: member.color, time: Date.now() })- } else if (reply?.working) {- slot.status = 'working'- round.replies.push({ kind: 'working', botId: member.id, name: member.name, color: member.color, time: Date.now() })- } else if (final !== undefined || (typeof reply === 'string' && said.length > 0)) {- slot.status = 'posted'- if (final !== undefined) postInRound(room, round, member, final, Date.now() - startedAt)- } else {- slot.status = typeof reply === 'string' ? 'passed' : 'missed'- round.passed.push(member.name)- if (reply?.missed) {- round.replies.push({ kind: 'missed', botId: member.id, name: member.name, color: member.color, time: Date.now() })- // The round moved on without this member: the log shows the call and then- // silence, which reads as a lost message. The group is told the baton was- // dropped, and what brings the member back.- appendRoom(room, { who: 'DS Bot', kind: 'notice', reason: 'missed', names: [member.name], minutes: Math.round(ROOM_REPLY_TIMEOUT_MS / 60000) })- }+ drainRoomInbox(room, round, agent)+ for (const slot of round.slots) {+ if (!startable(round, slot)) continue+ const turn = memberTurn(room, round, slot, signal)+ .catch(error => rt.warn('ds-bot: group turn of %s in %s failed: %s', slot.name, room.name, error))+ .finally(() => { turns.delete(turn); round.nudge() })+ turns.add(turn)}- const spoken = final === undefined ? said : [...said, final]- if (spoken.length === 0) continue- // Only the admin's "@all" calls everyone, so a member cannot set off a storm.- const leads = rt.isAdminOf(room, member.id)- const everyone = room.members.map(rt.botOf).filter(Boolean)- const others = everyone.filter(other => other.id !== member.id)- const { all, found: named } = mentionsIn(spoken.join('\n\n'), everyone)- const found = named.filter(other => other.id !== member.id)- const callees = leads && all ? [...found, ...others.filter(other => !found.includes(other))] : found- callMembers(round, index, callees, `${member.name} mentioned you`, member.id)+ // The greeting round leaves the user's messages for a round of their own.+ if (turns.size === 0 && !round.slots.some(slot => slot.status === 'waiting') && (round.kickoff || waitingLines(agent).length === 0)) break}+ await Promise.allSettled([...turns])+ delete round.nudge// The admin was alone with the user's message and passed: the round ends with// nothing said. The group says so once, so the user knows to call a member.const alone = round.soleAdmin !== undefined && round.slots.find(slot => slot.id === round.soleAdmin.id)?.status === 'passed'@@ -531,9 +548,74 @@ export function install(rt) {}}+ // One call's turn in the round. Its status says how it ended; what it says calls+ // members as soon as each line is posted.+ async function memberTurn(room, round, slot, signal) {+ const member = rt.botOf(slot.id)+ // Settings may change mid-round, for example when the admin removes someone.+ if (member === undefined || !room.members.includes(slot.id)) {+ slot.status = 'left'+ return+ }+ slot.status = 'speaking'+ let session+ try {+ session = await groupSessionFor(room, member)+ } catch (error) {+ rt.warn('ds-bot: group Session for %s in %s failed: %s', member.name, room.name, error)+ slot.status = 'failed'+ round.failed.push(member.name)+ round.replies.push({ kind: 'failed', botId: member.id, name: member.name, color: member.color, code: 'SESSION', text: String(error?.message ?? error).slice(0, 300), time: Date.now() })+ return+ }+ if (session === undefined) {+ slot.status = 'left'+ return+ }+ await loadGroupLines(room)+ const prompt = roomPrompt(room, member, round, slot)+ round.shown?.push(member.id)+ const text = session.brief === undefined ? prompt.text : `${session.brief}\n\n${prompt.text}`+ const said = []+ const called = new Set()+ const startedAt = Date.now()+ const reply = await roomTurn(room, member, session.id, { text, files: prompt.files }, slot.note ?? 'your turn', signal, round, slot.by, said, line => callFrom(room, round, member, line, called))+ const final = typeof reply === 'string' && !isPass(reply) ? reply : undefined+ if (reply?.failure !== undefined) {+ // Not a pass: the user sees why the member is silent, and the round goes on.+ slot.status = 'failed'+ round.failed.push(member.name)+ const { code, status, message } = reply.failure+ round.replies.push({ kind: 'failed', botId: member.id, name: member.name, color: member.color, code, ...(status ? { status } : {}), text: message, time: Date.now() })+ } else if (reply?.approval) {+ // The member's turn goes on in the background and posts when it ends.+ slot.status = 'waiting-approval'+ round.replies.push({ kind: 'approval', botId: member.id, name: member.name, color: member.color, time: Date.now() })+ } else if (reply?.working) {+ slot.status = 'working'+ round.replies.push({ kind: 'working', botId: member.id, name: member.name, color: member.color, time: Date.now() })+ } else if (final !== undefined || (typeof reply === 'string' && said.length > 0)) {+ slot.status = 'posted'+ if (final !== undefined) {+ postInRound(room, round, member, final, Date.now() - startedAt)+ callFrom(room, round, member, final, called)+ }+ } else {+ slot.status = typeof reply === 'string' ? 'passed' : 'missed'+ round.passed.push(member.name)+ if (reply?.missed) {+ round.replies.push({ kind: 'missed', botId: member.id, name: member.name, color: member.color, time: Date.now() })+ // The round moved on without this member: the log shows the call and then+ // silence, which reads as a lost message. The group is told the baton was+ // dropped, and what brings the member back.+ appendRoom(room, { who: 'DS Bot', kind: 'notice', reason: 'missed', names: [member.name], minutes: Math.round(ROOM_REPLY_TIMEOUT_MS / 60000) })+ }+ }+ }+ctx.tools.register(defineTool({name: 'group_relay',- description: 'Group chat relay only. Deliver the latest user message to the Bots in this group chat, one at a time, and collect their replies.',+ description: 'Group chat relay only. Deliver the latest user message to the Bots it calls in this group chat, and collect their replies.',parameters: {},output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },async execute(_args, exec) {@@ -565,13 +647,15 @@ export function install(rt) {}await rt.save()// An event post, and a member post that calls nobody, never pick the speakers- // over a message queued with them.+ // over a message queued with them. A post whose members an earlier round already+ // called (`called`) picks none.const callsNobody = post => post.member === true && openingSpeakers(room, post).length === 0- const opener = posts.findLast(post => !event(post) && !callsNobody(post)) ?? posts.findLast(post => !event(post)) ?? posts.at(-1)+ const open = posts.filter(post => post.called !== true)+ const opener = open.findLast(post => !event(post) && !callsNobody(post)) ?? open.findLast(post => !event(post)) ?? open.at(-1) ?? { text: '', quiet: true }const references = posts.flatMap(post => post.references ?? [])// A member a Bot's post calls by name works for that Bot.const named = opener.botId === undefined ? [] : mentionsIn(opener.text ?? '', room.members.map(rt.botOf).filter(Boolean)).found- const speakers = openingSpeakers(room, opener)+ const { speakers, ordered } = openingCall(room, opener)// The admin alone with the user's message: when it passes, the round ends with// nothing said, and the group says so once.const admin = room.members.map(rt.botOf).filter(Boolean).find(bot => rt.isAdminOf(room, bot.id))@@ -584,13 +668,14 @@ export function install(rt) {...(opener.kickoff ? { kickoff: true } : {}),...(references.length > 0 ? { references, shown: [] } : {}),slots: speakers.map(member => ({- id: member.id, name: member.name, status: 'waiting',+ id: member.id, name: member.name, status: 'waiting', batch: 1,+ ...(ordered ? { ordered: true } : {}),...(opener.kickoff ? { note: 'the group was just created' } : {}),...(named.includes(member) ? { by: opener.botId } : {}),...(opener.done ? { note: `${opener.name ?? 'a member'} finished the work you asked for` } : {}),})),+ batches: 1,...(soleAdmin ? { soleAdmin: { id: admin.id, name: admin.name, color: admin.color } } : {}),- speaking: null,replies: [],passed: [],failed: [],@@ -624,9 +709,19 @@ export function install(rt) {for (const turn of round.started) void rt.stopRoomTurn?.(room.sessions?.[turn.botId] ?? turn.sessionId, turn.exchangeId)}await rt.save()- for (const post of posts) {+ for (const post of open) {if (post.reportBack && rt.botOf(post.botId)) void reportRound(room, post, round)}+ // A post this round took in while it ran gets the replies of the members it called.+ for (const { post, ids, from } of round.reports ?? []) {+ if (!rt.botOf(post.botId)) continue+ const names = ids.map(id => rt.botOf(id)?.name).filter(Boolean)+ void reportRound(room, post, {+ replies: round.replies.slice(from).filter(reply => ids.includes(reply.botId)),+ passed: round.passed.filter(name => names.includes(name)),+ failed: round.failed.filter(name => names.includes(name)),+ })+ }exec.concludeTurn?.()return JSON.stringify({ replies: round.replies, passed: round.passed, ...(round.failed.length > 0 ? { failed: round.failed } : {}) })},@@ -723,30 +818,58 @@ export function install(rt) {// the admin answers alone in admin mode, or first of everyone. What a member posts// after its round moved on is answered by the member that asked for it; work the// user asked for is left for the user to read.- function openingSpeakers(room, opener) {+ // `ordered`: a plain message everyone answers in turn, admin first; any other call+ // starts its members at once.+ function openingCall(room, opener) {const everyone = room.members.map(rt.botOf).filter(Boolean)const members = everyone.filter(bot => bot.id !== opener.botId)const admin = members.find(bot => rt.isAdminOf(room, bot.id))- if (opener.kickoff) return admin ? [admin] : []- if (opener.quiet) return []- if (opener.done) return members.filter(bot => bot.id === opener.askedBy)+ const at = speakers => ({ speakers, ordered: false })+ if (opener.kickoff) return at(admin ? [admin] : [])+ if (opener.quiet) return at([])+ if (opener.done) return at(members.filter(bot => bot.id === opener.askedBy))const { all, found: named } = mentionsIn(opener.text, everyone, opener.references)const found = named.filter(bot => bot.id !== opener.botId)- if (opener.progress) return found- if (opener.late) return found.length > 0 ? found : members.filter(bot => bot.id === opener.askedBy)- if (opener.member) return found- if (found.length > 0 && !all) return found- if (!all && room.mode === 'admin' && admin) return [admin]- return admin ? [admin, ...members.filter(bot => bot !== admin)] : members+ if (opener.progress) return at(found)+ if (opener.late) return at(found.length > 0 ? found : members.filter(bot => bot.id === opener.askedBy))+ if (opener.member) return at(found)+ if (found.length > 0 && !all) return at(found)+ if (!all && room.mode === 'admin' && admin) return at([admin])+ const speakers = admin ? [admin, ...members.filter(bot => bot !== admin)] : members+ return { speakers, ordered: !all && speakers.length > 1 }+ }+ const openingSpeakers = (room, opener) => openingCall(room, opener).speakers++ // A Bot's post that lands while a round runs calls its members in that round at+ // once, as the relay it opens would. Returns whether it called anyone. A post that+ // wants the replies (`reportBack`) gets those of the members it called when the+ // round ends.+ function callPost(room, round, sender, text, extra) {+ if (extra.failed !== undefined || extra.resumed || extra.stopped) return false+ const post = { ...extra, botId: sender.id, name: sender.name, text }+ const { speakers, ordered } = openingCall(room, post)+ if (speakers.length === 0) return false+ const named = mentionsIn(text, room.members.map(rt.botOf).filter(Boolean)).found+ const by = speakers.filter(peer => named.includes(peer))+ const rest = speakers.filter(peer => !named.includes(peer))+ const note = extra.done ? `${sender.name} finished the work you asked for` : undefined+ callIn(round, by, note ?? `${sender.name} mentioned you`, sender.id, { ordered })+ callIn(round, rest, note, undefined, { ordered })+ if (extra.reportBack) {+ (round.reports ??= []).push({ post: { botId: sender.id, name: sender.name, reportBack: true, ...(extra.sub ? { sub: extra.sub } : {}) }, ids: speakers.map(peer => peer.id), from: round.replies.length })+ }+ return true}// A Bot's message into the group's own Session, which relays it as a new round.// While a round runs, the post goes into the group's log and that round's replies at- // once, so it is not held back until the round ends; the relay it still opens does not- // write it again (source `logged`).+ // once, and the members it calls start in that round, so it is not held back until+ // the round ends; the relay it still opens does not write it again (source `logged`)+ // nor call them again (source `called`).async function postToRoom(room, sender, text, extra = {}, files = []) {const running = [...rt.roomProgress.values()].find(round => round.roomId === room.id)let logged+ let called = falseif (running !== undefined) {ensureRoomLog(room)if (extra.failed !== undefined) {@@ -766,12 +889,13 @@ export function install(rt) {running.replies.push({ botId: sender.id, name: sender.name, color: sender.color, text: line, time: Date.now() })logged = room.seq}+ called = callPost(room, running, sender, text, extra)await rt.save()}const agent = await rt.resolveAgent(room.id)agent.followup(createUserMessage({content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }, ...files.map(attachment => ({ type: 'file', attachment }))],- source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, ...extra, ...(logged !== undefined ? { logged } : {}) },+ source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, ...extra, ...(logged !== undefined ? { logged } : {}), ...(called ? { called: true } : {}) },}))await ctx.sessions.flush(agent.session)}diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex 5a1e3cc6..73b11b81 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -316,9 +316,10 @@ export function install(rt) {.map(([id, entry]) => [id, entry.steeredAt]))// Per group, the members whose turn there is running or who move on to a fresh part;- // the round's current speaker is marked, since its round shows it.+ // the members answering in a round are marked, since the round shows them.const roomWorkView = () => {- const speaking = new Set([...roomProgress.values()].map(round => `${round.roomId}:${round.speaking}`))+ const speaking = new Set([...roomProgress.values()].flatMap(round => round.slots+ .filter(slot => slot.status === 'speaking').map(slot => `${round.roomId}:${slot.id}`)))const rooms = {}const add = (roomId, botId, work) => {if (rooms[roomId]?.some(item => item.botId === botId)) return@@ -462,6 +463,7 @@ export function install(rt) {// A post written into a running round already carries its log seq, or true// when its event needed none; the relay must not write it again....(source.logged !== undefined ? { logged: source.logged } : {}),+ ...(source.called ? { called: true } : {}),})} else if (source?.kind === SOURCE_KIND && source.role === 'kickoff' && rt.roomOf(id)) {queueRoomMessage(id, { text: '', kickoff: true })@@ -513,6 +515,8 @@ export function install(rt) {break}case 'agent/inbox/spliced':+ // A message the user sends to a group while its round runs joins that round.+ if (rt.roomOf(id)) rt.nudgeRoom?.(id)// A message the user steered into the running turn is fresh input, like// a send that never queued.if (event.data?.target === 'next-step' && entry.turn !== undefineddiff --git a/ds-bot/test/group-work.test.js b/ds-bot/test/group-work.test.jsindex b7eaf099..4a393f48 100644--- a/ds-bot/test/group-work.test.js+++ b/ds-bot/test/group-work.test.js@@ -486,47 +486,56 @@ const busyRound = async (t, room, services) => {return { host, first }}-test('a post during a running round is in the log at once, once, and shows in the round', async (t) => {+test('a post during a running round is in the log at once, once, and calls its members in that round', async (t) => {const { host, first } = await busyRound(t)await host.tool('post_to_group', { group: 'Ops', message: '@Tester 看一下文档' }, 'a')- const during = logLines(host)- const logged = during.at(-1)+ const logged = logLines(host).at(-1)assert.deepEqual([logged.who, logged.botId, logged.text], ['Chief', 'a', '@Tester 看一下文档'])const post = host.takePost()assert.equal(post.source.logged, logged.seq)- host.finish('gb', '整理好了。')- await settle(() => first() !== undefined)- assert.ok(first().replies.some(reply => reply.botId === 'a' && reply.text === '@Tester 看一下文档'))+ assert.equal(post.source.called, true)- // The relay the post opened skips its line but still calls the member it named.- const second = host.round('c2', post)+ // The Tester starts in the running round at once, while the Writer still works.await settle(() => host.agentOf('gc').calls.length === 1)assert.equal(host.begin('gc').source.askedBy, 'a')assert.match(text(host.agentOf('gc').calls[0]), /Chief: @Tester 看一下文档/)host.finish('gc', '看过了。')+ host.finish('gb', '整理好了。')+ await settle(() => first() !== undefined)+ assert.ok(first().replies.some(reply => reply.botId === 'a' && reply.text === '@Tester 看一下文档'))+ assert.ok(first().replies.some(reply => reply.botId === 'c' && reply.text === '看过了。'))++ // The relay the post still opens calls nobody again and writes the line nowhere.+ const second = host.round('c2', post)await settle(() => second() !== undefined)+ assert.deepEqual(second().replies, [])+ assert.equal(host.agentOf('gc').calls.length, 1)assert.equal(logLines(host).filter(line => line.text === '@Tester 看一下文档').length, 1)})-test('a post during a running round with report_back reports only the round it opened', async (t) => {+test('a post during a running round with report_back gets the replies of the members it called', async (t) => {const { host, first } = await busyRound(t)await host.tool('post_to_group', { group: 'Ops', message: '@Tester 看一下文档', report_back: true }, 'a')const post = host.takePost()assert.equal(typeof post.source.logged, 'number')- host.finish('gb', '整理好了。')- await settle(() => first() !== undefined)- const second = host.round('c2', post)await settle(() => host.agentOf('gc').calls.length === 1)host.begin('gc')host.finish('gc', '看过了。')- await settle(() => second() !== undefined)+ host.finish('gb', '整理好了。')+ await settle(() => first() !== undefined)await settle(() => host.agentOf('a').calls.length === 1)const report = host.agentOf('a').calls[0]assert.match(text(report), /Tester: 看过了。/)- assert.doesNotMatch(text(report), /看一下文档/)+ assert.doesNotMatch(text(report), /看一下文档|Writer/)++ // The relay the post opens reports nothing again.+ const second = host.round('c2', post)+ await settle(() => second() !== undefined)+ await new Promise(resolve => setImmediate(resolve))+ assert.equal(host.agentOf('a').calls.length, 1)})-test('a late reply during a running round is logged at once and not repeated', async (t) => {+test('a late reply during a running round is logged at once, called in that round and not repeated', async (t) => {t.mock.timers.enable({ apis: ['setTimeout'] })const host = await start(t)const first = host.round('c1', host.say('@Chief 安排一下文档'))@@ -549,16 +558,20 @@ test('a late reply during a running round is logged at once and not repeated', aassert.equal(post.source.late, true)assert.equal(typeof post.source.logged, 'number')assert.ok(logLines(host).some(line => line.who === 'Writer' && line.text === '整理好了,在 docs/ 下。'))+ assert.equal(post.source.called, true)+ // The Chief, which asked for it, answers the result in this round once its own turn ends.host.finish('ga', '确认过了。')+ await settle(() => host.agentOf('ga').calls.length === 3)+ host.begin('ga')+ host.finish('ga', '[PASS]')await settle(() => second() !== undefined)assert.ok(second().replies.some(reply => reply.botId === 'b' && reply.text === '整理好了,在 docs/ 下。'))- // The relay it opens still calls the member that asked, and writes the line nowhere again.+ // The relay it opens calls nobody again, and writes the line nowhere again.const third = host.round('c3', post)- await settle(() => host.agentOf('ga').calls.length === 3)- host.begin('ga')- host.finish('ga', '[PASS]')await settle(() => third() !== undefined)+ assert.deepEqual(third().replies, [])+ assert.equal(host.agentOf('ga').calls.length, 3)assert.equal(logLines(host).filter(line => line.text === '整理好了,在 docs/ 下。').length, 1)})@@ -601,13 +614,15 @@ test('a Main Bot outside the group posts into its running round, and a long postassert.match(line.text, /\[File "Post from Chief\.txt"/)const post = host.takePost()assert.equal(typeof post.source.logged, 'number')+ // The admin answers the post in the running round, once its own turn there ends.host.finish('gb', '整理好了。')- await settle(() => first() !== undefined)- const second = host.round('c2', post)await settle(() => host.agentOf('gb').calls.length === 2)host.begin('gb')host.finish('gb', '收到,看一下。')+ await settle(() => first() !== undefined)+ const second = host.round('c2', post)await settle(() => second() !== undefined)+ assert.deepEqual(second().replies, [])assert.equal(logLines(host).filter(entry => entry.files?.length === 1).length, 1)})@@ -871,19 +886,20 @@ test('what a member writes while it works shows in the round at once, and its @await settle(() => host.agentOf('gb').calls.length === 1)host.begin('gb')step(host, 'gb', '收到,我先看看 docs/ 的结构。@Tester 你等下帮我验一下', 'k1', 'list_bots')- await settle(() => true)+ // The line calls the Tester at once, while the Writer still works.+ await settle(() => host.agentOf('gc').calls.length === 1)const live = await progress(host)assert.deepEqual(live.replies.map(reply => [reply.name, reply.text]), [['Writer', '收到,我先看看 docs/ 的结构。@Tester 你等下帮我验一下']])- assert.equal(live.speaking, 'b')+ assert.deepEqual(live.speaking, ['b', 'c'])+ assert.match(text(host.begin('gc')), /Writer: 收到,我先看看 docs\/ 的结构。/)+ host.finish('gc', '验过了。')host.emit('gb', 'tool/result', { callId: 'k1' })host.finish('gb', '整理好了。')- await settle(() => host.agentOf('gc').calls.length === 1)- assert.match(text(host.begin('gc')), /Writer: 收到,我先看看 docs\/ 的结构。[\s\S]*Writer: 整理好了。/)- host.finish('gc', '验过了。')await settle(() => result() !== undefined)- assert.deepEqual(result().replies.map(reply => [reply.name, reply.text]), [['Writer', '收到,我先看看 docs/ 的结构。@Tester 你等下帮我验一下'], ['Writer', '整理好了。'], ['Tester', '验过了。']])+ assert.deepEqual(result().replies.map(reply => [reply.name, reply.text]), [['Writer', '收到,我先看看 docs/ 的结构。@Tester 你等下帮我验一下'], ['Tester', '验过了。'], ['Writer', '整理好了。']])+ assert.equal(host.agentOf('gc').calls.length, 1, 'one call per turn, however many lines name the member')const log = JSON.parse(readFileSync(join(host.home, 'state.json'), 'utf8')).rooms.r1.log- assert.deepEqual(log.map(line => line.who), ['User', 'Writer', 'Writer', 'Tester'])+ assert.deepEqual(log.map(line => line.who), ['User', 'Writer', 'Tester', 'Writer'])})test('a member whose every message went out while it worked counts as posted, not passed', async (t) => {diff --git a/ds-bot/test/rounds.test.js b/ds-bot/test/rounds.test.jsindex d8d9b5f7..8d38f70a 100644--- a/ds-bot/test/rounds.test.js+++ b/ds-bot/test/rounds.test.js@@ -683,17 +683,19 @@ test('calls parked under the old relay limit run in the group\'s next round', asstate().paused = [{ id: writer.id, name: 'Writer', note: 'Chief mentioned you', by: chief }]await rt.save()- // The user's next message opens the round; its own speaker, the admin, goes first.+ // The user's next message opens the round: its own speaker, the admin, and the+ // parked call start together.sent.length = 0await emit(room.id, userMessage('Status, please'))assert.equal(state().paused.length, 1, 'still parked until a round runs')const running = relay(room.id, 'relay')const first = await turnFor(sent)- assert.equal(first.sessionId, state().sessions[chief])- await answer(first.sessionId, first.message.source.exchangeId, 'All fine.', 1)- const parked = await turnFor(sent, first)- assert.equal(parked.sessionId, state().sessions[writer.id], 'the parked call runs after the round\'s own speaker')+ const second = await turnFor(sent, first)+ const [own, parked] = first.sessionId === state().sessions[chief] ? [first, second] : [second, first]+ assert.equal(own.sessionId, state().sessions[chief])+ assert.equal(parked.sessionId, state().sessions[writer.id], 'the parked call runs')assert.match(parked.message.content[0].text, /Chief mentioned you/)+ await answer(own.sessionId, own.message.source.exchangeId, 'All fine.', 1)await answer(parked.sessionId, parked.message.source.exchangeId, 'On it.', 2)await runningassert.equal(state().paused, undefined)@@ -852,3 +854,82 @@ test('a member still at work is shown with the group messages it has not read yeawait second0})++// #726: members one message calls start together, and a user's message mid-round+// reaches its members at once instead of waiting for the members already answering.+async function trio(call, sent) {+ const chief = (await call('state', {})).value.mainBotId+ const writer = (await call('create-bot', { name: 'Writer' })).value+ const tester = (await call('create-bot', { name: 'Tester' })).value+ const room = (await call('create-room', { name: 'R3', members: [chief, writer.id, tester.id] })).value+ await call('update-room', { id: room.id, mode: 'admin' })+ sent.length = 0+ return room+}++test('members called in one message start together, each told who else answers', async (t) => {+ const { call, emit, userMessage, relay, answer, stop, sent } = start()+ t.after(stop)+ const room = await trio(call, sent)+ await emit(room.id, userMessage('Search it, all of you'))+ const running = relay(room.id, 'relay')+ const admin = await turnFor(sent)+ await answer(admin.sessionId, admin.message.source.exchangeId, '@Writer @Tester search it', 1)+ // Both prompts go out before either member answers.+ const first = await turnFor(sent, admin)+ const second = await turnFor(sent, admin, first)+ assert.ok(first && second, 'both members got their turn at once')+ const prompts = [first, second].map(entry => entry.message.content[0].text)+ assert.ok(prompts.some(prompt => /Called together with you: Tester\./.test(prompt)))+ assert.ok(prompts.some(prompt => /Called together with you: Writer\./.test(prompt)))+ assert.ok(prompts.every(prompt => !/one at a time/.test(prompt)))+ await answer(second.sessionId, second.message.source.exchangeId, 'Second found it.', 2)+ await answer(first.sessionId, first.message.source.exchangeId, 'First found it too.', 3)+ const result = JSON.parse(await running)+ assert.deepEqual(result.replies.map(reply => reply.text), ['@Writer @Tester search it', 'Second found it.', 'First found it too.'])+})++test('a user message mid-round reaches the admin at once while a member still answers', async (t) => {+ const { call, emit, userMessage, compose, relay, answer, stop, sent, rt } = start()+ t.after(stop)+ const room = await trio(call, sent)+ const chief = rt.state.mainBotIds[0]+ await emit(room.id, userMessage('Start'))+ const running = relay(room.id, 'relay')+ const admin = await turnFor(sent)+ await answer(admin.sessionId, admin.message.source.exchangeId, '@Writer go', 1)+ const writer = await turnFor(sent, admin)+ // The Writer is still answering when the user writes; DSH reports the inbox change.+ await compose(room.id, 'why is the Tester idle?')+ await emit(room.id, { type: 'agent/inbox/spliced', data: { target: 'next-turn', inserted: [] } })+ const again = await turnFor(sent, admin, writer)+ assert.equal(again.sessionId, rt.state.rooms[room.id].sessions[chief], 'the admin answers the user without waiting for the Writer')+ assert.match(again.message.content[0].text, /why is the Tester idle\?/)+ assert.match(again.message.content[0].text, /Writer \(answering now\)/)+ await answer(again.sessionId, again.message.source.exchangeId, 'It was not called.', 2)+ await answer(writer.sessionId, writer.message.source.exchangeId, 'Done.', 3)+ const result = JSON.parse(await running)+ assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'User', 'Chief', 'Writer'])+})++test('a plain message in a group where everyone answers still goes one member at a time', async (t) => {+ const { call, emit, userMessage, relay, answer, stop, sent } = start()+ t.after(stop)+ const room = await trio(call, sent)+ await call('update-room', { id: room.id, mode: 'everyone' })+ await emit(room.id, userMessage('Count off'))+ const running = relay(room.id, 'relay')+ const first = await turnFor(sent)+ assert.match(first.message.content[0].text, /Members answer this message one at a time/)+ assert.match(first.message.content[0].text, /You are number 1 of 3/)+ await settle()+ assert.equal(sent.filter(entry => entry.message.source.role === 'room').length, 1, 'the next member waits')+ await answer(first.sessionId, first.message.source.exchangeId, 'one', 1)+ const second = await turnFor(sent, first)+ assert.match(second.message.content[0].text, /You are number 2 of 3/)+ await answer(second.sessionId, second.message.source.exchangeId, 'two', 2)+ const third = await turnFor(sent, first, second)+ await answer(third.sessionId, third.message.source.exchangeId, 'three', 3)+ const result = JSON.parse(await running)+ assert.deepEqual(result.replies.map(reply => reply.text), ['one', 'two', 'three'])+})diff --git a/ds-bot/test/tool-cells.test.js b/ds-bot/test/tool-cells.test.jsindex 6fdde216..64bc984e 100644--- a/ds-bot/test/tool-cells.test.js+++ b/ds-bot/test/tool-cells.test.js@@ -626,7 +626,7 @@ test('a PTC group relay shows its replies from the sub-call, live and after reloconst headless = { ...finished, name: '', call: null }assert.equal(shown(headless, { sessionId: 'room' }), reloaded)- const progress = [{ callId: 'other', replies: [{ botId: 'chief', text: 'Not this round.' }] }, { callId: 'call-1-1:ptc:1', replies: replies.slice(0, 1), speaking: 'chief' }]+ const progress = [{ callId: 'other', replies: [{ botId: 'chief', text: 'Not this round.' }] }, { callId: 'call-1-1:ptc:1', replies: replies.slice(0, 1), speaking: ['chief'] }]const asked = []const actions = { roomProgress: async (id) => { asked.push(id); return progress } }const running = program([call('group_relay', 'call-1-1:ptc:1', { running: true })], { running: true })@@ -639,7 +639,7 @@ test('a PTC group relay shows its replies from the sub-call, live and after relostop()timers.clear()assert.deepEqual(asked, ['room'])- assert.deepEqual(JSON.parse(JSON.stringify(sets)), [{ replies: replies.slice(0, 1), speaking: 'chief' }])+ assert.deepEqual(JSON.parse(JSON.stringify(sets)), [{ replies: replies.slice(0, 1), speaking: ['chief'] }])})// #105: the secret and question cards of a PTC program showed nowhere.