Skip to content

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

Draw the tool calls a PTC program makes

Fei2411d6e7d980aa16
diff --git a/CHANGELOG.md b/CHANGELOG.md
index be0739b5..6a3e00cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change
## [Unreleased]
+### Fixed
+
+- With the `ptc` agent preset, the chat shows the tools a Bot runs from its code again: group replies, question and key cards, and the lines for messages, Bots, groups and memory.
+
## [0.1.4] - 2026-10-13
### Added
diff --git a/ds-bot/client.js b/ds-bot/client.js
index ea2b7877..9661c796 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -3946,12 +3946,12 @@ function GroupEvent({ prefix, room: room2, name, roster, actions }) {
}
function MemoryEvent({ sessionId, scope, result, roster, actions, findBot }) {
if (!/^(Saved to|Updated in|Removed from) /.test(result)) return null;
- const self2 = roster.byId[sessionId];
+ const self = roster.byId[sessionId];
const team = /^(team|团队|共享)$/i.test(String(scope ?? "").trim());
const other = team || !scope ? void 0 : findBot(scope);
- const target = other && other.id !== self2?.id ? other : self2;
+ const target = other && other.id !== self?.id ? other : self;
if (!target) return null;
- const label = team ? t("Team memory updated") : target === self2 ? t("Memory updated") : t("Updated {name}'s memory", { name: target.name });
+ const label = team ? t("Team memory updated") : target === self ? t("Memory updated") : t("Updated {name}'s memory", { name: target.name });
return (0, import_react6.createElement)(
"div",
{ className: "bt-event" },
@@ -4220,7 +4220,7 @@ var TOOL_PHRASES = [
[/image|photo|draw/i, "Working on an image"]
];
var GROUP_PHRASES = { create_group: "Creating a group", update_group: "Updating the group", delete_group: "Deleting the group", post_to_group: "Posting in the group" };
-function toolActivity(name, arg, findBot, self2) {
+function toolActivity(name, arg, findBot, self) {
switch (name) {
case "ask_user":
return null;
@@ -4243,7 +4243,7 @@ function toolActivity(name, arg, findBot, self2) {
case "create_bot":
return { label: t("Creating {name}", { name: arg("name") ?? t("a Bot") }), state: "sending" };
case "update_bot": {
- const target = findBot(arg("name")) ?? findBot(arg("bot")) ?? (arg("bot") ? void 0 : self2);
+ const target = findBot(arg("name")) ?? findBot(arg("bot")) ?? (arg("bot") ? void 0 : self);
return { label: t("Updating {name}", { name: target?.name ?? t("a Bot") }), state: "sending" };
}
case "list_bots":
@@ -4376,27 +4376,35 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi
})
);
}
-function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }) {
- const roster = useRoster((value) => value);
- const root = node.data.root;
- const done = root.kind === "tool-result";
- const turn = node.location?.turn?.turn ?? root.turn;
- const hidden = isHiddenTurn(roster, sessionId, turn);
- const tool = toolName(root);
- const { text: arg, value: argValue } = toolArgs(root);
- const findBot = (nameOrId) => roster.byId[nameOrId] ?? roster.bots.find((bot) => bot.name.toLowerCase() === String(nameOrId ?? "").toLowerCase());
- useLiveNote(actions, sessionId, `tool:${root.callId ?? node.key}`, done || hidden ? null : toolActivity(tool, arg, findBot, roster.byId[sessionId]));
- if (hidden) return null;
+var DRAWN = /* @__PURE__ */ new Set(["message_bot", "stop_bot", "create_bot", "update_bot", "group_relay", "create_group", "update_group", "delete_group", "post_to_group", "ask_user", "request_secret", "ask_user_question", "read_group_chat", "remember", "forget"]);
+function callTree(root) {
+ const calls = [];
+ const seen = /* @__PURE__ */ new Set();
+ const visit = (call2) => {
+ const id = call2.callId ?? call2;
+ if (seen.has(id)) return;
+ seen.add(id);
+ calls.push(call2);
+ for (const child of call2.subCalls ?? []) visit(child);
+ };
+ visit(root);
+ return calls;
+}
+function renderCall(call2, { sessionId, roster, actions, useUi, useWork, findBot }) {
+ const tool = toolName(call2);
+ const done = call2.kind === "tool-result";
+ const { text: arg, value: argValue } = toolArgs(call2);
+ const self = roster.byId[sessionId];
switch (tool) {
case "message_bot": {
const target = findBot(arg("to")) ?? { name: arg("to") ?? "…", color: "gray" };
- if (done && root.isError) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Couldn't message {name}", { name: target.name }));
+ if (done && call2.isError) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Couldn't message {name}", { name: target.name }));
return (0, import_react6.createElement)(EventLine, { prefix: t("Messaged"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id), whole: true });
}
case "stop_bot": {
const target = findBot(arg("bot")) ?? { name: arg("bot") ?? "…", color: "gray" };
- if (done && root.isError) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Couldn't stop {name}", { name: target.name }));
- return (0, import_react6.createElement)(EventLine, { prefix: t("Stopped"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(roster.byId[sessionId]?.id ?? sessionId, bot.id), whole: true });
+ if (done && call2.isError) return (0, import_react6.createElement)("div", { className: "bt-event" }, t("Couldn't stop {name}", { name: target.name }));
+ return (0, import_react6.createElement)(EventLine, { prefix: t("Stopped"), bots: [target], onOpen: (bot) => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id), whole: true });
}
case "create_bot": {
const created = findBot(arg("name"));
@@ -4404,11 +4412,11 @@ function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }) {
return (0, import_react6.createElement)(EventLine, { prefix: t("Created"), bots: [created], onOpen: (bot) => actions.openSession(bot.id) });
}
case "update_bot": {
- const target = findBot(arg("name")) ?? findBot(arg("bot")) ?? (arg("bot") ? void 0 : roster.byId[sessionId]);
+ const target = findBot(arg("name")) ?? findBot(arg("bot")) ?? (arg("bot") ? void 0 : self);
return done && target ? (0, import_react6.createElement)(EventLine, { prefix: t("Updated"), bots: [target], onOpen: (bot) => actions.openSession(bot.id) }) : null;
}
case "group_relay":
- return (0, import_react6.createElement)(GroupReplies, { sessionId, callId: root.callId, done, content: root.content, roster, actions, useUi, useWork });
+ return (0, import_react6.createElement)(GroupReplies, { sessionId, callId: call2.callId, done, content: call2.content, roster, actions, useUi, useWork });
case "create_group":
case "update_group":
case "delete_group":
@@ -4420,25 +4428,25 @@ function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }) {
post_to_group: ["Posted in", "Couldn't post in the group"]
}[tool];
if (!done) return null;
- const result = contentText(root.content);
+ const result = contentText(call2.content);
const named = /^(Created group|Updated|Nothing changed in|Deleted|Posted in) "([^"]+)"/.exec(result);
- if (root.isError || !named) return (0, import_react6.createElement)("div", { className: "bt-event", title: result }, t(verbs[1]));
+ if (call2.isError || !named) return (0, import_react6.createElement)("div", { className: "bt-event", title: result }, t(verbs[1]));
const name = named[2];
const room2 = roster.rooms.find((entry) => entry.name === name);
return (0, import_react6.createElement)(GroupEvent, { prefix: t(verbs[0]), room: tool === "delete_group" ? void 0 : room2, name, roster, actions });
}
case "ask_user": {
const question = roster.questions?.[sessionId];
- if (!question || question.callId !== root.callId) return (0, import_react6.createElement)("span", { className: "bt-q-gone", hidden: true });
+ if (!question || question.callId !== call2.callId) return (0, import_react6.createElement)("span", { className: "bt-q-gone", hidden: true });
return (0, import_react6.createElement)(PendingQuestion, { sessionId, question, actions, inline: true });
}
case "request_secret":
- return (0, import_react6.createElement)(SecretToolCell, { sessionId, callId: root.callId, name: arg("name"), done, content: root.content, roster, actions });
+ return (0, import_react6.createElement)(SecretToolCell, { sessionId, callId: call2.callId, name: arg("name"), done, content: call2.content, roster, actions });
case "ask_user_question": {
if (!done) return null;
let parsed = null;
try {
- parsed = JSON.parse(contentText(root.content));
+ parsed = JSON.parse(contentText(call2.content));
} catch {
parsed = null;
}
@@ -4454,11 +4462,26 @@ function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }) {
}
case "remember":
case "forget":
- return done && !root.isError ? (0, import_react6.createElement)(MemoryEvent, { sessionId, scope: arg("scope"), result: contentText(root.content), roster, actions, findBot }) : null;
+ return done && !call2.isError ? (0, import_react6.createElement)(MemoryEvent, { sessionId, scope: arg("scope"), result: contentText(call2.content), roster, actions, findBot }) : null;
default:
return null;
}
}
+function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }) {
+ const roster = useRoster((value) => value);
+ const root = node.data.root;
+ const turn = node.location?.turn?.turn ?? root.turn;
+ const hidden = isHiddenTurn(roster, sessionId, turn);
+ const findBot = (nameOrId) => roster.byId[nameOrId] ?? roster.bots.find((bot) => bot.name.toLowerCase() === String(nameOrId ?? "").toLowerCase());
+ const calls = hidden ? [] : callTree(root);
+ const drawn = calls.filter((call2) => DRAWN.has(toolName(call2)));
+ const running = root.kind === "tool-result" ? void 0 : calls.findLast((call2) => call2.kind !== "tool-result");
+ const note = running ? toolActivity(toolName(running), toolArgs(running).text, findBot, roster.byId[sessionId]) : null;
+ useLiveNote(actions, sessionId, `tool:${root.callId ?? node.key}`, note);
+ if (drawn.length === 0) return null;
+ const env = { sessionId, roster, actions, useUi, useWork, findBot };
+ return (0, import_react6.createElement)(import_react6.Fragment, null, drawn.map((call2, index) => (0, import_react6.createElement)(import_react6.Fragment, { key: call2.callId ?? index }, renderCall(call2, env))));
+}
// src/client/activity-row.js
var import_react7 = require("react");
@@ -5828,8 +5851,8 @@ var conversationOf = (roster, sessionId) => {
if (!roster.ready) return null;
const room2 = roster.roomsById[sessionId];
if (room2) return { room: room2 };
- const self2 = roster.byId[sessionId];
- return self2 ? { self: self2 } : null;
+ const self = roster.byId[sessionId];
+ return self ? { self } : null;
};
function mentionRows(roster, sessionId, query = "") {
const here = conversationOf(roster, sessionId);
diff --git a/ds-bot/src/client/cells.js b/ds-bot/src/client/cells.js
index fd20cd74..74de98f2 100644
--- a/ds-bot/src/client/cells.js
+++ b/ds-bot/src/client/cells.js
@@ -593,28 +593,39 @@ function GroupReplies({ sessionId, callId, done, content, roster, actions, useUi
}))
}
-export function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }) {
- const roster = useRoster(value => value)
- const root = node.data.root
- const done = root.kind === 'tool-result'
- const turn = node.location?.turn?.turn ?? root.turn
- const hidden = isHiddenTurn(roster, sessionId, turn)
- const tool = toolName(root)
- const { text: arg, value: argValue } = toolArgs(root)
- const findBot = nameOrId => roster.byId[nameOrId] ?? roster.bots.find(bot => bot.name.toLowerCase() === String(nameOrId ?? '').toLowerCase())
- // A running tool shows only as the activity row's phrase.
- useLiveNote(actions, sessionId, `tool:${root.callId ?? node.key}`, done || hidden ? null : toolActivity(tool, arg, findBot, roster.byId[sessionId]))
- if (hidden) return null
+// The calls ToolCell draws. A PTC program (`run_code`) dispatches the real tools as
+// its sub-calls, so a call draws by its own name wherever it sits in the tree.
+const DRAWN = new Set(['message_bot', 'stop_bot', 'create_bot', 'update_bot', 'group_relay', 'create_group', 'update_group', 'delete_group', 'post_to_group', 'ask_user', 'request_secret', 'ask_user_question', 'read_group_chat', 'remember', 'forget'])
+// The root and its sub-calls in dispatch order, each call once.
+export function callTree(root) {
+ const calls = []
+ const seen = new Set()
+ const visit = (call) => {
+ const id = call.callId ?? call
+ if (seen.has(id)) return
+ seen.add(id)
+ calls.push(call)
+ for (const child of call.subCalls ?? []) visit(child)
+ }
+ visit(root)
+ return calls
+}
+
+function renderCall(call, { sessionId, roster, actions, useUi, useWork, findBot }) {
+ const tool = toolName(call)
+ const done = call.kind === 'tool-result'
+ const { text: arg, value: argValue } = toolArgs(call)
+ const self = roster.byId[sessionId]
switch (tool) {
case 'message_bot': {
const target = findBot(arg('to')) ?? { name: arg('to') ?? '…', color: 'gray' }
- if (done && root.isError) return h('div', { className: 'bt-event' }, t("Couldn't message {name}", { name: target.name }))
+ if (done && call.isError) return h('div', { className: 'bt-event' }, t("Couldn't message {name}", { name: target.name }))
return h(EventLine, { prefix: t('Messaged'), bots: [target], onOpen: bot => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id), whole: true })
}
case 'stop_bot': {
const target = findBot(arg('bot')) ?? { name: arg('bot') ?? '…', color: 'gray' }
- if (done && root.isError) return h('div', { className: 'bt-event' }, t("Couldn't stop {name}", { name: target.name }))
- return h(EventLine, { prefix: t('Stopped'), bots: [target], onOpen: bot => bot.id && actions.openExchange(roster.byId[sessionId]?.id ?? sessionId, bot.id), whole: true })
+ if (done && call.isError) return h('div', { className: 'bt-event' }, t("Couldn't stop {name}", { name: target.name }))
+ return h(EventLine, { prefix: t('Stopped'), bots: [target], onOpen: bot => bot.id && actions.openExchange(self?.id ?? sessionId, bot.id), whole: true })
}
case 'create_bot': {
const created = findBot(arg('name'))
@@ -622,11 +633,11 @@ export function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }
return h(EventLine, { prefix: t('Created'), bots: [created], onOpen: bot => actions.openSession(bot.id) })
}
case 'update_bot': {
- const target = findBot(arg('name')) ?? findBot(arg('bot')) ?? (arg('bot') ? undefined : roster.byId[sessionId])
+ const target = findBot(arg('name')) ?? findBot(arg('bot')) ?? (arg('bot') ? undefined : self)
return done && target ? h(EventLine, { prefix: t('Updated'), bots: [target], onOpen: bot => actions.openSession(bot.id) }) : null
}
case 'group_relay':
- return h(GroupReplies, { sessionId, callId: root.callId, done, content: root.content, roster, actions, useUi, useWork })
+ return h(GroupReplies, { sessionId, callId: call.callId, done, content: call.content, roster, actions, useUi, useWork })
case 'create_group':
case 'update_group':
case 'delete_group':
@@ -639,9 +650,9 @@ export function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }
}[tool]
if (!done) return null
// Tool results quote the group's name; anything else is a refusal.
- const result = contentText(root.content)
+ const result = contentText(call.content)
const named = /^(Created group|Updated|Nothing changed in|Deleted|Posted in) "([^"]+)"/.exec(result)
- if (root.isError || !named) return h('div', { className: 'bt-event', title: result }, t(verbs[1]))
+ if (call.isError || !named) return h('div', { className: 'bt-event', title: result }, t(verbs[1]))
const name = named[2]
const room = roster.rooms.find(entry => entry.name === name)
return h(GroupEvent, { prefix: t(verbs[0]), room: tool === 'delete_group' ? undefined : room, name, roster, actions })
@@ -649,15 +660,15 @@ export function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }
case 'ask_user': {
const question = roster.questions?.[sessionId]
// Answered or closed: the card leaves no gap where it was.
- if (!question || question.callId !== root.callId) return h('span', { className: 'bt-q-gone', hidden: true })
+ if (!question || question.callId !== call.callId) return h('span', { className: 'bt-q-gone', hidden: true })
return h(PendingQuestion, { sessionId, question, actions, inline: true })
}
case 'request_secret':
- return h(SecretToolCell, { sessionId, callId: root.callId, name: arg('name'), done, content: root.content, roster, actions })
+ return h(SecretToolCell, { sessionId, callId: call.callId, name: arg('name'), done, content: call.content, roster, actions })
case 'ask_user_question': {
if (!done) return null
let parsed = null
- try { parsed = JSON.parse(contentText(root.content)) } catch { parsed = null }
+ try { parsed = JSON.parse(contentText(call.content)) } catch { parsed = null }
const answer = parsed?.answers?.[0]
const question = argValue('questions')?.[0]
if (!answer) return null
@@ -670,8 +681,26 @@ export function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }
}
case 'remember':
case 'forget':
- return done && !root.isError ? h(MemoryEvent, { sessionId, scope: arg('scope'), result: contentText(root.content), roster, actions, findBot }) : null
+ return done && !call.isError ? h(MemoryEvent, { sessionId, scope: arg('scope'), result: contentText(call.content), roster, actions, findBot }) : null
default:
return null
}
}
+
+export function ToolCell({ node, sessionId, useRoster, useUi, useWork, actions }) {
+ const roster = useRoster(value => value)
+ const root = node.data.root
+ const turn = node.location?.turn?.turn ?? root.turn
+ const hidden = isHiddenTurn(roster, sessionId, turn)
+ const findBot = nameOrId => roster.byId[nameOrId] ?? roster.bots.find(bot => bot.name.toLowerCase() === String(nameOrId ?? '').toLowerCase())
+ const calls = hidden ? [] : callTree(root)
+ const drawn = calls.filter(call => DRAWN.has(toolName(call)))
+ // The newest call still running names the work, so a program reads as the tool it is in.
+ const running = root.kind === 'tool-result' ? undefined : calls.findLast(call => call.kind !== 'tool-result')
+ const note = running ? toolActivity(toolName(running), toolArgs(running).text, findBot, roster.byId[sessionId]) : null
+ // A running tool shows only as the activity row's phrase.
+ useLiveNote(actions, sessionId, `tool:${root.callId ?? node.key}`, note)
+ if (drawn.length === 0) return null
+ const env = { sessionId, roster, actions, useUi, useWork, findBot }
+ return h(Fragment, null, drawn.map((call, index) => h(Fragment, { key: call.callId ?? index }, renderCall(call, env))))
+}
diff --git a/ds-bot/test/tool-cells.test.js b/ds-bot/test/tool-cells.test.js
new file mode 100644
index 00000000..47d27eac
--- /dev/null
+++ b/ds-bot/test/tool-cells.test.js
@@ -0,0 +1,269 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { fileURLToPath } from 'node:url'
+import { runInNewContext } from 'node:vm'
+import { build } from 'esbuild'
+
+// The tool cells, bundled once and rendered with a minimal React:
+// components run as plain functions, effects are collected and run on demand.
+const { outputFiles } = await build({
+ stdin: {
+ contents: [
+ "export { ToolCell, callTree } from './src/client/cells.js'",
+ ].join('\n'),
+ resolveDir: fileURLToPath(new URL('..', import.meta.url)),
+ },
+ bundle: true, format: 'cjs', platform: 'browser', write: false, logLevel: 'silent',
+ external: ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives'],
+})
+let effects = []
+const sets = []
+const Fragment = Symbol('Fragment')
+const h = (type, props, ...children) => ({ type, props: { ...props, children } })
+const react = {
+ createElement: h, Fragment,
+ useEffect: (effect) => { effects.push(effect) },
+ useLayoutEffect: (effect) => { effects.push(effect) },
+ useState: initial => [typeof initial === 'function' ? initial() : initial, value => sets.push(value)],
+ useMemo: make => make(), useRef: current => ({ current }), useId: () => 'card-id',
+}
+const timers = new Set()
+const module = { exports: {} }
+runInNewContext(outputFiles[0].text, {
+ module, exports: module.exports,
+ document: { hidden: false },
+ setTimeout: (fn) => { const timer = { fn }; timers.add(timer); return timer },
+ clearTimeout: timer => timers.delete(timer),
+ require: (name) => {
+ if (name === 'react') return react
+ if (name === 'react-dom') return { createPortal: node => node }
+ if (name === '@deepseek-ai/dsh-client-ui-primitives') return { MarkdownText: ({ text }) => text }
+ throw new Error(`Unexpected platform module ${name}`)
+ },
+})
+const { ToolCell, callTree } = module.exports
+
+// Runs the effects collected since the last render; returns the cleanups.
+const mount = () => {
+ const cleanups = effects.map(effect => effect()).filter(cleanup => typeof cleanup === 'function')
+ effects = []
+ return () => { for (const cleanup of cleanups) cleanup() }
+}
+const expand = (node) => {
+ if (node === null || node === undefined || typeof node === 'boolean') return null
+ if (Array.isArray(node)) return node.map(expand)
+ if (typeof node !== 'object') return node
+ if (typeof node.type === 'function') return expand(node.type(node.props))
+ return { ...node, props: { ...node.props, children: expand(node.props.children) } }
+}
+const text = (node) => {
+ if (node === null || node === undefined) return ''
+ if (Array.isArray(node)) return node.map(text).join('')
+ return typeof node === 'object' ? text(node.props.children) : String(node)
+}
+const find = (node, match) => {
+ if (Array.isArray(node)) return node.map(child => find(child, match)).find(Boolean)
+ if (!node || typeof node !== 'object') return undefined
+ return match(node) ? node : find(node.props.children, match)
+}
+const count = (haystack, needle) => haystack.split(needle).length - 1
+
+const writer = { id: 'writer', name: 'Writer', color: 'blue' }
+const chief = { id: 'chief', name: 'Chief', color: 'green' }
+const room = { id: 'room', name: 'Ops', members: ['writer', 'chief'], admin: 'chief' }
+const team = (over = {}) => ({
+ bots: [writer, chief], byId: { writer, chief }, rooms: [room], roomsById: { room }, exchangeTurns: {},
+ questions: {}, secretRequests: {}, secrets: [], ...over,
+})
+const question = (callId, over = {}) => ({ id: 'question', callId, question: 'Which draft?', options: [{ label: 'Short' }], allowCustom: true, ...over })
+const request = (callId, over = {}) => ({ id: 'request', callId, sessionId: chief.id, name: 'DEMO_TOKEN', purpose: 'Test card', status: 'pending', kind: 'fill', ...over })
+
+const text$ = value => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value) }]
+const call = (name, callId, { args = {}, content = '', subCalls = [], running = false, isError = false } = {}) => (running
+ ? { phase: 'start', name, callId, argsRaw: JSON.stringify(args), subCalls, turn: 0 }
+ : { kind: 'tool-result', name, callId, call: { name, argsRaw: JSON.stringify(args) }, content: text$(content), isError, subCalls })
+const program = (subCalls, over = {}) => call('run_code', 'program', { subCalls, ...over })
+
+const props = (root, { sessionId = chief.id, roster = team(), actions = {}, turn = 1 } = {}) => ({
+ node: { key: 'node', data: { root }, location: { turn: { turn } } }, sessionId,
+ useRoster: select => select(roster), useUi: select => select({ reactions: {}, visits: {} }), actions,
+})
+const show = (root, options) => {
+ const out = expand(ToolCell(props(root, options)))
+ effects = []
+ return out
+}
+const shown = (root, options) => text(show(root, options))
+
+// One finished call of every kind ToolCell draws, and what it shows.
+const BRANCHES = [
+ ['message_bot', { args: { to: 'Writer' } }, /Messaged.*Writer/],
+ ['stop_bot', { args: { bot: 'Writer' } }, /Stopped.*Writer/],
+ ['create_bot', { args: { name: 'Writer' } }, /Created.*Writer/],
+ ['update_bot', { args: { name: 'Writer' } }, /Updated.*Writer/],
+ ['group_relay', { content: { replies: [{ botId: 'writer', text: 'Relay reply.' }] } }, /Writer.*Relay reply\./],
+ ['create_group', { content: 'Created group "Ops" with Writer.' }, /Created group.*Ops/],
+ ['update_group', { content: 'Updated "Ops".' }, /Updated group.*Ops/],
+ ['delete_group', { content: 'Deleted "Ops".' }, /Deleted group/],
+ ['post_to_group', { content: 'Posted in "Ops".' }, /Posted in.*Ops/],
+ ['ask_user', {}, /Which draft\?.*Short/],
+ ['request_secret', { args: { name: 'DEMO_TOKEN' } }, /Chief needs a key.*DEMO_TOKEN/],
+ ['ask_user_question', { args: { questions: [{ question: 'Ship it?', options: [{ label: 'Yes' }] }] }, content: { answers: [{ selected: ['Yes'] }] } }, /Ship it\?.*Yes/],
+ ['read_group_chat', { args: { group: 'Ops' } }, /Read.*Ops/],
+ ['remember', { args: { scope: 'Chief' }, content: 'Saved to Chief memory.' }, /Memory updated/],
+ ['forget', { args: { scope: 'Chief' }, content: 'Removed from Chief memory.' }, /Memory updated/],
+]
+const rosterFor = callId => team({ questions: { chief: question(callId) }, secretRequests: { chief: [request(callId)] } })
+
+test('every call ToolCell draws shows the same nested in a PTC program as on its own', () => {
+ assert.equal(BRANCHES.length, 15)
+ for (const [name, options, expected] of BRANCHES) {
+ const native = shown(call(name, 'direct', options), { roster: rosterFor('direct') })
+ assert.match(native, expected, `${name} on its own`)
+ const nested = shown(program([call(name, 'program:ptc:1', options)]), { roster: rosterFor('program:ptc:1') })
+ assert.equal(nested, native, `${name} under run_code`)
+ const deep = shown(program([call('run_code', 'program:ptc:1', { subCalls: [call(name, 'program:ptc:1:ptc:1', options)] })]), { roster: rosterFor('program:ptc:1:ptc:1') })
+ assert.equal(deep, native, `${name} two programs deep`)
+ }
+})
+
+test('a program draws every known sub-call in dispatch order and each call once', () => {
+ const relay = call('group_relay', 'program:ptc:2', { content: { replies: [{ botId: 'writer', text: 'Group reply.' }] } })
+ const message = call('message_bot', 'program:ptc:1', { args: { to: 'Writer' } })
+ const secret = call('request_secret', 'program:ptc:3', { args: { name: 'DEMO_TOKEN' } })
+ const root = program([message, call('run_code', 'program:ptc:4', { subCalls: [relay, secret, message] }), relay, call('bash', 'program:ptc:5')])
+ assert.deepEqual(JSON.parse(JSON.stringify(callTree(root).map(entry => entry.callId))), ['program', 'program:ptc:1', 'program:ptc:4', 'program:ptc:2', 'program:ptc:3', 'program:ptc:5'])
+ const out = shown(root, { roster: team({ secretRequests: { chief: [request('program:ptc:3')] } }) })
+ assert.match(out, /Messaged.*Writer.*Group reply\..*Chief needs a key/)
+ assert.equal(count(out, 'Messaged'), 1)
+ assert.equal(count(out, 'Group reply.'), 1)
+ assert.equal(count(out, 'needs a key'), 1)
+})
+
+test('nested group relays keep their own replies in order, each once', () => {
+ const first = call('group_relay', 'program:ptc:1:ptc:1', { content: { replies: [{ botId: 'writer', text: 'First reply.' }] } })
+ const second = call('group_relay', 'program:ptc:1:ptc:2', { content: { replies: [{ botId: 'writer', text: 'Second reply.' }] } })
+ const out = shown(program([call('run_code', 'program:ptc:1', { subCalls: [first, second] }), first]), { sessionId: 'room' })
+ assert.match(out, /First reply\..*Second reply\./)
+ assert.equal(count(out, 'First reply.'), 1)
+})
+
+test('cards and replies still show when the program\'s own call head left the loaded history', () => {
+ const roster = team({ questions: { chief: question('program:ptc:3') }, secretRequests: { chief: [request('program:ptc:1')] } })
+ const relay = call('group_relay', 'program:ptc:2', { content: { replies: [{ botId: 'writer', text: 'Group reply.' }] } })
+ const root = { ...program([call('request_secret', 'program:ptc:1', { args: { name: 'DEMO_TOKEN' } }), relay, call('ask_user', 'program:ptc:3')]), name: '', call: null }
+ assert.match(shown(root, { roster }), /Chief needs a key.*Group reply\..*Which draft\?/)
+})
+
+test('each sub-call shows its own state, not its program\'s', () => {
+ const created = call('create_bot', 'program:ptc:1', { args: { name: 'Writer' } })
+ assert.match(shown(program([created], { running: true })), /Created.*Writer/)
+ assert.equal(shown(program([{ ...call('create_bot', 'program:ptc:1', { args: { name: 'Writer' }, running: true }) }])), '')
+ const failed = call('message_bot', 'program:ptc:1', { args: { to: 'Writer' }, isError: true })
+ assert.match(shown(program([failed])), /Couldn't message Writer/)
+ assert.match(shown(program([call('message_bot', 'program:ptc:1', { args: { to: 'Writer' } })], { isError: true })), /^Messaged/)
+ const refused = call('post_to_group', 'program:ptc:1', { content: 'No group is called "Nope".', isError: true })
+ const posted = call('post_to_group', 'program:ptc:2', { content: 'Posted in "Ops".' })
+ assert.match(shown(program([refused, posted])), /Couldn't post in the group.*Posted in.*Ops/)
+})
+
+test('a program with no known sub-call draws nothing, as before', () => {
+ assert.equal(ToolCell(props(program([]))), null)
+ assert.equal(ToolCell(props(program([call('bash', 'program:ptc:1'), call('read_file', 'program:ptc:2')]))), null)
+ assert.equal(ToolCell(props(call('bash', 'direct'))), null)
+ effects = []
+})
+
+test('a hidden Bot-to-Bot turn draws none of its sub-calls', () => {
+ const roster = team({ exchangeTurns: { chief: [1] }, secretRequests: { chief: [request('program:ptc:1')] } })
+ const root = program([call('request_secret', 'program:ptc:1', { args: { name: 'DEMO_TOKEN' } }), call('message_bot', 'program:ptc:2', { args: { to: 'Writer' } })])
+ assert.equal(shown(root, { roster }), '')
+ assert.match(shown(root, { roster, turn: 2 }), /Chief needs a key.*Messaged/)
+})
+
+test('a message line opens the exchange of the chat\'s Bot, from any part', () => {
+ const opened = []
+ const out = show(program([call('message_bot', 'program:ptc:1', { args: { to: 'Writer' } })]), { actions: { openExchange: (...ids) => opened.push(ids) } })
+ find(out, node => node.type === 'button').props.onClick()
+ const current = { ...chief, sessionId: 'chief-2', parts: ['chief', 'chief-2'] }
+ const roster = team({ bots: [writer, current], byId: { writer, chief: current, 'chief-2': current } })
+ const later = show(call('message_bot', 'direct', { args: { to: 'Writer' } }), { sessionId: 'chief-2', roster, actions: { openExchange: (...ids) => opened.push(ids) } })
+ find(later, node => node.type === 'button').props.onClick()
+ assert.deepEqual(JSON.parse(JSON.stringify(opened)), [['chief', 'writer'], ['chief', 'writer']])
+})
+
+// The activity row reads one note per chat node.
+const notes = (root, options = {}) => {
+ const log = []
+ ToolCell(props(root, { ...options, actions: { noteLive: (sessionId, id, entry) => log.push({ sessionId, id, entry }) } }))
+ const unmount = mount()
+ unmount()
+ return JSON.parse(JSON.stringify(log))
+}
+
+test('the live note follows the running sub-call of a program', () => {
+ const asking = notes(program([call('message_bot', 'program:ptc:1', { args: { to: 'Writer' }, running: true })], { running: true }))
+ assert.deepEqual(asking, [
+ { sessionId: 'chief', id: 'tool:program', entry: { label: 'Asking Writer', state: 'sending' } },
+ { sessionId: 'chief', id: 'tool:program', entry: null },
+ ])
+ const relaying = notes(program([call('message_bot', 'program:ptc:1', { args: { to: 'Writer' } }), call('group_relay', 'program:ptc:2', { running: true })], { running: true }))
+ assert.equal(relaying[0].entry.relay, true)
+ const shell = notes(program([call('bash', 'program:ptc:1', { running: true })], { running: true }))
+ assert.equal(shell[0].entry.label, 'Running shell commands')
+ const between = notes(program([call('message_bot', 'program:ptc:1', { args: { to: 'Writer' } })], { running: true }))
+ assert.equal(between[0].entry.label, null)
+ assert.deepEqual(notes(program([call('message_bot', 'program:ptc:1', { args: { to: 'Writer' }, running: true })])), [])
+ const roster = team({ exchangeTurns: { chief: [1] } })
+ assert.deepEqual(notes(program([call('message_bot', 'program:ptc:1', { args: { to: 'Writer' }, running: true })], { running: true }), { roster }), [])
+ assert.equal(notes(call('message_bot', 'direct', { args: { to: 'Writer' }, running: true }))[0].entry.label, 'Asking Writer')
+})
+
+// #38: a PTC group round's replies vanished once the round ended.
+test('a PTC group relay shows its replies from the sub-call, live and after reload', async () => {
+ const replies = [{ botId: 'writer', text: 'Hello from Writer.' }, { botId: 'chief', text: 'Hello from Chief.' }]
+ const finished = program([call('group_relay', 'call-1-1:ptc:1', { content: { replies } })])
+ const reloaded = shown(finished, { sessionId: 'room' })
+ assert.match(reloaded, /Writer.*Hello from Writer\..*Chief.*Admin.*Hello from Chief\./)
+ const 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 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 })
+ const relay = find(ToolCell(props(running, { sessionId: 'room', actions })), node => node.type?.name === 'GroupReplies')
+ effects = []
+ sets.length = 0
+ relay.type(relay.props)
+ const stop = mount()
+ await new Promise(resolve => setImmediate(resolve))
+ stop()
+ timers.clear()
+ assert.deepEqual(asked, ['room'])
+ 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.
+test('PTC secret and question cards show at their sub-calls and act on their own requests', async () => {
+ const roster = team({ questions: { chief: question('call-1-2:ptc:1') }, secretRequests: { chief: [request('call-2-1:ptc:1')] } })
+ const answers = []
+ const canceled = []
+ const actions = { answerQuestion: async (...args) => answers.push(args), secretCancel: async id => canceled.push(id) }
+ const asking = show(program([call('ask_user', 'call-1-2:ptc:1')]), { roster, actions })
+ assert.match(text(asking), /Which draft\?/)
+ find(asking, node => node.type === 'button' && node.props.className === 'bt-q-opt').props.onClick()
+ assert.deepEqual(JSON.parse(JSON.stringify(answers)), [['chief', 'question', { selected: ['Short'], custom: '' }]])
+
+ const secret = show(program([call('request_secret', 'call-2-1:ptc:1', { args: { name: 'DEMO_TOKEN' }, running: true })], { running: true }), { roster, actions })
+ assert.match(text(secret), /Chief needs a key/)
+ await find(secret, node => node.props['aria-label'] === 'Cancel the request').props.onClick()
+ assert.deepEqual(canceled, ['request'])
+
+ const settled = team({ secretRequests: { chief: [request('call-2-1:ptc:1', { status: 'canceled' })] } })
+ const after = shown(program([call('request_secret', 'call-2-1:ptc:1', { args: { name: 'DEMO_TOKEN' } })]), { roster: settled })
+ assert.match(after, /Chief asked for DEMO_TOKEN.*Canceled/)
+ assert.doesNotMatch(after, /Paste or type the key/)
+ assert.doesNotMatch(shown(program([call('ask_user', 'call-0-1:ptc:1')]), { roster }), /Which draft\?/)
+ assert.equal(shown(program([call('ask_user', 'call-1-2:ptc:1')]), { roster: team() }), '')
+})