Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Take mid-round group messages from the Session's own inbox

FeiZhuLulu123d3340912f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 43c0f50a..f3550a51 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,10 +23,7 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change
- A long conversation's fresh part keeps the Bot's model and thinking level. Before, the new part fell back to the default model.
- A provider adapter that cannot measure tokens no longer fails every turn. The context size is estimated instead, with one warning in the log.
- The memory panel's summary works on models that think by default. The call asks for the model's lowest thinking level, and when the answer is cut off at the output limit it is written once more with a larger budget instead of failing or being saved half-written.
-
-### 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.
+- A message sent to a group chat while a round is running joins that round before the next member speaks. Everyone still to speak sees it, and the members it is for answer it in the same round. Before, it waited for the whole round to end. A message with images or a referenced conversation still waits for its own round.
## [0.1.2] - 2026-10-11
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 0eec11db..d4c5b6ac 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -4136,10 +4136,10 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi
const 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, entry.pending]) : "";
+ const key = entry ? JSON.stringify([entry.replies, entry.speaking]) : "";
if (entry && key !== seen) {
seen = key;
- setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null, pending: entry.pending ?? [] });
+ setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null });
}
timer = setTimeout(tick, document.hidden ? 5e3 : 1e3);
};
@@ -4157,16 +4157,21 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi
replies = [];
}
}
- 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 && queued.length === 0 && pending.length === 0) return null;
+ if (replies.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 === "user") {
+ return (0, import_react6.createElement)("div", { key: `user-${index}`, className: "bt-urow" }, (0, import_react6.createElement)(
+ "div",
+ { className: "bt-ububble" },
+ (0, import_react6.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: reply.text, labels: mdLabels(), variant: "compact" })
+ ));
+ }
if (reply.kind === "failed") {
return (0, import_react6.createElement)(
"div",
@@ -4183,7 +4188,6 @@ 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.js
index 0f294015..de473554 100644
--- a/ds-bot/src/client/cells.js
+++ b/ds-bot/src/client/cells.js
@@ -506,8 +506,8 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi
const 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, entry.pending]) : ''
- if (entry && key !== seen) { seen = key; setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null, pending: entry.pending ?? [] }) }
+ const key = entry ? JSON.stringify([entry.replies, entry.speaking]) : ''
+ if (entry && key !== seen) { seen = key; setLive({ replies: entry.replies ?? [], speaking: entry.speaking ?? null }) }
timer = setTimeout(tick, document.hidden ? 5000 : 1000)
}
void tick()
@@ -517,16 +517,17 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi
if (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 && queued.length === 0 && pending.length === 0) return null
+ if (replies.length === 0 && pending.length === 0) return null
const 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 === 'user') {
+ return h('div', { key: `user-${index}`, className: 'bt-urow' }, h('div', { className: 'bt-ububble' },
+ h(MarkdownText, { text: reply.text, labels: mdLabels(), variant: 'compact' })))
+ }
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) }))
@@ -537,7 +538,6 @@ 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 null
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js
index 110370fb..60f59690 100644
--- a/ds-bot/src/host/channel.js
+++ b/ds-bot/src/host/channel.js
@@ -129,15 +129,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,
- // 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),
- })))
+ return ok([...rt.roomProgress.entries()].filter(([, entry]) => entry.roomId === body.roomId).map(([callId, entry]) => ({ callId, replies: entry.replies, speaking: entry.speaking ?? null })))
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 })
@@ -262,30 +254,12 @@ 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.
- const early = rt.roomOf(sessionId) !== undefined && rt.roomBusy(sessionId)
- ? rt.queueRoomMessage(sessionId, { text, early: true })
- : undefined
- try {
- await ctx.sessionController.prompt({
- requestId: randomUUID(),
- sessionId,
- mode: 'queue',
- content: [{ type: 'text', text }],
- }, AbortSignal.timeout(30_000))
- } catch (error) {
- // The round may have drained the record while prompt() was in flight;
- // then the message reached the room, so this send still succeeded.
- if (early !== undefined && early.posted === true) return ok(true)
- if (early !== undefined) {
- const inbox = rt.roomInbox.get(sessionId) ?? []
- const at = inbox.indexOf(early)
- if (at !== -1) inbox.splice(at, 1)
- void rt.save()
- }
- throw error
- }
+ await ctx.sessionController.prompt({
+ requestId: randomUUID(),
+ sessionId,
+ mode: 'queue',
+ content: [{ type: 'text', text }],
+ }, AbortSignal.timeout(30_000))
return ok(true)
}
case 'update-check': {
diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.js
index dc58c7ee..b16cb977 100644
--- a/ds-bot/src/host/groups.js
+++ b/ds-bot/src/host/groups.js
@@ -13,7 +13,7 @@ import { randomUUID } from 'node:crypto'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { ROOM_REPLY_TIMEOUT_MS, SOURCE_KIND } from './constants.js'
-import { escapeRegExp, splitRef } from './text.js'
+import { escapeRegExp, splitRef, textOf } from './text.js'
import { GROUP_REF, output } from './tools.js'
import { failureLine } from './turns.js'
@@ -203,55 +203,69 @@ export function install(rt) {
}
// 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
+ // already spoke; either way it goes right after slot `index`. `cap` is the caller's
// per-member turn bound for the round.
- function callMembers(room, round, turns, index, callees, callerName, cap) {
+ function callMembers(round, turns, index, callees, note, 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`
+ called.note = note
round.slots.splice(next, 0, called)
next += 1
}
}
- const freshInbox = room => (rt.roomInbox.get(room.id) ?? [])
- .filter(item => item.early === true && item.posted !== true && item.consumed !== true)
+ // The user's messages waiting in the group Session's inbox while a round runs, from
+ // the composer whether it queued or steered them. Images and chat references are
+ // only read when the Session takes the message itself, so a message with either
+ // stays for the next round, and so does everything after it in that list.
+ const waitingLines = agent => ['nextStep', 'nextTurn'].flatMap((list) => {
+ const lines = []
+ for (const message of agent?.inbox?.[list] ?? []) {
+ if (message.source?.kind !== 'user') continue
+ const content = Array.isArray(message.content) ? message.content : []
+ const text = textOf(content)
+ if (text === '' || content.some(block => block?.type !== 'text') || text.includes('dsh-session:')) break
+ lines.push({ id: message.id, text })
+ }
+ return lines
+ })
- // 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 = freshInbox(room)
- 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)
+ // 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. Returns
+ // the number of turns added, which the round's limit allows for.
+ function drainRoomInbox(room, round, turns, index, agent) {
+ // The greeting's prompt tells the admin the user has not written yet.
+ if (round.kickoff) return 0
+ const lines = waitingLines(agent).filter(line => agent.inbox.remove(line.id))
+ if (lines.length === 0) return 0
+ const before = round.slots.length
+ const members = room.members.map(rt.botOf).filter(Boolean)
+ for (const line of lines) {
+ appendRoom(room, { who: 'User', text: line.text })
+ 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, turns, index - 1, openingSpeakers(room, { text: line.text }), note, ROOM_ADMIN_TURNS_EACH)
}
// The user spoke in this room, so Bots may start their own rounds again.
room.botRounds = 0
void rt.save()
+ return round.slots.length - before
}
- async function runRound(room, round, signal) {
- const limit = round.slots.length + ROOM_EXTRA_TURNS + (room.admin ? ROOM_ADMIN_EXTRA_TURNS : 0)
+ async function runRound(room, round, signal, agent) {
+ let limit = round.slots.length + ROOM_EXTRA_TURNS + (room.admin ? ROOM_ADMIN_EXTRA_TURNS : 0)
const turns = new Map()
// 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 || freshInbox(room).length > 0) && round.turns < limit; index += 1) {
+ for (let index = 0; (index < round.slots.length || waitingLines(agent).length > 0) && round.turns < limit; index += 1) {
if (signal.aborted) break
- drainRoomInbox(room, round, turns, index)
+ limit += drainRoomInbox(room, round, turns, index, agent)
if (index >= round.slots.length) break
const slot = round.slots[index]
const member = rt.botOf(slot.id)
@@ -302,7 +316,7 @@ export function install(rt) {
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
- callMembers(room, round, turns, index, callees, member.name, leads ? ROOM_ADMIN_TURNS_EACH : ROOM_TURNS_EACH)
+ callMembers(round, turns, index, callees, `${member.name} mentioned you`, leads ? ROOM_ADMIN_TURNS_EACH : ROOM_TURNS_EACH)
}
}
@@ -320,15 +334,7 @@ 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)
- // 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 posts = queued.length > 0 ? queued : [{ 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)) {
@@ -357,7 +363,7 @@ export function install(rt) {
}
rt.roomProgress.set(exec.callId, round)
try {
- await runRound(room, round, exec.signal)
+ await runRound(room, round, exec.signal, exec.agent)
} catch (error) {
rt.warn('ds-bot: group round in %s stopped: %s', room.name, error)
} finally {
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index ff52e510..0db9647b 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -42,10 +42,7 @@ export function install(rt) {
const roomProgress = new Map()
/** @type {Map<string, {text:string, botId?:string, name?:string, reportBack?:boolean, hop?:number, kickoff?:boolean, references?:{labels:string[], text:string}[]}[]>} messages a room's next relay posts */
const roomInbox = new Map()
- const queueRoomMessage = (roomId, item) => {
- roomInbox.set(roomId, [...(roomInbox.get(roomId) ?? []), item])
- return item
- }
+ const queueRoomMessage = (roomId, item) => roomInbox.set(roomId, [...(roomInbox.get(roomId) ?? []), item])
const liveOf = id => {
let entry = live.get(id)
@@ -203,21 +200,9 @@ export function install(rt) {
attachReference(roomInbox.get(id), source, 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)
- // 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 } : {}) })
- }
+ queueRoomMessage(id, { text: textOf(event.data.content), ...(images.length > 0 ? { images } : {}) })
}
const own = rt.chatOwners.get(id)
if (own !== undefined) rt.dropKickoff(own)
@@ -282,5 +267,5 @@ export function install(rt) {
}
})
- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, queueRoomMessage, activityView })
+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView })
}
diff --git a/ds-bot/test/rounds.test.js b/ds-bot/test/rounds.test.js
index bbe10028..b46eccf8 100644
--- a/ds-bot/test/rounds.test.js
+++ b/ds-bot/test/rounds.test.js
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict'
+import { randomUUID } from 'node:crypto'
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -7,13 +8,32 @@ 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.
+// session/event listener, so a round runs with no model. Prompts land in the
+// Session's inbox the way DSH holds them while a turn runs: queued for the next turn,
+// or steered into the next step.
function start() {
const home = mkdtempSync(join(tmpdir(), 'ds-bot-rounds-'))
const ctx = fakeContext()
const workspaces = new Map()
const sent = []
- const prompts = []
+ const inboxes = new Map()
+ const inboxOf = (sessionId) => {
+ if (!inboxes.has(sessionId)) {
+ const inbox = { nextTurn: [], nextStep: [] }
+ inbox.remove = (id) => {
+ for (const list of ['nextTurn', 'nextStep']) {
+ const at = inbox[list].findIndex(message => message.id === id)
+ if (at !== -1) {
+ inbox[list] = inbox[list].toSpliced(at, 1)
+ return true
+ }
+ }
+ return false
+ }
+ inboxes.set(sessionId, inbox)
+ }
+ return inboxes.get(sessionId)
+ }
let sessions = 0
Object.assign(ctx, {
llm: {
@@ -35,7 +55,11 @@ function start() {
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 } },
+ prompt: async (request) => {
+ const inbox = inboxOf(request.sessionId)
+ inbox[request.mode === 'steer' ? 'nextStep' : 'nextTurn'].push({ id: randomUUID(), role: 'user', source: { kind: 'user', rpcId: request.requestId }, content: request.content })
+ return { accepted: true }
+ },
page: async () => ({ events: [] }),
},
sessionTitle: { rename: async () => {} },
@@ -57,6 +81,15 @@ function start() {
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 }] } })
+ // What the shell's composer does: prompt the group's Session directly.
+ const compose = (sessionId, content, mode = 'queue') => ctx.sessionController.prompt({
+ requestId: randomUUID(),
+ sessionId,
+ mode,
+ content: typeof content === 'string' ? [{ type: 'text', text: content }] : content,
+ })
+ const relay = (roomId, callId, signal = new AbortController().signal) => ctx.registeredTools.get('group_relay')
+ .execute({}, { agent: { id: roomId, inbox: inboxOf(roomId) }, callId, signal })
// 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 } })
@@ -68,7 +101,7 @@ function start() {
ctx.dispose()
rmSync(home, { recursive: true, force: true })
}
- return { call, emit, userMessage, answer, stop, sent, prompts, ctx, home }
+ return { call, emit, userMessage, compose, relay, inboxOf, answer, stop, sent, ctx, home }
}
const settle = () => new Promise(resolve => setTimeout(resolve, 20))
@@ -80,88 +113,128 @@ const waitFor = async (check) => {
}
return undefined
}
+const turnFor = (sent, ...earlier) => waitFor(() => sent.find(entry => !earlier.includes(entry) && entry.message.source.role === 'room'))
-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)
+async function team(call, sent) {
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
+ const room = (await call('create-room', { name: 'R1', members: [chief, writer.id] })).value
await call('update-room', { id: room.id, mode: 'everyone' })
sent.length = 0
+ return room
+}
- // The user's first message queues and the relay opens the round: admin speaks first.
+test('a message the composer queues mid-round joins the round and leaves the Session\'s queue', async (t) => {
+ const { call, emit, userMessage, compose, relay, inboxOf, answer, stop, sent } = start()
+ t.after(stop)
+ const room = await team(call, sent)
+
+ // The user's first message opens the round: the 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'))
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
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()
+ await compose(room.id, '@Writer ping mid-round')
// 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'))
+ const second = await turnFor(sent, first)
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)
+ const result = JSON.parse(await running)
assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'User', 'Writer'])
+ // Taken out of the queue, the message opens no second round after this one.
+ assert.deepEqual(inboxOf(room.id).nextTurn, [])
+})
- // 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 plain message steered mid-round is answered by everyone, admin first, inside the round', async (t) => {
+ const { call, emit, userMessage, compose, relay, inboxOf, answer, stop, sent } = start()
+ t.after(stop)
+ const room = await team(call, sent)
+
+ await emit(room.id, userMessage('Start'))
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
+ await compose(room.id, 'steer this way', 'steer')
+ await answer(first.sessionId, first.message.source.exchangeId, 'one', 1)
+ // The admin already spoke, so it gets one more turn for the new message.
+ const second = await turnFor(sent, first)
+ assert.equal(second.sessionId, first.sessionId)
+ assert.match(second.message.content[0].text, /steer this way/)
+ assert.match(second.message.content[0].text, /new message from the user/)
+ await answer(second.sessionId, second.message.source.exchangeId, 'one again', 2)
+ const third = await turnFor(sent, first, second)
+ assert.match(third.message.content[0].text, /steer this way/)
+ await answer(third.sessionId, third.message.source.exchangeId, 'two', 3)
+ const result = JSON.parse(await running)
+ assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'User', 'Chief', 'Writer'])
+ assert.deepEqual(inboxOf(room.id).nextStep, [])
})
-test('a message sent during the last speaker\'s turn still joins the round', async (t) => {
- const { call, emit, userMessage, answer, stop, sent, ctx } = start()
+test('a message sent during the last speaker\'s turn is still answered in the round', async (t) => {
+ const { call, emit, userMessage, relay, answer, stop, sent } = 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
+ const room = await team(call, sent)
await emit(room.id, userMessage('Kick it off'))
- 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'))
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
await answer(first.sessionId, first.message.source.exchangeId, 'Chief first', 1)
- const second = await waitFor(() => sent.find(entry => entry !== first && entry.message.source.role === 'room'))
+ const second = await turnFor(sent, first)
// The last member is already answering when the message lands.
- assert.equal((await call('send', { sessionId: room.id, text: '@Chief once more late' })).ok, true)
+ assert.equal((await call('send', { sessionId: room.id, text: 'one more thing' })).ok, true)
await answer(second.sessionId, second.message.source.exchangeId, 'Writer done', 2)
- const third = await waitFor(() => sent.find(entry => entry !== first && entry !== second && entry.message.source.role === 'room'))
- assert.ok(third, 'Chief is called back for the late message')
- assert.match(third.message.content[0].text, /@Chief once more late/)
- assert.match(third.message.content[0].text, /the user mentioned you/)
+ const third = await turnFor(sent, first, second)
+ assert.ok(third, 'the admin answers the late message')
+ assert.match(third.message.content[0].text, /one more thing/)
await answer(third.sessionId, third.message.source.exchangeId, 'Back again', 3)
- const result = JSON.parse(await relay)
+ const fourth = await turnFor(sent, first, second, third)
+ assert.ok(fourth, 'and so does the Writer')
+ await answer(fourth.sessionId, fourth.message.source.exchangeId, 'Me too', 4)
+ const result = JSON.parse(await running)
+ assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer', 'User', 'Chief', 'Writer'])
+})
+
+test('in admin mode a plain mid-round message goes to the admin', async (t) => {
+ const { call, emit, userMessage, compose, relay, answer, stop, sent } = start()
+ t.after(stop)
+ const room = await team(call, sent)
+ await call('update-room', { id: room.id, mode: 'admin' })
+
+ await emit(room.id, userMessage('Start'))
+ const running = relay(room.id, 'relay')
+ // The admin answers alone and calls the Writer.
+ const first = await turnFor(sent)
+ await answer(first.sessionId, first.message.source.exchangeId, '@Writer your call', 1)
+ const second = await turnFor(sent, first)
+ assert.notEqual(second.sessionId, first.sessionId)
+ await compose(room.id, 'what do you think?')
+ await answer(second.sessionId, second.message.source.exchangeId, 'Writer here', 2)
+ const third = await turnFor(sent, first, second)
+ assert.equal(third.sessionId, first.sessionId, 'the admin answers the user')
+ assert.match(third.message.content[0].text, /what do you think\?/)
+ await answer(third.sessionId, third.message.source.exchangeId, 'Admin here', 3)
+ const result = JSON.parse(await running)
assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer', 'User', 'Chief'])
})
test('a mid-round user line resets the room\'s bot-round budget', async (t) => {
- const { call, emit, userMessage, answer, stop, sent, ctx, home } = start()
+ const { call, emit, userMessage, compose, relay, answer, stop, sent, ctx, home } = 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', { name: 'R1', members: [chief, writer.id] })).value
- await call('update-room', { id: room.id, mode: 'everyone' })
- sent.length = 0
+ const room = await team(call, sent)
await emit(room.id, userMessage('Start'))
- 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'))
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
await answer(first.sessionId, first.message.source.exchangeId, 'one', 1)
- const second = await waitFor(() => sent.find(entry => entry !== first && entry.message.source.role === 'room'))
+ const second = await turnFor(sent, first)
// A Main Bot posts into the room while the last member is still answering:
// that spends one bot-round budget.
@@ -170,57 +243,79 @@ test('a mid-round user line resets the room\'s bot-round budget', async (t) => {
assert.equal(roomState().botRounds, 1, String(posted))
// The user's mid-round message counts as the user speaking: the budget reopens.
- assert.equal((await call('send', { sessionId: room.id, text: 'user back mid-round' })).ok, true)
+ await compose(room.id, '@Writer user back mid-round')
await answer(second.sessionId, second.message.source.exchangeId, 'two', 2)
- JSON.parse(await relay)
+ const third = await turnFor(sent, first, second)
+ await answer(third.sessionId, third.message.source.exchangeId, 'three', 3)
+ JSON.parse(await running)
assert.equal(roomState().botRounds, 0)
})
-test('a failed send drops the early record so the round never sees it', async (t) => {
- const { call, emit, userMessage, answer, stop, sent, ctx } = start()
+test('a message with an image or a chat reference waits for its own round, and so does what follows it', async (t) => {
+ const { call, emit, userMessage, compose, relay, inboxOf, answer, stop, sent } = 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
+ const room = await team(call, sent)
await emit(room.id, userMessage('Start'))
- 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'))
-
- // While the admin is answering, the Session-side queueing fails.
- const prompt = ctx.sessionController.prompt
- ctx.sessionController.prompt = async () => { throw new Error('queue full') }
- const failed = await call('send', { sessionId: room.id, text: 'ghost mid-round' })
- ctx.sessionController.prompt = prompt
- assert.equal(failed.ok, false)
-
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
+ await compose(room.id, [{ type: 'text', text: 'see this' }, { type: 'image', data: 'AAAA', mediaType: 'image/png' }])
+ await compose(room.id, 'after the image')
+ await compose(room.id, 'about @[Notes](dsh-session:abc123)', 'steer')
await answer(first.sessionId, first.message.source.exchangeId, 'one', 1)
- const second = await waitFor(() => sent.find(entry => entry !== first && entry.message.source.role === 'room'))
- assert.doesNotMatch(second.message.content[0].text, /ghost mid-round/)
+ const second = await turnFor(sent, first)
+ assert.doesNotMatch(second.message.content[0].text, /see this|after the image|about @/)
await answer(second.sessionId, second.message.source.exchangeId, 'two', 2)
- const result = JSON.parse(await relay)
- assert.equal(result.replies.filter(reply => reply.text === 'ghost mid-round').length, 0)
+ const result = JSON.parse(await running)
+ assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer'])
+ assert.equal(inboxOf(room.id).nextTurn.length, 2)
+ assert.equal(inboxOf(room.id).nextStep.length, 1)
+})
+
+test('the greeting round leaves a waiting message for its own round', async (t) => {
+ const { call, emit, compose, relay, inboxOf, answer, stop, sent } = start()
+ t.after(stop)
+ const room = await team(call, sent)
+
+ await emit(room.id, { type: 'user/message', data: { source: { kind: 'bot', role: 'kickoff' }, content: [{ type: 'text', text: '[Group chat created]' }] } })
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
+ await compose(room.id, 'hello there')
+ await answer(first.sessionId, first.message.source.exchangeId, 'Welcome!', 1)
+ const result = JSON.parse(await running)
+ assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief'])
+ assert.equal(inboxOf(room.id).nextTurn.length, 1)
+})
+
+test('a stopped round leaves a waiting message for the next round', async (t) => {
+ const { call, emit, userMessage, compose, relay, inboxOf, stop, sent } = start()
+ t.after(stop)
+ const room = await team(call, sent)
+
+ await emit(room.id, userMessage('Start'))
+ const controller = new AbortController()
+ const running = relay(room.id, 'relay', controller.signal)
+ await turnFor(sent)
+ await compose(room.id, 'still there?')
+ controller.abort()
+ const result = JSON.parse(await running)
+ assert.equal(result.replies.some(reply => reply.kind === 'user'), false)
+ assert.equal(inboxOf(room.id).nextTurn.length, 1)
})
test('a message sent between rounds still opens a full round', async (t) => {
- const { call, emit, userMessage, answer, stop, sent, ctx } = start()
+ const { call, emit, userMessage, relay, answer, stop, sent } = 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
+ const room = await team(call, sent)
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'))
+ const running = relay(room.id, 'relay')
+ const first = await turnFor(sent)
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'))
+ const second = await turnFor(sent, first)
assert.ok(second)
await answer(second.sessionId, second.message.source.exchangeId, 'Hello!', 2)
- const result = JSON.parse(await relay)
+ const result = JSON.parse(await running)
assert.deepEqual(result.replies.map(reply => reply.name ?? 'User'), ['Chief', 'Writer'])
})