A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Join user messages sent mid-round into the running group round
lulu feizhueaa2e0037a8f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 83de4c1d..132776d2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,10 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change- Every Bot can change its own name, role, color, model and instructions; only a Main Bot changes other Bots.+### Fixed++- A message sent to a group chat while a round is running shows at once and joins that round instead of waiting for it to end.+## [0.1.2] - 2026-10-11### Addeddiff --git a/ds-bot/client.js b/ds-bot/client.jsindex acc2892d..d5105d63 100644--- a/ds-bot/client.js+++ b/ds-bot/client.js@@ -4084,10 +4084,10 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUiconst result = await actions.roomProgress(sessionId);if (stop) return;const entry = (result ?? []).find((item) => item.callId === callId) ?? (result ?? [])[0];- const key = entry ? JSON.stringify([entry.replies, entry.speaking]) : "";+ const key = entry ? JSON.stringify([entry.replies, entry.speaking, entry.pending]) : "";if (entry && key !== seen) {seen = key;- setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null });+ setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null, pending: entry.pending ?? [] });}timer = setTimeout(tick, document.hidden ? 5e3 : 1e3);};@@ -4105,14 +4105,16 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUireplies = [];}}+ const queued = done ? [] : (live.pending ?? []).map((text, index) => ({ kind: "user", text, key: `pending-${index}` }));const pending = done || !live.speaking ? [] : [live.speaking];- if (replies.length === 0 && pending.length === 0) return null;+ if (replies.length === 0 && queued.length === 0 && pending.length === 0) return null;const room2 = roster.roomsById[sessionId];return (0, import_react6.createElement)("div",{ className: "bt-group-replies" },replies.map((reply, index) => {const bot = roster.byId[reply.botId] ?? { id: reply.botId, name: reply.name, color: reply.color ?? "gray" };+ if (reply.kind === "user") return (0, import_react6.createElement)("div", { key: `user-${index}`, className: "bt-event" }, reply.text);if (reply.kind === "failed") {return (0, import_react6.createElement)("div",@@ -4129,6 +4131,7 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi}return (0, import_react6.createElement)(GroupMessage, { key: `${reply.botId}-${index}`, bot, text: reply.text, room: room2, roster, actions, msgKey: callId ? `${sessionId}:${callId}:${index}` : void 0, useUi });}),+ queued.map((reply) => (0, import_react6.createElement)("div", { key: reply.key, className: "bt-event" }, reply.text)),pending.map((id) => {const bot = roster.byId[id];if (!bot) return null;diff --git a/ds-bot/src/client/cells.js b/ds-bot/src/client/cells.jsindex 09d80959..7db3a6b5 100644--- a/ds-bot/src/client/cells.js+++ b/ds-bot/src/client/cells.js@@ -491,8 +491,8 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUiconst result = await actions.roomProgress(sessionId)if (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 }) }+ const key = entry ? JSON.stringify([entry.replies, entry.speaking, entry.pending]) : ''+ if (entry && key !== seen) { seen = key; setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null, pending: entry.pending ?? [] }) }timer = setTimeout(tick, document.hidden ? 5000 : 1000)}void tick()@@ -502,13 +502,16 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUiif (done) {try { replies = JSON.parse(contentText(content)).replies ?? [] } catch { replies = [] }}+ // User messages sent mid-round show at once, then join the replies when posted.+ const queued = done ? [] : (live.pending ?? []).map((text, index) => ({ kind: 'user', text, key: `pending-${index}` }))// Members speak one at a time, so only the current speaker is typing.const pending = done || !live.speaking ? [] : [live.speaking]- if (replies.length === 0 && pending.length === 0) return null+ if (replies.length === 0 && queued.length === 0 && pending.length === 0) return nullconst room = roster.roomsById[sessionId]return h('div', { className: 'bt-group-replies' },replies.map((reply, index) => {const bot = roster.byId[reply.botId] ?? { id: reply.botId, name: reply.name, color: reply.color ?? 'gray' }+ if (reply.kind === 'user') return h('div', { key: `user-${index}`, className: 'bt-event' }, reply.text)if (reply.kind === 'failed') {return h('div', { key: `${reply.botId}-${index}`, className: 'bt-event bt-event-error', role: 'status', title: [reply.code, reply.status, reply.text].filter(Boolean).join(' · ') },t('{name} could not answer: {reason}', { name: bot.name, reason: failureLabel(reply.code, reply.text) }))@@ -519,6 +522,7 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi}return h(GroupMessage, { key: `${reply.botId}-${index}`, bot, text: reply.text, room, roster, actions, msgKey: callId ? `${sessionId}:${callId}:${index}` : undefined, useUi })}),+ queued.map(reply => h('div', { key: reply.key, className: 'bt-event' }, reply.text)),pending.map((id) => {const bot = roster.byId[id]if (!bot) return nulldiff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex 60f59690..63463382 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -129,7 +129,15 @@ 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.speaking ?? null,+ // Messages sent mid-round that the next drain has not posted yet.+ pending: (rt.roomInbox.get(entry.roomId) ?? [])+ .filter(item => item.early === true && item.posted !== true && item.consumed !== true)+ .map(item => item.text),+ })))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 })@@ -254,6 +262,9 @@ export function install(rt) {// A Bot id or an earlier part of its own chat means the current part.const past = rt.pastOwners.get(body.sessionId)const sessionId = rt.botOf(body.sessionId) ? rt.chatOf(body.sessionId) : past && past.roomId === undefined ? rt.chatOf(past.botId) : body.sessionId+ // While a group is mid-round its queued copy waits out the whole round;+ // record it for the running round too so the next speaker sees it now.+ if (rt.roomOf(sessionId) !== undefined && rt.roomBusy(sessionId)) rt.queueRoomMessage(sessionId, { text, early: true })await ctx.sessionController.prompt({requestId: randomUUID(),sessionId,diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex f8d414c5..8f93528c 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -180,11 +180,50 @@ export function install(rt) {return stripOwnName(member.name, String(reply ?? '').trim())}+ // 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 this slot. `cap` is the caller's+ // per-member turn bound for the round.+ function callMembers(room, round, turns, index, callees, callerName, cap) {+ let next = index + 1+ for (const peer of callees) {+ if ((turns.get(peer.id) ?? 0) >= cap) continue+ 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 = `${callerName} mentioned you`+ round.slots.splice(next, 0, called)+ next += 1+ }+ }++ // Messages the user sent while this round is running post into the log between+ // speakers, so the members still to speak see them; a member they @ is called+ // right after this slot, as if the admin had called it.+ function drainRoomInbox(room, round, turns, index) {+ const fresh = (rt.roomInbox.get(room.id) ?? [])+ .filter(item => item.early === true && item.posted !== true && item.consumed !== true)+ if (fresh.length === 0) return+ const others = room.members.map(rt.botOf).filter(Boolean)+ for (const item of fresh) {+ item.posted = true+ appendRoom(room, { who: 'User', text: item.text })+ round.replies.push({ kind: 'user', text: item.text, time: Date.now() })+ const { all, found } = mentionsIn(item.text, others)+ const callees = all ? [...found, ...others.filter(other => !found.includes(other))] : found+ // The member next to speak is still waiting on this slot, not past it: a call+ // for it is a note on its own slot, not an extra turn.+ const next = round.slots[index]+ if (next?.status === 'waiting' && callees.some(peer => peer.id === next.id)) next.note = 'the user mentioned you'+ callMembers(room, round, turns, index, callees.filter(peer => peer.id !== next?.id), 'the user', ROOM_ADMIN_TURNS_EACH)+ }+ void rt.save()+ }+async function runRound(room, round, signal) {const limit = round.slots.length + ROOM_EXTRA_TURNS + (room.admin ? ROOM_ADMIN_EXTRA_TURNS : 0)const turns = new Map()for (let index = 0; index < round.slots.length && round.turns < limit; index += 1) {if (signal.aborted) break+ drainRoomInbox(room, round, turns, index)const slot = round.slots[index]const member = rt.botOf(slot.id)// Settings may change mid-round, for example when the admin removes someone.@@ -228,22 +267,12 @@ export function install(rt) {appendRoom(room, { who: member.name, botId: member.id, text: reply })round.replies.push({ botId: member.id, name: member.name, color: member.color, text: reply, time: Date.now() })void rt.save()- // 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 this speaker. Only the admin's- // "@all" calls everyone, so a member cannot set off a storm.+ // Only the admin's "@all" calls everyone, so a member cannot set off a storm.const leads = rt.isAdminOf(room, member.id)const others = room.members.filter(id => id !== member.id).map(rt.botOf).filter(Boolean)const { all, found } = mentionsIn(reply, others)const callees = leads && all ? [...found, ...others.filter(other => !found.includes(other))] : found- let next = index + 1- for (const peer of callees) {- if ((turns.get(peer.id) ?? 0) >= (leads ? ROOM_ADMIN_TURNS_EACH : ROOM_TURNS_EACH)) continue- 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 = `${member.name} mentioned you`- round.slots.splice(next, 0, called)- next += 1- }+ callMembers(room, round, turns, index, callees, member.name, leads ? ROOM_ADMIN_TURNS_EACH : ROOM_TURNS_EACH)}}@@ -261,7 +290,15 @@ export function install(rt) {// Session folds into one turn are not lost; the newest one picks the speakers.const queued = rt.roomInbox.get(room.id) ?? []rt.roomInbox.delete(room.id)- const posts = queued.length > 0 ? queued : [{ text: '' }]+ // Queued copies of messages a running round already posted, or recorded for it+ // and never drained, arrive with the next turn: the posted ones open no round,+ // and a turn that brings nothing new closes without one.+ const fresh = queued.filter(post => post.consumed !== true && post.posted !== true)+ if (queued.length > 0 && fresh.length === 0) {+ exec.concludeTurn?.()+ return JSON.stringify({ replies: [], passed: [] })+ }+ const posts = fresh.length > 0 ? fresh : [{ text: '' }]const startSeq = room.seq + 1// The opening greeting is a cue for the admin, not a line of the group.for (const post of posts.filter(item => !item.kickoff)) {diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex ad2ed353..ab4d3dbe 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -182,9 +182,21 @@ export function install(rt) {queueRoomMessage(id, { text: reminderText(textOf(event.data.content)) })} else if (source?.kind === 'user' || source?.kind === REPLY_KIND) {if (rt.roomOf(id) && source.kind === 'user') {+ const text = textOf(event.data.content)const images = (Array.isArray(event.data.content) ? event.data.content : []).filter(block => block?.type === 'image' && !block.offloaded).map(block => block.attachment)- queueRoomMessage(id, { text: textOf(event.data.content), ...(images.length > 0 ? { images } : {}) })+ // A message recorded for a running round (`early`) reaches the Session+ // again once its queued prompt lands: keep the round's own posting and+ // treat this copy as consumed so it neither posts nor opens a round.+ const earlier = images.length === 0+ ? (rt.roomInbox.get(id) ?? []).find(item => item.early === true && item.claimed !== true && item.text === text)+ : undefined+ if (earlier !== undefined) {+ earlier.claimed = true+ queueRoomMessage(id, { text, consumed: true })+ } else {+ queueRoomMessage(id, { text, ...(images.length > 0 ? { images } : {}) })+ }}const own = rt.chatOwners.get(id)if (own !== undefined) rt.dropKickoff(own)@@ -246,5 +258,5 @@ export function install(rt) {}})- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView })+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, queueRoomMessage, activityView })}diff --git a/ds-bot/test/rounds.test.js b/ds-bot/test/rounds.test.jsnew file mode 100644index 00000000..83781742--- /dev/null+++ b/ds-bot/test/rounds.test.js@@ -0,0 +1,142 @@+import assert from 'node:assert/strict'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { test } from 'node:test'+import { apply } from '../index.js'+import { fakeContext } from './fake-ctx.js'++// A fake team of two Bots in one group; member answers are played back through the+// session/event listener, so a round runs with no model.+function start() {+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-rounds-'))+ const ctx = fakeContext()+ const workspaces = new Map()+ const sent = []+ const prompts = []+ let sessions = 0+ Object.assign(ctx, {+ llm: {+ listProviders: () => [{ id: 'deepseek', name: 'DeepSeek' }],+ listModels: async () => [{ id: 'deepseek-v4-flash' }],+ resolveModelInfo: async () => ({}),+ },+ workspaceRegistry: {+ get: id => workspaces.get(id),+ resolveByPath: async () => undefined,+ create: async (path) => {+ const workspace = { id: `w${workspaces.size + 1}`, path }+ workspaces.set(workspace.id, workspace)+ return workspace+ },+ archiveSession: async () => {},+ },+ sessionController: {+ create: async () => ({ sessionId: `s${++sessions}` }),+ resolveAgent: async sessionId => ({ agent: { session: { id: sessionId }, followup: message => sent.push({ sessionId, message }) } }),+ selectModel: async () => {},+ prompt: async (request) => { prompts.push(request); return { accepted: true } },+ page: async () => ({ events: [] }),+ },+ sessionTitle: { rename: async () => {} },+ sessions: { flush: async () => {} },+ })+ let route+ const register = ctx.connection.fetch.register+ ctx.connection.fetch.register = (options) => {+ route = options+ return register(options)+ }+ apply(ctx, { home })+ const call = async (endpoint, payload) => {+ const response = await route.fetch(new Request('http://localhost/api/bot', { method: 'POST', body: JSON.stringify({ endpoint, payload }) }))+ return response.json()+ }+ // Session events arrive one at a time in DSH; awaiting each listener keeps that order.+ const emit = async (sessionId, event) => {+ for (const listener of ctx.listeners.get('session/event') ?? []) await listener({ id: sessionId }, event)+ }+ const userMessage = text => ({ type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text }] } })+ // The Bot's answer to its group turn: a delivery source plus the reply text.+ const answer = async (sessionId, exchangeId, text, turn) => {+ await emit(sessionId, { type: 'turn/start', data: { turn } })+ await emit(sessionId, { type: 'user/message', data: { source: { kind: 'bot', role: 'room', exchangeId }, content: [{ type: 'text', text: 'your turn' }] } })+ await emit(sessionId, { type: 'assistant/message', data: { message: { content: [{ type: 'text', text }] } } })+ await emit(sessionId, { type: 'turn/end', data: { reason: { kind: 'stop' } } })+ }+ const stop = () => {+ ctx.dispose()+ rmSync(home, { recursive: true, force: true })+ }+ return { call, emit, userMessage, answer, stop, sent, prompts, ctx }+}++const settle = () => new Promise(resolve => setTimeout(resolve, 20))+const waitFor = async (check) => {+ for (let at = 0; at < 100; at += 1) {+ const value = check()+ if (value !== undefined) return value+ await settle()+ }+ return undefined+}++test('a message sent mid-round joins the round: the next speaker sees it, the queued copy opens no round', async (t) => {+ const { call, emit, userMessage, answer, stop, sent, prompts, ctx } = start()+ t.after(stop)+ const chief = (await call('state', {})).value.mainBotId+ const writer = (await call('create-bot', { name: 'Writer' })).value+ const room = (await call('create-room', { members: [chief, writer.id] })).value+ await call('update-room', { id: room.id, mode: 'everyone' })+ sent.length = 0++ // The user's first message queues and the relay opens the round: admin speaks first.+ await emit(room.id, userMessage('Tell me a long story'))+ const relay = ctx.registeredTools.get('group_relay').execute({}, { agent: { id: room.id }, callId: 'relay', signal: new AbortController().signal })+ const first = await waitFor(() => sent.find(entry => entry.message.source.role === 'room'))+ assert.ok(first, 'the admin gets the first turn')++ // While the admin is still answering, the user sends another message.+ assert.equal((await call('send', { sessionId: room.id, text: '@Writer ping mid-round' })).ok, true)+ await settle()++ // The admin answers; the Writer's turn prompt must already carry the new line.+ await answer(first.sessionId, first.message.source.exchangeId, 'Once upon a time...', 1)+ const second = await waitFor(() => sent.find(entry => entry !== first && entry.message.source.role === 'room'))+ assert.ok(second, 'the Writer gets the next turn')+ assert.match(second.message.content[0].text, /@Writer ping mid-round/)+ assert.match(second.message.content[0].text, /the user mentioned you/)++ // The Writer answers and the round ends; the earlier send also reached the Session.+ await answer(second.sessionId, second.message.source.exchangeId, 'Ping back!', 2)+ const result = JSON.parse(await relay)+ assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'User', 'Writer'])++ // The queued copy of the mid-round message arrives with the next turn: nothing new.+ await emit(room.id, userMessage('@Writer ping mid-round'))+ const before = sent.length+ const again = JSON.parse(await ctx.registeredTools.get('group_relay').execute({}, { agent: { id: room.id }, callId: 'relay-2', signal: new AbortController().signal }))+ assert.deepEqual(again, { replies: [], passed: [] })+ assert.equal(sent.length, before)+})++test('a message sent between rounds still opens a full round', async (t) => {+ const { call, emit, userMessage, answer, stop, sent, ctx } = start()+ t.after(stop)+ const chief = (await call('state', {})).value.mainBotId+ const writer = (await call('create-bot', { name: 'Writer' })).value+ const room = (await call('create-room', { members: [chief, writer.id] })).value+ await call('update-room', { id: room.id, mode: 'everyone' })+ sent.length = 0++ await emit(room.id, userMessage('Hello group'))+ const relay = ctx.registeredTools.get('group_relay').execute({}, { agent: { id: room.id }, callId: 'relay', signal: new AbortController().signal })+ const first = await waitFor(() => sent.find(entry => entry.message.source.role === 'room'))+ assert.ok(first)+ await answer(first.sessionId, first.message.source.exchangeId, 'Hi!', 1)+ const second = await waitFor(() => sent.find(entry => entry !== first && entry.message.source.role === 'room'))+ assert.ok(second)+ await answer(second.sessionId, second.message.source.exchangeId, 'Hello!', 2)+ const result = JSON.parse(await relay)+ assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer'])+})