diff --git a/docs/plans/2026-11-06-operator-tasks-origin.md b/docs/plans/2026-11-06-operator-tasks-origin.md new file mode 100644 index 0000000000..045e3063e3 --- /dev/null +++ b/docs/plans/2026-11-06-operator-tasks-origin.md @@ -0,0 +1,89 @@ +# Operator Tasks, and the A · U badge + +## Why + +The Bot details panel listed two things: what the Bot was working on (Active Tasks) and +what waited on the user (Unresolved Tasks). Nothing said whether the Bot was working on +the user's own ask or on another Bot's work, so the panel could not answer the one +question the operator has while several Bots run at once: who is doing what I asked for. + +This adds a third list, Operator Tasks, above Active Tasks, and replaces the single +unresolved count in the chat header with two numbers, `A · U`. + +## What an Operator Task is + +A job is the user's when it started from any of: + +- a message the user sent to the Bot's own chat, including one they steered into a + running turn; +- a task the user scheduled for that Bot; +- an order relayed by a manager Bot on the user's behalf, hop by hop (Igor to a coding + Bot, and on to a Bot that coding Bot asked). + +It leaves the list when the Bot's turn for that job ends, which is when the Bot sends +its reply. A job that is waiting on another Bot stays listed, through the open work it +holds (`state.works`), until the result comes back and the reply that carries it is sent. + +Group chat work stays in Active Tasks. A post in a group is queued as a room message, +not a user turn, and the group already shows who was called. + +## How the origin is recorded + +Nothing recorded where a task came from, so the host now records it in three places: + +- `src/host/turns.js`: the running turn of a Session carries `origin: 'operator'` when + it was started by the user, by a schedule, or by a relayed order. `originFrom` names + the manager Bot that passed it on, and `askText` keeps the user's words for the row. + The turn's origin is exposed on `workView`, which is what the panel reads. +- `src/host/delivery.js`: a message sent while its sender works for the operator carries + `origin: 'operator'` on its source, so each relay hop passes the origin on. +- `src/host/handoffs.js`: the work a Bot opens remembers its origin (`openWork`), so the + job keeps it across a restart, and `workOrigin` reads it back. + +A relay after a restart falls back to the work it answers, so a job does not lose its +origin when the app restarts mid-job. + +## The lists + +`src/host/operator-tasks.js` now returns `operator`, `active` and `unresolved` per Bot: + +- a running turn whose origin is the operator (kind `ask`, or `relay` with `via`); +- an order whose work carries the operator origin; +- a wait whose open work carries the operator origin, with the age of that work. + +An order stands back while the Bot's running turn for the same work is shown, so a job +appears once. No item can be in both lists, since one origin decides the list. + +## The badge + +`OperatorBadge` in the chat header shows `A · U`: A in the accent colour, U in the +danger colour the count used before, each capped at `99+`, and nothing at all when both +are 0. The panel keeps its three section headings with their own counts. + +## The three 11/5 local hotfixes are not in this branch + +The installed 0.2.7 also carries three local fixes from the 11/5 DeepSeek Harness 0.2.2 +session: the pre-step and seam failure capture in `parts.js`, the tools waterfall guard +in `tools.js`, and the stack on a turn failure in `turns.js`. + +They exist only in the installed copy and in `patches/ds-bot@0.2.7.patch`. Adding them to +this branch was tried and reverted: under the branch's pinned DeepSeek Harness +(`0.2.1-rc.5`, also under `0.2.2-rc.1`) they break 27 tests, because they wrap DSH +services (`tools.resolve`, `systemPrompt.assemble`) that the test host does not provide +the same way, and they change the plugin's registration list that `test/install.test.js` +fixes. Porting them is a DeepSeek Harness upgrade job, not a panel change, and the repo +rules forbid patching DSH from the plugin. The regenerated patch is built from the +installed bytes, so the running app keeps all three. + +## Verification + +- `npm test`, `node scripts/build-client.mjs --check` and `npm run lint` pass. +- `test/operator-tasks.test.js` drives the host: a turn the user starts is an Operator + Task until its reply, a relayed turn carries the origin (a plain team job does not), + the orders and waits land in the right list, and nothing is in both. +- `test/operator-tasks-client.test.js` renders the panel and the badge and asserts the + section order, the labels, the two colours, the `99+` cap and the empty state. +- The mock test bench (`dev/bench.sh`) cannot start on this workstation: WSL has no + distribution and Git Bash has no `setsid`. The panel was rendered from the real + components and the real stylesheet in headless Chromium instead (screenshot in the + session log), and the unit tests above cover the behaviour. diff --git a/ds-bot/client.js b/ds-bot/client.js index 4fd854ae13..e811c6e2b9 100644 --- a/ds-bot/client.js +++ b/ds-bot/client.js @@ -1174,13 +1174,20 @@ var ZH = { "New task": "新建任务", "No scheduled tasks yet.": "还没有定时任务。", "No scheduled tasks yet. Add one": "还没有定时任务,去添加", + "Operator Tasks": "你交给它的任务", "Active Tasks": "进行中的任务", "Unresolved Tasks": "待你处理的任务", "{title} · {count}": "{title} · {count}", + "Your ask": "你的要求", + "Relayed by {name}": "由 {name} 转达", + "Nothing of yours in hand.": "你交给它的任务都完成了。", "Nothing running right now.": "现在没有在进行的工作。", "Nothing waiting on you.": "没有等你处理的事。", + "1 task from you": "有 1 件事来自你", + "{count} tasks from you": "有 {count} 件事来自你", "1 task waits on you": "有 1 件事等你处理", "{count} tasks wait on you": "有 {count} 件事等你处理", + "{yours} from you, {waiting} waiting on you": "{yours} 件来自你,{waiting} 件等你处理", "a teammate": "一位队友", "a group": "一个群聊", 'in group "{name}"': "在群聊「{name}」里", @@ -11262,8 +11269,9 @@ var SIDEBAR_CSS = ` // src/client/operator-tasks.js var import_react22 = require("react"); -var EMPTY = { active: [], unresolved: [] }; +var EMPTY = { operator: [], active: [], unresolved: [] }; var operatorTasksOf = (roster, botId) => roster.operatorTasks?.[botId] ?? EMPTY; +var operatorCount = (roster, botId) => operatorTasksOf(roster, botId).operator.length; var unresolvedCount = (roster, botId) => operatorTasksOf(roster, botId).unresolved.length; var nameOf = (roster, id) => roster.byId?.[id]?.name ?? roster.roomsById?.[id]?.name ?? t("a teammate"); var where = (roster, item) => item.roomId ? t('in group "{name}"', { name: roster.roomsById?.[item.roomId]?.name ?? t("a group") }) : ""; @@ -11287,12 +11295,15 @@ function unresolvedLine(item) { return { label: "", text: item.text ?? "" }; } } +var doingOf2 = (item) => { + if (item.switching) return t("Moving on to a fresh part"); + if (item.tool === void 0) return item.text || t("Working"); + return item.target ? t("Running {tool} on {target}", { tool: item.tool, target: item.target }) : t("Running {tool}", { tool: item.tool }); +}; function activeLine(item, roster) { switch (item.kind) { - case "turn": { - const doing = item.switching ? t("Moving on to a fresh part") : item.tool ? item.target ? t("Running {tool} on {target}", { tool: item.tool, target: item.target }) : t("Running {tool}", { tool: item.tool }) : item.text || t("Working"); - return { label: t("Working now"), text: [doing, where(roster, item)].filter(Boolean).join(" ") }; - } + case "turn": + return { label: t("Working now"), text: [doingOf2(item), where(roster, item)].filter(Boolean).join(" ") }; case "order": return { label: t("Order"), text: t("From {name}", { name: nameOf(roster, item.from) }) }; case "waiting": @@ -11301,6 +11312,16 @@ function activeLine(item, roster) { return { label: "", text: item.text ?? "" }; } } +function operatorLine(item, roster) { + switch (item.kind) { + case "ask": + return { label: t("Your ask"), text: doingOf2(item) }; + case "relay": + return { label: t("Relayed by {name}", { name: item.via ?? t("a teammate") }), text: doingOf2(item) }; + default: + return activeLine(item, roster); + } +} function TaskList({ title, items, line, roster, empty }) { return (0, import_react22.createElement)( "div", @@ -11326,14 +11347,24 @@ function TaskList({ title, items, line, roster, empty }) { function OperatorTasks({ bot, roster }) { const tasks = operatorTasksOf(roster, bot.id); return [ + (0, import_react22.createElement)(TaskList, { key: "operator", title: t("Operator Tasks"), items: tasks.operator, line: operatorLine, roster, empty: t("Nothing of yours in hand.") }), (0, import_react22.createElement)(TaskList, { key: "active", title: t("Active Tasks"), items: tasks.active, line: activeLine, roster, empty: t("Nothing running right now.") }), (0, import_react22.createElement)(TaskList, { key: "unresolved", title: t("Unresolved Tasks"), items: tasks.unresolved, line: unresolvedLine, roster, empty: t("Nothing waiting on you.") }) ]; } -function UnresolvedBadge({ count }) { - if (!(count > 0)) return null; - const label = count === 1 ? t("1 task waits on you") : t("{count} tasks wait on you", { count }); - return (0, import_react22.createElement)("span", { className: "bt-pill-tasks", title: label, "aria-label": label }, count > 99 ? "99+" : String(count)); +var capped = (count) => count > 99 ? "99+" : String(count); +function OperatorBadge({ operator, unresolved }) { + const yours = operator > 0 ? operator : 0; + const waiting = unresolved > 0 ? unresolved : 0; + if (yours === 0 && waiting === 0) return null; + const label = waiting === 0 ? yours === 1 ? t("1 task from you") : t("{count} tasks from you", { count: yours }) : yours === 0 ? waiting === 1 ? t("1 task waits on you") : t("{count} tasks wait on you", { count: waiting }) : t("{yours} from you, {waiting} waiting on you", { yours, waiting }); + return (0, import_react22.createElement)( + "span", + { className: "bt-pill-tasks", title: label, "aria-label": label }, + (0, import_react22.createElement)("span", { className: "bt-pill-yours" }, capped(yours)), + (0, import_react22.createElement)("span", { className: "bt-pill-dot", "aria-hidden": true }, "·"), + (0, import_react22.createElement)("span", { className: "bt-pill-waiting" }, capped(waiting)) + ); } var OPERATOR_TASKS_CSS = ` .bt-ops-empty{font-size:12px;line-height:16px;color:var(--bt-ink-3);padding:2px 0} @@ -11344,7 +11375,10 @@ var OPERATOR_TASKS_CSS = ` .bt-ops-age{flex:none;font-size:11px;line-height:16px;color:var(--bt-ink-3);font-variant-numeric:tabular-nums;white-space:nowrap} .bt-ops-text{font-size:12px;line-height:16px;color:var(--bt-ink-2);overflow-wrap:anywhere;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden} .bt-ops-note{font-size:11px;line-height:15px;color:var(--bt-ink-3);margin-top:2px} -.bt-pill-tasks{flex:none;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:var(--bt-danger);color:var(--bt-main);font-size:11px;line-height:18px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums} +.bt-pill-tasks{flex:none;display:inline-flex;align-items:center;gap:3px;height:18px;padding:0 6px;border-radius:999px;background:var(--bt-hover);font-size:11px;line-height:18px;font-weight:600;font-variant-numeric:tabular-nums} +.bt-pill-yours{color:var(--bt-accent)} +.bt-pill-waiting{color:var(--bt-danger)} +.bt-pill-dot{color:var(--bt-ink-3);font-weight:400} `; // src/client/header.js @@ -11460,7 +11494,7 @@ function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSe (0, import_react23.createElement)("span", { className: "bt-pill-goal" }, (0, import_react23.createElement)("span", { className: "bt-pill-ico", "aria-hidden": true }, (0, import_react23.createElement)(GoalIcon)), (0, import_react23.createElement)("span", { className: "bt-pill-title" }, view.title)), (0, import_react23.createElement)("span", { className: "bt-pill-name" }, name) ) : (0, import_react23.createElement)("span", { className: "bt-pill-name" }, away ? t("Back to chat") : bot?.name ?? room2?.name ?? (title || t("New chat"))), - bot && !away ? (0, import_react23.createElement)(UnresolvedBadge, { count: unresolvedCount(roster, bot.id) }) : null, + bot && !away ? (0, import_react23.createElement)(OperatorBadge, { operator: operatorCount(roster, bot.id), unresolved: unresolvedCount(roster, bot.id) }) : null, goalShown && view?.number !== void 0 ? (0, import_react23.createElement)("span", { className: "bt-pill-count" }, `${view.number}/${view.count}`) : null, (0, import_react23.createElement)(MemoryNotice, { shown: memoryNotice }), (0, import_react23.createElement)("span", { className: "bt-pill-go", "aria-hidden": true }, (0, import_react23.createElement)(GoArrow)) diff --git a/ds-bot/src/client/header.js b/ds-bot/src/client/header.js index 27285d76a8..e755197de3 100644 --- a/ds-bot/src/client/header.js +++ b/ds-bot/src/client/header.js @@ -6,7 +6,7 @@ import { botState, BotAvatar, RoomAvatar } from './mark.js' import { ActivityIndicator } from './activity-row.js' import { clockLabel, openingTurn, unseenSince } from './cells.js' import { GoalIsland, goalView } from './goal.js' -import { UnresolvedBadge, unresolvedCount } from './operator-tasks.js' +import { OperatorBadge, operatorCount, unresolvedCount } from './operator-tasks.js' import { viewBottom } from './motion.js' import { t } from './i18n.js' @@ -128,7 +128,7 @@ export function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus h('span', { className: 'bt-pill-goal' }, h('span', { className: 'bt-pill-ico', 'aria-hidden': true }, h(GoalIcon)), h('span', { className: 'bt-pill-title' }, view.title)), h('span', { className: 'bt-pill-name' }, name)) : h('span', { className: 'bt-pill-name' }, away ? t('Back to chat') : bot?.name ?? room?.name ?? (title || t('New chat'))), - bot && !away ? h(UnresolvedBadge, { count: unresolvedCount(roster, bot.id) }) : null, + bot && !away ? h(OperatorBadge, { operator: operatorCount(roster, bot.id), unresolved: unresolvedCount(roster, bot.id) }) : null, goalShown && view?.number !== undefined ? h('span', { className: 'bt-pill-count' }, `${view.number}/${view.count}`) : null, h(MemoryNotice, { shown: memoryNotice }), h('span', { className: 'bt-pill-go', 'aria-hidden': true }, h(GoArrow))) diff --git a/ds-bot/src/client/i18n.js b/ds-bot/src/client/i18n.js index fa21ffe0ce..27af413370 100644 --- a/ds-bot/src/client/i18n.js +++ b/ds-bot/src/client/i18n.js @@ -1127,13 +1127,20 @@ const ZH = { 'New task': '新建任务', 'No scheduled tasks yet.': '还没有定时任务。', 'No scheduled tasks yet. Add one': '还没有定时任务,去添加', + 'Operator Tasks': '你交给它的任务', 'Active Tasks': '进行中的任务', 'Unresolved Tasks': '待你处理的任务', '{title} · {count}': '{title} · {count}', + 'Your ask': '你的要求', + 'Relayed by {name}': '由 {name} 转达', + 'Nothing of yours in hand.': '你交给它的任务都完成了。', 'Nothing running right now.': '现在没有在进行的工作。', 'Nothing waiting on you.': '没有等你处理的事。', + '1 task from you': '有 1 件事来自你', + '{count} tasks from you': '有 {count} 件事来自你', '1 task waits on you': '有 1 件事等你处理', '{count} tasks wait on you': '有 {count} 件事等你处理', + '{yours} from you, {waiting} waiting on you': '{yours} 件来自你,{waiting} 件等你处理', 'a teammate': '一位队友', 'a group': '一个群聊', 'in group "{name}"': '在群聊「{name}」里', diff --git a/ds-bot/src/client/operator-tasks.js b/ds-bot/src/client/operator-tasks.js index 09c84771f5..102daffef4 100644 --- a/ds-bot/src/client/operator-tasks.js +++ b/ds-bot/src/client/operator-tasks.js @@ -1,14 +1,15 @@ -// A Bot's operator tasks in its details panel, and the count after its name in the -// chat header. The host builds the list (src/host/operator-tasks.js): Unresolved is -// what waits on the user, Active what the Bot works on. The header counts -// Unresolved only, so its number always means "this needs you". +// A Bot's operator tasks in its details panel, and the two counts after its name in the +// chat header. The host builds the lists (src/host/operator-tasks.js): Operator is what +// the user asked the Bot to do, Active what it does for anyone else, Unresolved what +// waits on the user. The header shows "A · U": A in accent blue, U in the danger colour. import { createElement as h } from 'react' import { relativeShort } from './text.js' import { t } from './i18n.js' -const EMPTY = { active: [], unresolved: [] } +const EMPTY = { operator: [], active: [], unresolved: [] } export const operatorTasksOf = (roster, botId) => roster.operatorTasks?.[botId] ?? EMPTY +export const operatorCount = (roster, botId) => operatorTasksOf(roster, botId).operator.length export const unresolvedCount = (roster, botId) => operatorTasksOf(roster, botId).unresolved.length const nameOf = (roster, id) => roster.byId?.[id]?.name ?? roster.roomsById?.[id]?.name ?? t('a teammate') @@ -29,20 +30,31 @@ function unresolvedLine(item) { } } +// What a running item is doing, in its own words. +const doingOf = (item) => { + if (item.switching) return t('Moving on to a fresh part') + if (item.tool === undefined) return item.text || t('Working') + return item.target ? t('Running {tool} on {target}', { tool: item.tool, target: item.target }) : t('Running {tool}', { tool: item.tool }) +} + function activeLine(item, roster) { switch (item.kind) { - case 'turn': { - const doing = item.switching ? t('Moving on to a fresh part') - : item.tool ? (item.target ? t('Running {tool} on {target}', { tool: item.tool, target: item.target }) : t('Running {tool}', { tool: item.tool })) - : item.text || t('Working') - return { label: t('Working now'), text: [doing, where(roster, item)].filter(Boolean).join(' ') } - } + case 'turn': return { label: t('Working now'), text: [doingOf(item), where(roster, item)].filter(Boolean).join(' ') } case 'order': return { label: t('Order'), text: t('From {name}', { name: nameOf(roster, item.from) }) } case 'waiting': return { label: t('Waiting on'), text: [...item.bots, ...item.rooms].map(id => nameOf(roster, id)).join(', ') } default: return { label: '', text: item.text ?? '' } } } +// The user's own work: the ask in their words, or the manager Bot that passed it on. +function operatorLine(item, roster) { + switch (item.kind) { + case 'ask': return { label: t('Your ask'), text: doingOf(item) } + case 'relay': return { label: t('Relayed by {name}', { name: item.via ?? t('a teammate') }), text: doingOf(item) } + default: return activeLine(item, roster) + } +} + function TaskList({ title, items, line, roster, empty }) { return h('div', { className: 'bt-ops' }, h('div', { className: 'bt-section-title' }, items.length === 0 ? title : t('{title} · {count}', { title, count: items.length })), @@ -62,16 +74,29 @@ function TaskList({ title, items, line, roster, empty }) { export function OperatorTasks({ bot, roster }) { const tasks = operatorTasksOf(roster, bot.id) return [ + h(TaskList, { key: 'operator', title: t('Operator Tasks'), items: tasks.operator, line: operatorLine, roster, empty: t('Nothing of yours in hand.') }), h(TaskList, { key: 'active', title: t('Active Tasks'), items: tasks.active, line: activeLine, roster, empty: t('Nothing running right now.') }), h(TaskList, { key: 'unresolved', title: t('Unresolved Tasks'), items: tasks.unresolved, line: unresolvedLine, roster, empty: t('Nothing waiting on you.') }), ] } -// After the Bot's name in the chat header; nothing at all when the count is 0. -export function UnresolvedBadge({ count }) { - if (!(count > 0)) return null - const label = count === 1 ? t('1 task waits on you') : t('{count} tasks wait on you', { count }) - return h('span', { className: 'bt-pill-tasks', title: label, 'aria-label': label }, count > 99 ? '99+' : String(count)) +// After the Bot's name in the chat header: "A · U", the tasks the user gave it and the +// tasks waiting on the user. Nothing at all when both are 0. +const capped = count => (count > 99 ? '99+' : String(count)) + +export function OperatorBadge({ operator, unresolved }) { + const yours = operator > 0 ? operator : 0 + const waiting = unresolved > 0 ? unresolved : 0 + if (yours === 0 && waiting === 0) return null + const label = waiting === 0 + ? (yours === 1 ? t('1 task from you') : t('{count} tasks from you', { count: yours })) + : yours === 0 + ? (waiting === 1 ? t('1 task waits on you') : t('{count} tasks wait on you', { count: waiting })) + : t('{yours} from you, {waiting} waiting on you', { yours, waiting }) + return h('span', { className: 'bt-pill-tasks', title: label, 'aria-label': label }, + h('span', { className: 'bt-pill-yours' }, capped(yours)), + h('span', { className: 'bt-pill-dot', 'aria-hidden': true }, '·'), + h('span', { className: 'bt-pill-waiting' }, capped(waiting))) } export const OPERATOR_TASKS_CSS = ` @@ -83,5 +108,8 @@ export const OPERATOR_TASKS_CSS = ` .bt-ops-age{flex:none;font-size:11px;line-height:16px;color:var(--bt-ink-3);font-variant-numeric:tabular-nums;white-space:nowrap} .bt-ops-text{font-size:12px;line-height:16px;color:var(--bt-ink-2);overflow-wrap:anywhere;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden} .bt-ops-note{font-size:11px;line-height:15px;color:var(--bt-ink-3);margin-top:2px} -.bt-pill-tasks{flex:none;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:var(--bt-danger);color:var(--bt-main);font-size:11px;line-height:18px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums} +.bt-pill-tasks{flex:none;display:inline-flex;align-items:center;gap:3px;height:18px;padding:0 6px;border-radius:999px;background:var(--bt-hover);font-size:11px;line-height:18px;font-weight:600;font-variant-numeric:tabular-nums} +.bt-pill-yours{color:var(--bt-accent)} +.bt-pill-waiting{color:var(--bt-danger)} +.bt-pill-dot{color:var(--bt-ink-3);font-weight:400} ` diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js index 3039b168a0..f17fe7220f 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -69,6 +69,12 @@ export function install(rt) { const fromName = from?.name ?? 'You' const room = rt.roomOf(roomId) const asker = work === undefined ? undefined : rt.botOf(state.works?.[work]?.from)?.name + // A message sent while its sender works for the operator is the operator's ask, and + // says so on its source: each relay hop passes it on, so a job keeps its origin all + // the way down the team. After a restart the work it is for remembers (handoffs.js). + const origin = rt.operatorTurnOf?.(fromId) !== undefined + ? 'operator' + : (work === undefined ? undefined : state.works?.[work]?.origin) // Session events reject `undefined` members, so optional fields are omitted instead. const source = { kind: SOURCE_KIND, @@ -76,6 +82,7 @@ export function install(rt) { role, exchangeId, senderName: fromName, + ...(origin === 'operator' ? { origin } : {}), ...(work ? { work } : {}), ...(fromId ? { senderSessionId: fromId } : {}), ...(replyTo ? { replyTo } : {}), diff --git a/ds-bot/src/host/handoffs.js b/ds-bot/src/host/handoffs.js index 58ef7f8e52..278ff43f57 100644 --- a/ds-bot/src/host/handoffs.js +++ b/ds-bot/src/host/handoffs.js @@ -94,13 +94,18 @@ export function install(rt) { // (or a turn picked up again) goes on with. const workOf = info => (info === undefined ? undefined : info.role === 'request' && info.audience !== 'user' ? info.exchangeId : info.work) + // Where the work came from, for the operator's task lists (turns.js, operator-tasks.js). + const workOrigin = id => (id === undefined ? undefined : works()[id]?.origin) // `parent`: the work the sender was doing when it sent this one. `child`: the // session id of the subagent a run of this work belongs to — the run, not the // child, is the sub-work, so a child that is continued hands up a result per run. function openWork(id, { from, to, parent, fromRoom, room, name, child }) { const above = parent === undefined ? undefined : works()[parent] - works()[id] = { ...(from ? { from } : {}), ...(to ? { to } : {}), ...(room ? { room } : {}), ...(above ? { parent } : {}), ...(fromRoom ? { fromRoom } : {}), ...(name ? { name } : {}), ...(child ? { child } : {}), open: [], results: [], at: Date.now() } + // The job remembers where it came from: the work it belongs to, else the turn its + // sender is running. Saved with the rest, so a restart keeps the Operator Task. + const origin = above?.origin ?? (rt.operatorTurnOf?.(from) !== undefined ? 'operator' : undefined) + works()[id] = { ...(from ? { from } : {}), ...(to ? { to } : {}), ...(room ? { room } : {}), ...(above ? { parent } : {}), ...(fromRoom ? { fromRoom } : {}), ...(name ? { name } : {}), ...(child ? { child } : {}), ...(origin ? { origin } : {}), open: [], results: [], at: Date.now() } if (above !== undefined) above.open.push(id) save() } @@ -362,5 +367,5 @@ export function install(rt) { return lines.join('; ') } - Object.assign(rt, { workOf, openWork, closeWork, dropWork, takenWork: taken, lateWork, answerMissed, ownsWork: owns, waitsWork: waits, holdWork: hold, workAsker: askedBy, answerText, upstreamOf, sameWork, forgetBotWork: forgetBot, statusOf, waitingView, settleSubWork, subWorkRun, nameSubWork }) + Object.assign(rt, { workOf, workOrigin, openWork, closeWork, dropWork, takenWork: taken, lateWork, answerMissed, ownsWork: owns, waitsWork: waits, holdWork: hold, workAsker: askedBy, answerText, upstreamOf, sameWork, forgetBotWork: forgetBot, statusOf, waitingView, settleSubWork, subWorkRun, nameSubWork }) } diff --git a/ds-bot/src/host/operator-tasks.js b/ds-bot/src/host/operator-tasks.js index 96a9aac84d..c82ab78ea2 100644 --- a/ds-bot/src/host/operator-tasks.js +++ b/ds-bot/src/host/operator-tasks.js @@ -1,7 +1,8 @@ -// Operator tasks: per Bot, what waits on the user (Unresolved) and what the Bot is -// working on (Active). Built only from sources the host already keeps, plus the -// operator's loose-ends register, which this module reads and never writes. -// Git, CI and merges reach none of these sources, so no text filter is needed. +// Operator tasks: per Bot, what the user asked it to do (Operator), what it works on for +// anyone else (Active), and what waits on the user (Unresolved). Built only from sources +// the host already keeps, plus the operator's loose-ends register, which this module +// reads and never writes. Git, CI and merges reach none of these sources, so no text +// filter is needed. import { readFileSync, statSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' @@ -86,7 +87,7 @@ export function install(rt) { const view = {} const entryOf = (botId) => { if (botId === undefined || state.bots?.[botId] === undefined) return undefined - return (view[botId] ??= { active: [], unresolved: [] }) + return (view[botId] ??= { operator: [], active: [], unresolved: [] }) } const add = (botId, list, item) => { entryOf(botId)?.[list].push(item) } @@ -115,20 +116,57 @@ export function install(rt) { add(byName.get(owner), 'unresolved', { kind: 'decision', key: `decision:${id}`, id, ...rest }) } + // The operator's ask, directly or through a manager Bot (turns.js marks it): what + // the Bot works on for the user goes in Operator Tasks, the rest in Active Tasks. + const runningWork = new Map() for (const [botId, work] of Object.entries(rt.workView?.() ?? {})) { - add(botId, 'active', { kind: 'turn', key: 'turn', at: work.since, ...(work.tool ? { tool: work.tool } : {}), ...(work.target ? { target: work.target } : {}), ...(work.said ? { text: clip(work.said, 160) } : {}), ...(work.switching ? { switching: true } : {}), ...(work.roomId ? { roomId: work.roomId } : {}) }) + const operator = work.origin === 'operator' + if (work.work !== undefined) runningWork.set(botId, work.work) + const text = operator ? work.ask ?? work.said : work.said + add(botId, operator ? 'operator' : 'active', { + kind: operator ? (work.originFrom ? 'relay' : 'ask') : 'turn', + key: 'turn', + at: work.since, + ...(text ? { text: clip(text, 160) } : {}), + ...(operator && work.originFrom ? { via: work.originFrom } : {}), + ...(work.tool ? { tool: work.tool } : {}), + ...(work.target ? { target: work.target } : {}), + ...(work.switching ? { switching: true } : {}), + ...(work.roomId ? { roomId: work.roomId } : {}), + }) } for (const [id, work] of Object.entries(state.works ?? {})) { if (work?.to === undefined || work.from === undefined || work.to === work.from) continue - add(work.to, 'active', { kind: 'order', key: `order:${id}`, from: work.from, at: work.at }) + // The running turn already says this job is being done, so the order stands back. + if (runningWork.get(work.to) === id) continue + add(work.to, work.origin === 'operator' ? 'operator' : 'active', { kind: 'order', key: `order:${id}`, from: work.from, at: work.at }) + } + // A Bot waiting on another Bot for the user's job is still the user's job: the open + // work it holds from or for the operator says so, and when that work began. + const operatorWorkOf = (botId) => { + let at + let operator = false + for (const work of Object.values(state.works ?? {})) { + if (work?.origin !== 'operator' || (work.to !== botId && work.from !== botId)) continue + operator = true + if (work.at !== undefined && (at === undefined || work.at < at)) at = work.at + } + return { operator, at } } for (const [botId, waiting] of Object.entries(rt.waitingView?.() ?? {})) { - add(botId, 'active', { kind: 'waiting', key: 'waiting', bots: waiting.bots ?? [], rooms: waiting.rooms ?? [] }) + const own = operatorWorkOf(botId) + add(botId, own.operator ? 'operator' : 'active', { + kind: 'waiting', + key: 'waiting', + bots: waiting.bots ?? [], + rooms: waiting.rooms ?? [], + ...(own.operator && own.at !== undefined ? { at: own.at } : {}), + }) } // Oldest first: what has waited longest sits on top. for (const entry of Object.values(view)) { - for (const list of [entry.active, entry.unresolved]) list.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity)) + for (const list of [entry.operator, entry.active, entry.unresolved]) list.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity)) } return view } diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js index d8d06ce020..f4a31a1a7e 100644 --- a/ds-bot/src/host/turns.js +++ b/ds-bot/src/host/turns.js @@ -387,6 +387,19 @@ export function install(rt) { entry.info = info // The trigger's text without its header line, for the card gate (card-gate.js). entry.infoText = typeof text === 'string' ? text : undefined + // Where the job came from. A relay carries `origin` on its message source, so the + // operator's ask passes on hop by hop; the work it is for keeps it across a restart + // (handoffs.js), so a turn claimed for that work is the operator's too. + const askedFor = rt.workOf?.(info) + const operator = info?.origin === 'operator' + || (askedFor !== undefined && state.works?.[askedFor]?.origin === 'operator') + || (info?.work !== undefined && state.works?.[info.work]?.origin === 'operator') + if (operator && !rt.groupOwners.has(sessionId)) { + entry.origin = 'operator' + entry.originAt ??= Date.now() + if (typeof info.senderName === 'string') entry.originFrom = info.senderName + if (typeof text === 'string' && text.trim() !== '') entry.askText = text + } // A turn that was stopped for a part switch brings its joined requests along. if (Array.isArray(info.joined) && info.joined.length > 0) { entry.joined = info.joined.filter(item => item?.info !== undefined && item.info !== null) @@ -452,7 +465,18 @@ export function install(rt) { const owner = rt.groupOwners.get(id) const botId = owner?.botId ?? rt.chatOwners.get(id) if (botId === undefined || (owner !== undefined && bots[botId] !== undefined)) continue - bots[botId] = { since: entry.since, ...doingOf(entry), ...(owner ? { roomId: owner.roomId } : {}) } + const forWork = rt.workOf?.(entry.info) + bots[botId] = { + since: entry.since, + ...doingOf(entry), + ...(owner ? { roomId: owner.roomId } : {}), + ...(forWork !== undefined ? { work: forWork } : {}), + ...(entry.origin === 'operator' ? { + origin: 'operator', + ...(entry.originFrom ? { originFrom: entry.originFrom } : {}), + ...(entry.askText ? { ask: entry.askText } : {}), + } : {}), + } } for (const [id] of subagentsByParent) { const sub = subagentDoingOf(id) @@ -473,6 +497,20 @@ export function install(rt) { return bots } + // The running turn a Bot is doing for the operator, when it has one: its own chat + // first, else a group Session it speaks in. delivery.js and handoffs.js read it, so a + // relay carries the origin on and the work a job waits for keeps it. + const operatorTurnOf = (botId) => { + if (botId === undefined) return undefined + const own = live.get(rt.chatOf(botId)) + if (own?.turn !== undefined && own.origin === 'operator') return own + for (const [id, entry] of live) { + if (entry.turn === undefined || entry.origin !== 'operator') continue + if (rt.groupOwners.get(id)?.botId === botId) return entry + } + return undefined + } + // Per Session, when its running turn began. const turnsView = () => Object.fromEntries([...live] .filter(([, entry]) => entry.turn !== undefined && entry.since !== undefined) @@ -689,6 +727,12 @@ export function install(rt) { entry.toolCount = carry.toolCount ?? 0 entry.opened = true entry.carried = true + // A steer cut carries the job's origin too: the fresh turn goes on with the + // same work, so it is the same Operator Task. + entry.origin = carry.origin + entry.originFrom = carry.originFrom + entry.askText = carry.askText + entry.originAt = carry.originAt if (carry.info !== undefined) claimTrigger(id, entry, carry.info) entry.joined = carry.joined // A request the carry displaced as this turn's trigger keeps its deferred @@ -724,6 +768,17 @@ export function install(rt) { // Bot relay that lands inside it may claim: the first message of a turn // still claims it as today, a later one only joins it. const opened = entry.opened === true + // The operator's own line, or a task they scheduled, starts Operator work. A group + // post is queued as a room message and belongs to the group, so group work stays + // in Active Tasks. A message sent while the turn runs keeps the origin on the + // entry, so the wait until its own turn answers it still shows as the operator's. + if (!rt.groupOwners.has(id) && (source?.kind === 'user' || source?.kind === 'schedule')) { + entry.origin = 'operator' + entry.originAt ??= Date.now() + delete entry.originFrom + const asked = textOf(event.data.content) + if (asked.trim() !== '') entry.askText = asked + } if (entry.turn !== undefined && !bare(source) && (source?.kind === 'user' || source?.kind === REPLY_KIND || source?.kind === 'schedule' || source?.kind === SOURCE_KIND)) { entry.opened = true @@ -862,6 +917,13 @@ export function install(rt) { if (event.data?.target === 'next-step' && entry.turn !== undefined && (event.data.inserted ?? []).some(message => message?.source?.kind === 'user')) { entry.steeredAt = event.time ?? Date.now() + // The user's line steered the running turn: it is the operator's work, and no + // longer a manager's relay. + if (!rt.groupOwners.has(id)) { + entry.origin = 'operator' + entry.originAt ??= Date.now() + delete entry.originFrom + } } break case 'assistant/message': { @@ -887,7 +949,7 @@ export function install(rt) { const steerCut = cut !== undefined && event.data?.reason?.kind === 'aborted' && event.data.reason.reason?.kind === 'hook' && event.data.reason.reason.reason === STEER_CUT if (steerCut) { - entry.carry = { info: entry.info, joined: entry.joined ?? [], later: entry.later ?? [], texts: entry.texts.slice(0, cut.texts), shown: entry.shown, answers: entry.answers, toolCount: entry.toolCount ?? 0 } + entry.carry = { info: entry.info, joined: entry.joined ?? [], later: entry.later ?? [], texts: entry.texts.slice(0, cut.texts), shown: entry.shown, answers: entry.answers, toolCount: entry.toolCount ?? 0, origin: entry.origin, originFrom: entry.originFrom, askText: entry.askText, originAt: entry.originAt } } const info = entry.info const turn = entry.turn @@ -902,6 +964,14 @@ export function install(rt) { const switched = entry.switched === true entry.turn = undefined entry.info = undefined + // The turn's reply answers what it was doing, so an Operator Task ends here. A + // job that still waits on another Bot stays listed through its open work + // (handoffs.js), and an ask that is still queued marks the entry again when it + // arrives. + entry.origin = undefined + entry.originFrom = undefined + entry.askText = undefined + entry.originAt = undefined entry.texts = [] entry.shown = 0 entry.step = undefined @@ -1145,5 +1215,5 @@ export function install(rt) { }, 'ds-bot: prompt rejection reasons') } - Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents }) + Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, operatorTurnOf, stopRoomTurn, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents }) } diff --git a/ds-bot/test/operator-tasks.test.js b/ds-bot/test/operator-tasks.test.js index 4b247a34cb..6ac45e9d2a 100644 --- a/ds-bot/test/operator-tasks.test.js +++ b/ds-bot/test/operator-tasks.test.js @@ -3,7 +3,12 @@ import assert from 'node:assert/strict' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { runInNewContext } from 'node:vm' +import { build } from 'esbuild' import { install, openDecisions } from '../src/host/operator-tasks.js' +import { install as installTurns } from '../src/host/turns.js' +import { SOURCE_KIND } from '../src/host/constants.js' const line = record => JSON.stringify(record) @@ -76,6 +81,7 @@ test('operatorTasksView sorts each source onto the right Bot and list', () => { assert.equal(view.coder.unresolved.find(item => item.kind === 'question').roomId, 'room-1') // Active: the running turn and the order from Igor; the Bot's own and group work are not orders. + assert.deepEqual(view.coder.operator, []) assert.deepEqual(view.coder.active.map(item => item.kind), ['order', 'turn']) assert.equal(view.coder.active[0].from, 'chief') assert.deepEqual(view.chief.active.map(item => item.kind), ['waiting']) @@ -88,6 +94,105 @@ test('operatorTasksView sorts each source onto the right Bot and list', () => { } }) +test('work the user started is in Operator Tasks, and the order for it stands back', () => { + const rt = fakeRuntime({ + looseEnds: false, + state: { + works: { + w1: { from: 'chief', to: 'coder', origin: 'operator', open: [], results: [], at: 90 }, + w2: { from: 'chief', to: 'coder', open: [], results: [], at: 80 }, + }, + }, + work: { + coder: { since: 100, tool: 'pwsh', work: 'w1', origin: 'operator', originFrom: 'Igor', ask: 'Add the panel' }, + chief: { since: 110, said: 'Reading the repo' }, + }, + waiting: { coder: { bots: ['chief'], rooms: [], for: ['chief'] } }, + }) + const view = rt.operatorTasksView() + + // The relayed turn and the wait for the Bot it handed on are the operator's job. + assert.deepEqual(view.coder.operator.map(item => item.kind), ['waiting', 'relay']) + assert.equal(view.coder.operator[1].via, 'Igor') + assert.equal(view.coder.operator[1].text, 'Add the panel') + assert.equal(view.coder.operator[1].at, 100) + + // The order the turn is already doing stands back; the one the user did not start stays Active. + assert.deepEqual(view.coder.active.map(item => item.kind), ['order']) + assert.equal(view.coder.active[0].from, 'chief') + assert.deepEqual(view.chief.active.map(item => item.kind), ['turn']) + + // No job appears in both lists. + const keys = list => new Set(list.map(item => item.key)) + const inOperator = keys(view.coder.operator) + assert.equal([...keys(view.coder.active)].some(key => inOperator.has(key)), false) +}) + +// The host records the origin on the running turn (turns.js), so the details panel and +// the header badge can tell the user's own asks apart from the team's work. +function turnHost({ works = {} } = {}) { + let listener + const rt = { + ctx: { on: (name, fn) => { if (name === 'session/event') listener = fn } }, + config: { looseEnds: false }, + state: { exchangeTurns: {}, questions: {}, views: {}, secretRequests: {}, works, bots: { b: { id: 'b', name: 'Writer' } } }, + isBotSession: () => true, + roomOf: () => undefined, + groupOwners: new Map(), + chatOwners: new Map([['b', 'b']]), + botOf: id => ({ b: { id: 'b', name: 'Writer' } })[id], + selfOf: id => id, + chatOf: id => id, + save: async () => {}, + deliver: async () => {}, + userWrote() {}, + userAnswered() {}, + noteFailure() {}, + warn() {}, + switchJobs: () => [], + approvalsView: () => [], + } + installTurns(rt) + install(rt) + let seq = 0 + const emit = (id, type, data) => listener({ id }, { type, seq: ++seq, data }) + return { rt, emit } +} + +const textBlock = text => [{ type: 'text', text }] +const relay = (extra = {}) => ({ kind: SOURCE_KIND, form: 'relay', role: 'request', senderName: 'Igor', exchangeId: 'e1', ...extra }) + +test('a turn the user starts is an Operator Task until its reply', () => { + const { rt, emit } = turnHost() + emit('b', 'turn/start', { turn: 1 }) + emit('b', 'user/message', { content: textBlock('Add the panel'), source: { kind: 'user' } }) + assert.equal(rt.workView().b.origin, 'operator') + assert.equal(rt.workView().b.ask, 'Add the panel') + assert.equal(rt.operatorTasksView().b.operator[0].kind, 'ask') + + // The reply ends the job: it leaves Operator Tasks. + emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } }) + assert.equal(rt.workView().b, undefined) + assert.deepEqual(rt.operatorTasksView().b?.operator ?? [], []) +}) + +test('a relayed turn carries the operator origin, and a plain team job does not', () => { + const { rt, emit } = turnHost() + emit('b', 'turn/start', { turn: 1 }) + emit('b', 'user/message', { content: textBlock('[Message from Igor]\nrun the checks'), source: relay({ origin: 'operator' }) }) + assert.equal(rt.workView().b.origin, 'operator') + assert.equal(rt.workView().b.originFrom, 'Igor') + assert.equal(rt.operatorTasksView().b.operator[0].kind, 'relay') + emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } }) + + // The same request without the origin is the team's own work. + emit('b', 'turn/start', { turn: 2 }) + emit('b', 'user/message', { content: textBlock('[Message from Igor]\nlook at this'), source: relay({ exchangeId: 'e2' }) }) + assert.equal(rt.workView().b.origin, undefined) + assert.deepEqual(rt.operatorTasksView().b?.operator ?? [], []) + assert.equal(rt.operatorTasksView().b.active[0].kind, 'turn') +}) + test('a missing register leaves the decisions empty and the rest intact', () => { const rt = fakeRuntime({ looseEnds: join(tmpdir(), 'ds-bot-no-such-register.jsonl'), state: { questions: { 'chief-chat': { id: 'q1', question: 'Go?', askedAt: 1 } } } }) const view = rt.operatorTasksView() @@ -143,3 +248,80 @@ test('the state answer carries operator tasks live, and a closed decision leaves const later = await call('state', { since: first.revision, models: first.modelsKey, live: first.liveKey }) assert.deepEqual(later.operatorTasks, {}) }) + +// The details panel and the header badge the user sees: the three sections in order, +// and the "A · U" pair with the operator count in the accent colour and the waiting +// count in the danger colour. The client module is browser code, so it is bundled here. +const operatorTasksBundle = await build({ + entryPoints: [fileURLToPath(new URL('../src/client/operator-tasks.js', import.meta.url))], + bundle: true, format: 'cjs', platform: 'node', write: false, + external: ['react'], +}) +const operatorTasksModule = { exports: {} } +runInNewContext(operatorTasksBundle.outputFiles[0].text, { + module: operatorTasksModule, exports: operatorTasksModule.exports, URL, setTimeout, clearTimeout, + require: (name) => { + if (name === 'react') { + return { createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity).filter(child => child !== null && child !== undefined && child !== false) }) } + } + throw new Error(`no platform module ${name}`) + }, +}) +const { OperatorTasks, OperatorBadge, OPERATOR_TASKS_CSS } = operatorTasksModule.exports + +// The element tree the component builds, with function components run. +const tree = node => (node === null || node === undefined || typeof node !== 'object' ? node + : Array.isArray(node) ? node.map(tree) + : typeof node.type === 'function' ? tree(node.type(node.props)) + : { type: node.type, props: node.props, children: (node.children ?? []).map(tree) }) +const textOf = node => (node === null || node === undefined || node === false ? '' + : typeof node === 'string' ? node + : Array.isArray(node) ? node.map(textOf).join('') + : (node.children ?? []).map(textOf).join('')) +const findAll = (node, want) => (node === null || node === undefined || typeof node !== 'object' ? [] + : Array.isArray(node) ? node.flatMap(child => findAll(child, want)) + : [...(want(node) ? [node] : []), ...(node.children ?? []).flatMap(child => findAll(child, want))]) + +const roster = { + byId: { igor: { id: 'igor', name: 'Igor' } }, + roomsById: {}, + operatorTasks: { + coder: { + operator: [{ kind: 'relay', key: 'turn', at: 10, text: 'Add the panel', via: 'Igor' }], + active: [{ kind: 'order', key: 'order:w2', at: 5, from: 'igor' }], + unresolved: [{ kind: 'question', key: 'question:q1', at: 20, text: 'Which option?', sessionId: 'coder' }], + }, + }, +} + +test('the panel shows Operator Tasks above Active and Unresolved', () => { + const panel = tree(OperatorTasks({ bot: { id: 'coder' }, roster })) + const titles = findAll(panel, node => node.props?.className === 'bt-section-title').map(textOf) + // The bundle comes from another realm, so compare plain values. + assert.deepEqual(JSON.parse(JSON.stringify(titles)), ['Operator Tasks · 1', 'Active Tasks · 1', 'Unresolved Tasks · 1']) + + // The user's job, in the words of the Bot that passed it on. + const lines = findAll(panel, node => node.props?.className === 'bt-ops-label').map(textOf) + assert.equal(lines[0], 'Relayed by Igor') + const texts = findAll(panel, node => node.props?.className === 'bt-ops-text').map(textOf) + assert.equal(texts[0], 'Add the panel') +}) + +test('the header badge shows the two counts, A accent and U danger', () => { + const badge = tree(OperatorBadge({ operator: 3, unresolved: 5 })) + assert.equal(textOf(badge), '3·5') + const [yours, dot, waiting] = badge.children + assert.equal(yours.props.className, 'bt-pill-yours') + assert.equal(waiting.props.className, 'bt-pill-waiting') + assert.equal(dot.props.className, 'bt-pill-dot') + // The two colours are the accent and the danger colour the pill always used. + assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-yours\{color:var\(--bt-accent\)\}/) + assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-waiting\{color:var\(--bt-danger\)\}/) + assert.equal(badge.props.title, '3 from you, 5 waiting on you') +}) + +test('the badge caps each count and shows nothing when both are 0', () => { + assert.equal(textOf(tree(OperatorBadge({ operator: 140, unresolved: 0 }))), '99+·0') + assert.equal(textOf(tree(OperatorBadge({ operator: 0, unresolved: 250 }))), '0·99+') + assert.equal(OperatorBadge({ operator: 0, unresolved: 0 }), null) +})