diff --git a/ds-bot/README.md b/ds-bot/README.md
index af95ade6c8..6a0fb886cc 100644
--- a/ds-bot/README.md
+++ b/ds-bot/README.md
@@ -11,7 +11,7 @@ Tested with dsh `0.2.2-rc.1` (Web and Desktop).
- **Long-lived Bots**: each Bot is a dsh Session in the "DS Bot" workspace, with its own name, role, instructions and model.
- **Working folders**: a Bot can work in a folder you choose instead of the team workspace, and a group chat can set one folder for all its members there. Pick it in the Bot's settings or details panel or in the group's settings, or ask a Bot (`update_bot`, `update_group`). After a change, the chat goes on in a fresh part that starts in the new folder. When a Bot sets a folder outside the team workspace, or adds a Bot to a group that works in one, it asks for your approval if those Bots can only write in their folder. Folders that hold dsh data (`$DSH_HOME`, the team's data) are refused. The team workspace itself moves in Settings > General > Locations; Bots and groups that work there go on in a fresh part in the new folder, and the old folder keeps its files.
- **Permission presets**: each Bot runs with its own dsh permission preset (Read only, Workspace or Full access), set in its details panel. A group chat can run all its members with one preset there, in place of their own: turn on **Same for every member** under Permissions in the group's settings. Only you set permissions; Bots cannot change them.
-- **Bots work together**: `message_bot` sends a message to another Bot, `create_bot` and `update_bot` add and set up Bots (including a profile photo from a local image file or a data URL), and `ask_user` asks you a question without blocking the other Bots. `show_view` draws a card in a Bot's own chat — text, metrics, tables, charts, inputs with local formulas, progress, choices, confirmations, short forms and sandboxed HTML; an interactive card waits for your answer. `/side` (or **Side chat** in the panel's `···` menu) opens a side chat in the right panel that answers from a snapshot of the Bot's chat without running tools or interrupting its work. A Bot can also be marked **Private** in its settings: other Bots cannot read its working folder, memory or chat, and its outbound sharing needs your approval.
+- **Bots work together**: `message_bot` sends a message to another Bot, `create_bot` and `update_bot` add and set up Bots (including a profile photo from a local image file or a data URL), and `ask_user` asks you a question without blocking the other Bots. A question card closes when the Bot finishes a later turn you can see that asks nothing, or when a Main Bot withdraws it with `void_question`; a turn that only answers another Bot leaves it open, and a late click on a closed card is refused. `show_view` draws a card in a Bot's own chat: text, metrics, tables, charts, inputs with local formulas, progress, choices, confirmations, short forms and sandboxed HTML; an interactive card waits for your answer. `/side` (or **Side chat** in the panel's `···` menu) opens a side chat in the right panel that answers from a snapshot of the Bot's chat without running tools or interrupting its work. A Bot can also be marked **Private** in its settings: other Bots cannot read its working folder, memory or chat, and its outbound sharing needs your approval.
- **Group chats**: in admin-first mode the admin answers first and calls in other members with `@Name`; in all-members mode members speak in order. Members `@`-mentioned in the same message start work in parallel. Type `@` to pick a member from a list, or use **+ → Reference a chat** to attach another Bot's chat as context. A member with nothing new to add stays quiet (`[PASS]`). For multi-stage work, the admin can align on and run a group **Goal** (`group_goal`), assigning tasks per stage and checking evidence before advancing. Each member has its own hidden Session per group, so a group never reads a Bot's private chat.
- **Roles and permissions**:
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 7def82cff0..bb023f3ed7 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -47,6 +47,7 @@ var ZH = {
Working: "进行中",
"Waiting for your answer": "等你回答",
"Waiting for {names}": "等 {names} 交回",
+ "Waiting for a teammate": "等队友交回工作",
"Unread activity": "有未读",
"Not read yet": "未读",
Search: "搜索",
@@ -1307,6 +1308,7 @@ var ZH = {
"Add files": "添加文件",
"Reference a chat": "引用对话",
"Chat with {name}": "与 {name} 的对话",
+ Brainstorm: "头脑风暴",
"Scheduled task": "定时任务",
"Send to": "发给",
"Scheduled task: {text}": "定时任务:{text}",
@@ -1360,6 +1362,39 @@ 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": "你的要求",
+ "The ask is not recorded": "没有记录你的要求",
+ "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}」里",
+ "Question card": "问题卡片",
+ "Answer card": "待回答的卡片",
+ "A card waiting for your answer": "一张等你回答的卡片",
+ "Key request": "密钥请求",
+ "Tool approval": "工具审批",
+ "Decision {id}": "决定 {id}",
+ "due {date}": "截止 {date}",
+ "not shown on a card yet": "还没有以卡片形式出现",
+ "Working now": "正在工作",
+ "Moving on to a fresh part": "正在换到新的对话段",
+ "Running {tool} on {target}": "正在对 {target} 运行 {tool}",
+ "Running {tool}": "正在运行 {tool}",
+ Order: "委托",
+ "From {name}": "来自 {name}",
+ "Waiting on": "在等",
"Automation tasks are off in DSH": "DSH 的「自动化任务」没有打开",
"No such Bot": "没有这个 Bot",
"No such Bot or group chat": "没有这个 Bot 或群聊",
@@ -1738,14 +1773,14 @@ var markNoted = (error) => {
if (error !== null && typeof error === "object") noted.add(error);
return error;
};
-function noteClientError(where, error) {
+function noteClientError(where2, error) {
if (error !== null && typeof error === "object") {
if (noted.has(error)) return;
noted.add(error);
}
const message = String(error?.message ?? error ?? "error").slice(0, 300);
const code = typeof error?.code === "string" ? error.code : void 0;
- const text = `${where}: ${message}`;
+ const text = `${where2}: ${message}`;
const now = Date.now();
const last = entries.at(-1);
if (last && last.text === text && now - last.time < REPEAT_MS) {
@@ -1756,7 +1791,7 @@ function noteClientError(where, error) {
entries.push({ time: now, level: "error", text, ...code ? { code } : {} });
if (entries.length > MAX) entries.splice(0, entries.length - MAX);
}
-var quietly = (where) => (error) => noteClientError(where, error);
+var quietly = (where2) => (error) => noteClientError(where2, error);
var clearClientErrors = () => {
entries.length = 0;
};
@@ -1951,8 +1986,8 @@ function bodyOf(def, paint, flat = false) {
return "";
}
}
-var eyeMarkup = ([cx, cy, w, h61, tilt]) => ``;
-var happyEyeMarkup = ([cx, cy, w, h61, tilt]) => ``;
+var eyeMarkup = ([cx, cy, w, h62, tilt]) => ``;
+var happyEyeMarkup = ([cx, cy, w, h62, tilt]) => ``;
var maskBox = (size) => `maskUnits="userSpaceOnUse" x="${-size}" y="${-size}" width="${size * 3}" height="${size * 3}"`;
var holes = (def, eyes) => `${eyes}`;
var MASK_ID = "%MASK%";
@@ -2007,8 +2042,15 @@ function createSource(initial) {
}
};
}
-var EMPTY_ROSTER = { revision: -1, mainBotId: null, mainBotIds: [], bots: [], rooms: [], agents: [], sections: [], exchangeTurns: {}, questions: {}, btwCards: {}, sideChats: {}, learning: {}, secrets: [], capabilities: [], capabilityStatuses: {}, secretRequests: {}, models: [], defaultModel: null, modelsKey: null, prefs: {}, byId: {}, roomsById: {}, agentsById: {}, agentOf: {}, ready: false };
+var EMPTY_ROSTER = { revision: -1, mainBotId: null, mainBotIds: [], bots: [], rooms: [], agents: [], sections: [], exchangeTurns: {}, questions: {}, btwCards: {}, sideChats: {}, learning: {}, secrets: [], capabilities: [], capabilityStatuses: {}, operatorTasks: {}, secretRequests: {}, models: [], defaultModel: null, modelsKey: null, prefs: {}, byId: {}, roomsById: {}, agentsById: {}, agentOf: {}, ready: false };
var isMainOf = (roster, id) => id !== void 0 && (roster.mainBotIds ?? []).includes(id);
+function ownedSessionIds(roster) {
+ return [...new Set([
+ ...roster.bots.flatMap((bot) => [bot.id, bot.sessionId ?? bot.id, ...bot.parts ?? []]),
+ ...roster.rooms.flatMap((room2) => [room2.id, room2.sessionId ?? room2.id, ...room2.ownParts ?? [], ...room2.parts ?? [], ...Object.values(room2.sessions ?? {})]),
+ ...Object.keys(roster.agentOf ?? {})
+ ].filter((id) => typeof id === "string" && id !== ""))];
+}
function indexRoster(value) {
const byId = {};
for (const bot of value.bots) {
@@ -2026,6 +2068,13 @@ function indexRoster(value) {
}
return { ...value, agents: value.agents ?? [], sections: value.sections ?? [], byId, roomsById, agentsById, agentOf, ready: true };
}
+var SESSIONS_EVENT = "ds-bot:sessions";
+var legacySessionsEvent = "dsh-bot:sessions";
+function publishOwnedSessions(win, ids) {
+ win.__dshBotSessions = ids;
+ win.dispatchEvent(new CustomEvent(SESSIONS_EVENT, { detail: ids }));
+ win.dispatchEvent(new CustomEvent(legacySessionsEvent, { detail: ids }));
+}
function isAgentSession(roster, cache, sessionId) {
if (sessionId === void 0 || sessionId === null || sessionId === "") return false;
if (roster.ready) return roster.agentOf[sessionId] !== void 0;
@@ -2280,8 +2329,8 @@ function teamActions({ call: call2, after, partFor, roster, ui: ui2, live, cards
diagnosticsClear: () => call2("diagnostics-clear"),
repoStars: () => call2("repo-stars"),
// A failed action away from any form (a menu, the palette) shows as a toast.
- reportError: (error, where = "action") => {
- noteClientError(where, error);
+ reportError: (error, where2 = "action") => {
+ noteClientError(where2, error);
ui2.set((state) => ({ ...state, toast: { text: error?.message ?? String(error), token: Date.now() } }));
},
dismissToast: (token) => ui2.set((state) => state.toast && (token === void 0 || state.toast.token === token) ? { ...state, toast: null } : state),
@@ -2393,7 +2442,10 @@ var shellTokens = ({ light, dark }) => ({
"--dsw-specific-input-major": { light: light.bg, dark: dark.sidebar },
"--dsw-alias-label-primary": { light: light.text, dark: dark.text },
"--dsw-alias-label-secondary": { light: rgba(light.text, 0.74), dark: rgba(dark.text, 0.74) },
- "--dsw-alias-label-tertiary": { light: rgba(light.text, 0.6), dark: rgba(dark.text, 0.6) }
+ "--dsw-alias-label-tertiary": { light: rgba(light.text, 0.6), dark: rgba(dark.text, 0.6) },
+ // The shell's idle dot (pending to-dos, idle sessions) is neutral-300, 1.4:1 on the
+ // light page; graphics need 3:1. Same step as label-tertiary keeps it in each theme.
+ "--dsw-alias-state-idle-primary": { light: rgba(light.text, 0.6), dark: rgba(dark.text, 0.6) }
});
var customThemes = {};
var registry = createSource(0);
@@ -2777,12 +2829,12 @@ function liveSprings(apply2) {
const dt = Math.min(0.5, Math.max(1e-3, (now - last) / 1e3));
last = now;
const steps = Math.ceil(dt * 240);
- const h61 = dt / steps;
+ const h62 = dt / steps;
let moving = false;
for (const [key, value] of values) {
for (let index = 0; index < steps; index += 1) {
- value.v += (-value.k * (value.x - value.to) - value.c * value.v) * h61;
- value.x += value.v * h61;
+ value.v += (-value.k * (value.x - value.to) - value.c * value.v) * h62;
+ value.x += value.v * h62;
}
if (Math.abs(value.x - value.to) < 0.05 && Math.abs(value.v) < 1) {
value.x = value.to;
@@ -2972,134 +3024,13 @@ function stepMenuFocus(menu, event, trigger) {
return true;
}
-// src/client/storage.js
-var STORAGE = {
- unread: "ds-bot:unread",
- reactions: "ds-bot:reactions",
- seen: "ds-bot:seen",
- prefs: "ds-bot:prefs",
- surface: "ds-bot:surface",
- agentSessions: "ds-bot:agent-sessions",
- browserWidth: "ds-bot:browser-width",
- sidebar: "ds-bot:sidebar",
- browsers: "ds-bot.browser.v2"
-};
-var LEGACY_PREFIXES = ["dsh-bot:", "dsh-bot-team:"];
-var LEGACY_BROWSER_KEYS = ["ds-bot.browser.v1", "dsh-bot.browser.v1"];
-var LEGACY_THEMES = { grok: "mono" };
-function legacyKeys(key) {
- if (key === STORAGE.browsers) return LEGACY_BROWSER_KEYS;
- const name = key.slice(key.indexOf(":") + 1);
- return LEGACY_PREFIXES.map((prefix) => `${prefix}${name}`);
-}
-var migrateBrowsers = (storage) => {
- if (storage.getItem(STORAGE.browsers) !== null) {
- for (const key of LEGACY_BROWSER_KEYS) storage.removeItem(key);
- return;
- }
- for (const key of LEGACY_BROWSER_KEYS) {
- try {
- const value = storage.getItem(key);
- if (value === null) continue;
- const previous = JSON.parse(value) ?? {};
- const tabs = Object.fromEntries(Object.entries(previous).filter(([, page]) => page && typeof page === "object").map(([botId, page]) => {
- const tab = { id: `v1-${botId}`, url: page.url ?? "", title: page.title ?? "" };
- return [botId, { tabs: [tab], active: tab.id }];
- }));
- storage.setItem(STORAGE.browsers, JSON.stringify(tabs));
- for (const earlier of LEGACY_BROWSER_KEYS) storage.removeItem(earlier);
- return;
- } catch {
- }
- }
-};
-function migrateStorage(storage = globalThis.localStorage) {
- for (const key of Object.values(STORAGE)) {
- if (key === STORAGE.browsers) continue;
- for (const legacy of legacyKeys(key)) {
- try {
- const value = storage.getItem(legacy);
- if (value !== null && storage.getItem(key) === null) storage.setItem(key, value);
- storage.removeItem(legacy);
- } catch {
- }
- }
- }
- try {
- migrateBrowsers(storage);
- } catch {
- }
- try {
- const prefs = JSON.parse(storage.getItem(STORAGE.prefs) ?? "null");
- if (prefs && Object.hasOwn(LEGACY_THEMES, prefs.theme ?? "")) {
- storage.setItem(STORAGE.prefs, JSON.stringify({ ...prefs, theme: LEGACY_THEMES[prefs.theme] }));
- }
- } catch {
- }
-}
-
-// src/client/frame-layout.js
-var MIN_CHAT = 420;
-var RAIL_WIDTH = 88;
-var PANEL_MIN = { details: 320, browser: 360, side: 320 };
-var DSH_NARROW = 1024;
-var SIDEBAR_MIN = 264;
-var SIDEBAR_MAX = 420;
-var FALLBACK_SIDEBAR_WIDTH = 280;
-var RAIL_SNAP = (RAIL_WIDTH + SIDEBAR_MIN) / 2;
-function frameLayout({ viewport, sidebarWidth, pref, drawer = false, panel = null }) {
- const fits = pref === "open" && viewport >= sidebarWidth + MIN_CHAT;
- let left = pref === "hidden" ? "hidden" : fits ? "open" : drawer && pref === "open" ? "drawer" : "rail";
- let occupied = left === "open" ? sidebarWidth : left === "hidden" ? 0 : RAIL_WIDTH;
- let panelState = "none";
- if (panel !== null) {
- const need = (PANEL_MIN[panel.view] ?? PANEL_MIN.details) + MIN_CHAT;
- if (occupied + need <= viewport) panelState = "shown";
- else if (panel.yielded === true) {
- if (left !== "hidden") {
- left = "rail";
- occupied = RAIL_WIDTH;
- }
- panelState = occupied + need <= viewport ? "shown" : "overlay";
- } else panelState = "folded";
- }
- return { left, panel: panelState, column: occupied, room: Math.max(0, viewport - occupied) };
-}
-function dragColumn(x, viewport) {
- if (x < RAIL_SNAP) return { left: "rail", width: RAIL_WIDTH };
- const docks = viewport >= SIDEBAR_MIN + MIN_CHAT;
- const high = docks ? Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, viewport - MIN_CHAT)) : SIDEBAR_MAX;
- return { left: docks ? "open" : "drawer", width: Math.round(Math.max(SIDEBAR_MIN, Math.min(x, high))) };
-}
-var toggledPref = (pref, shown) => pref === "hidden" ? shown : "hidden";
-var RESIZE_SETTLE_MS = 500;
-var userSidebarToggle = ({ before, after, requested = false, sinceResize = Infinity }) => before.collapsed !== after.collapsed && !requested && sinceResize >= RESIZE_SETTLE_MS && before.viewport < DSH_NARROW === after.viewport < DSH_NARROW;
-var PREFS = ["open", "rail", "hidden"];
-function readSidebar(storage = globalThis.localStorage) {
- try {
- const saved = JSON.parse(storage.getItem(STORAGE.sidebar) ?? "null");
- const pref = PREFS.includes(saved?.pref) ? saved.pref : "open";
- const shown = saved?.shown === "rail" ? "rail" : "open";
- const width = Number.isFinite(saved?.width) ? Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, saved.width)) : FALLBACK_SIDEBAR_WIDTH;
- return { pref, shown, width };
- } catch {
- return { pref: "open", shown: "open", width: FALLBACK_SIDEBAR_WIDTH };
- }
-}
-function writeSidebar(value, storage = globalThis.localStorage) {
- try {
- storage.setItem(STORAGE.sidebar, JSON.stringify(value));
- } catch {
- }
-}
-
// src/client/styles.js
var SHELL_CSS = `
-body{--bt-im-telegram:#229ed9;--bt-im-weixin:#07c160;--bt-im-feishu:#3370ff;--bt-im-dingtalk:#1e88e5;--bt-im-wecom:#0082ef;--bt-im-qq:#e03e3e;--bt-im-discord:#5865f2;--bt-im-slack:#4a154b;--bt-im-mark-ink:#ffffff;--bt-qr-paper:#ffffff;--bt-qr-ink:#141414;--bt-ink:#141414;--bt-danger:#e02135;--bt-ink-2:rgba(20,20,20,.6);--bt-ink-3:rgba(20,20,20,.36);--bt-bubble:#eeeeee;--bt-sidebar:#f7f7f7;--bt-main:#fcfcfc;--bt-line:rgba(20,20,20,.08);--bt-line-2:rgba(20,20,20,.15);--bt-line-weak:rgba(20,20,20,.1);--bt-hover:rgba(119,119,119,.09);--bt-active:rgba(119,119,119,.17);--bt-card:#ffffff;--bt-accent:#4d6bfe;--bt-green:#00c972;--bt-star:#ff9800;--bt-user:#070707;--bt-user-ink:#fcfcfc;--bt-tag-bg:rgba(20,20,20,.06);--bt-tag-ink:rgba(20,20,20,.56);--bt-knob:#ffffff;--bt-glass-bg:color-mix(in srgb,var(--bt-main) 78%,transparent);--bt-glass-border:rgba(255,255,255,.72);--bt-glass-rim:rgba(20,20,20,.09);--bt-glass-shadow:0 8px 28px -6px rgba(0,0,0,.08),0 2px 6px -1px rgba(0,0,0,.04),inset 0 1px 0 rgba(255,255,255,.82);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 14%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 14%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 24%,transparent);-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:100%;--bt-font:var(--dsw-font-family,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}
+body{--bt-im-telegram:#229ed9;--bt-im-weixin:#07c160;--bt-im-feishu:#3370ff;--bt-im-dingtalk:#1e88e5;--bt-im-wecom:#0082ef;--bt-im-qq:#e03e3e;--bt-im-discord:#5865f2;--bt-im-slack:#4a154b;--bt-im-mark-ink:#ffffff;--bt-qr-paper:#ffffff;--bt-qr-ink:#141414;--bt-ink:#141414;--bt-danger:#e02135;--bt-ink-2:rgba(20,20,20,.6);--bt-ink-3:rgba(20,20,20,.36);--bt-bubble:#eeeeee;--bt-sidebar:#f7f7f7;--bt-main:#fcfcfc;--bt-line:rgba(20,20,20,.08);--bt-line-2:rgba(20,20,20,.15);--bt-line-weak:rgba(20,20,20,.1);--bt-hover:rgba(119,119,119,.09);--bt-active:rgba(119,119,119,.17);--bt-card:#ffffff;--bt-accent:#4d6bfe;--bt-green:#00c972;--bt-star:#ff9800;--bt-waiting:#5b6472;--bt-user:#070707;--bt-user-ink:#fcfcfc;--bt-tag-bg:rgba(20,20,20,.06);--bt-tag-ink:rgba(20,20,20,.56);--bt-knob:#ffffff;--bt-glass-bg:color-mix(in srgb,var(--bt-main) 78%,transparent);--bt-glass-border:rgba(255,255,255,.72);--bt-glass-rim:rgba(20,20,20,.09);--bt-glass-shadow:0 8px 28px -6px rgba(0,0,0,.08),0 2px 6px -1px rgba(0,0,0,.04),inset 0 1px 0 rgba(255,255,255,.82);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 14%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 14%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 24%,transparent);-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:100%;--bt-font:var(--dsw-font-family,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}
/* iOS waits out a double-tap zoom on buttons; the plugin's own controls never zoom. */
:is(.bt-tool,.bt-uaction,.bt-menu button,.bt-menu-item,.bt-icon-btn,.bt-round,.bt-pill,.bt-account,.bt-set-row,.bt-settings-item,.bt-react-strip button,.bt-palette-row,.bt-palette-clear,.bt-tab,.bt-ptab,.bt-ptab-x,.bt-bcard-x,.bt-plus,.bt-q-btn,.bt-q-x,.bt-x,.bt-nc-send,.bt-send,.bt-soft,.bt-mini,.bt-side-send,.bt-shape,.bt-swatch,.bt-color,.bt-newchat,.bt-task-day,.bt-task-remove,.bt-fb-btn){touch-action:manipulation}
:is(.bt-round,.bt-you,.bt-account,.bt-color,.bt-color span,.bt-swatch,.bt-icon-btn,.bt-avatar-trigger,.bt-avatar-pencil,.bt-plus,.bt-mic,.bt-voice){corner-shape:round}
-body[data-ds-dark-theme]{--bt-im-telegram:#2ea8de;--bt-im-weixin:#17c96a;--bt-im-feishu:#4d84ff;--bt-im-dingtalk:#3d99ed;--bt-im-wecom:#2898f2;--bt-im-qq:#e85555;--bt-im-discord:#6e7bf2;--bt-im-slack:#7c4380;--bt-im-mark-ink:#ffffff;--bt-ink:#f2f2f2;--bt-ink-2:rgba(242,242,242,.6);--bt-ink-3:rgba(242,242,242,.36);--bt-bubble:#262626;--bt-sidebar:#1b1b1b;--bt-main:#141414;--bt-line:rgba(255,255,255,.08);--bt-line-2:rgba(255,255,255,.15);--bt-line-weak:rgba(255,255,255,.1);--bt-hover:rgba(160,160,160,.12);--bt-active:rgba(160,160,160,.2);--bt-card:#1f1f1f;--bt-user:#f2f2f2;--bt-user-ink:#141414;--bt-tag-bg:rgba(255,255,255,.09);--bt-tag-ink:rgba(242,242,242,.62);--bt-glass-bg:color-mix(in srgb,var(--bt-main) 74%,transparent);--bt-glass-border:rgba(255,255,255,.13);--bt-glass-rim:rgba(255,255,255,.11);--bt-glass-shadow:0 12px 32px -6px rgba(0,0,0,.42),0 2px 8px -1px rgba(0,0,0,.28),inset 0 1px 0 rgba(255,255,255,.12);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 18%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 18%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 28%,transparent)}
+body[data-ds-dark-theme]{--bt-im-telegram:#2ea8de;--bt-im-weixin:#17c96a;--bt-im-feishu:#4d84ff;--bt-im-dingtalk:#3d99ed;--bt-im-wecom:#2898f2;--bt-im-qq:#e85555;--bt-im-discord:#6e7bf2;--bt-im-slack:#7c4380;--bt-im-mark-ink:#ffffff;--bt-ink:#f2f2f2;--bt-ink-2:rgba(242,242,242,.6);--bt-ink-3:rgba(242,242,242,.36);--bt-bubble:#262626;--bt-sidebar:#1b1b1b;--bt-main:#141414;--bt-line:rgba(255,255,255,.08);--bt-line-2:rgba(255,255,255,.15);--bt-line-weak:rgba(255,255,255,.1);--bt-hover:rgba(160,160,160,.12);--bt-active:rgba(160,160,160,.2);--bt-card:#1f1f1f;--bt-user:#f2f2f2;--bt-user-ink:#141414;--bt-tag-bg:rgba(255,255,255,.09);--bt-tag-ink:rgba(242,242,242,.62);--bt-waiting:#9aa3b2;--bt-glass-bg:color-mix(in srgb,var(--bt-main) 74%,transparent);--bt-glass-border:rgba(255,255,255,.13);--bt-glass-rim:rgba(255,255,255,.11);--bt-glass-shadow:0 12px 32px -6px rgba(0,0,0,.42),0 2px 8px -1px rgba(0,0,0,.28),inset 0 1px 0 rgba(255,255,255,.12);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 18%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 18%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 28%,transparent)}
${Object.entries(INKS).map(([name, [light]]) => `body{--bt-ink-${name}:${light}}`).join("")}
${Object.entries(INKS).map(([name, [, dark]]) => `body[data-ds-dark-theme]{--bt-ink-${name}:${dark}}`).join("")}
.bt-mark{display:inline-block;flex:none;position:relative;line-height:0}
@@ -3190,6 +3121,14 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default}
.bt-badge-main path{fill:var(--bt-star);stroke:var(--bt-sidebar);stroke-width:2.6;stroke-linejoin:round;paint-order:stroke}
.bt-badge-alert{background:color-mix(in srgb,var(--bt-accent) 78%,var(--bt-sidebar));color:var(--bt-accent-ink,#fff);font-size:8.5px;line-height:12px;font-weight:600;font-family:var(--bt-font)}
.bt-badge-working{background:color-mix(in srgb,var(--bt-green) 82%,var(--bt-sidebar));width:8px;height:8px;right:1px;bottom:1px}
+/* local: waiting-mark. A Bot whose own turn is over but whose handed-on work has not
+ come back cannot wear the working badge, and a Main Bot's star takes the one badge
+ slot, so the wait gets a slot of its own opposite the star. */
+.bt-badge-waiting{right:auto;left:0;background:color-mix(in srgb,var(--bt-waiting) 90%,var(--bt-sidebar))}
+.bt-badge-waiting svg{width:9px;height:9px}
+.bt-badge-waiting :is(circle,path){fill:none;stroke:var(--bt-sidebar);stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
+body:not([data-bt-motion=quiet]) .bt-badge-waiting{animation:bt-wait-tick 2.4s ease-in-out infinite}
+@keyframes bt-wait-tick{0%,100%{opacity:1}50%{opacity:.4}}
.bt-cluster{position:relative;display:inline-block;flex:none;line-height:0}
.bt-cluster>*{position:absolute}
.bt-cluster-more,.bt-cluster-you{display:inline-flex;align-items:center;justify-content:center;border-radius:50%;background:var(--bt-active);color:var(--bt-ink-3);font-family:var(--bt-font);font-weight:500;line-height:1;font-variant-numeric:tabular-nums}
@@ -3212,6 +3151,10 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default}
.bt-side:not(.bt-rail)>.bt-list::-webkit-scrollbar-track{background:transparent}
.bt-side:not(.bt-rail)>.bt-list::-webkit-scrollbar-thumb{border:4px solid transparent;border-radius:6px;background:color-mix(in srgb,var(--bt-ink) 16%,transparent) padding-box}
.bt-side:not(.bt-rail)>.bt-list:hover::-webkit-scrollbar-thumb{background-color:color-mix(in srgb,var(--bt-ink) 30%,transparent)}
+/* local: sidebar-coexistence. Every Main Bot tiles, two to a row. */
+.bt-tile-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));justify-items:center;align-self:stretch;padding:8px 0 2px}
+.bt-tile-grid>.bt-tile-wrap{padding:6px 0}
+.bt-tile-grid .bt-tile{width:100%;max-width:112px}
.bt-tile-wrap{display:flex;justify-content:center;padding:20px 0 15px}
.bt-tile{display:flex;flex-direction:column;align-items:center;gap:4px;width:95px;padding:6px 8px 4px;border-radius:16px;border:0;background:transparent;color:var(--bt-ink);cursor:pointer;font-family:inherit;transition:background-color .12s ease}
.bt-tile:hover{background:var(--bt-hover)}
@@ -3239,6 +3182,10 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default}
.bt-leftcol{position:fixed;left:0;top:0;bottom:0;z-index:25;display:flex;--bt-lc-clear:var(--dsh-frame-top-clearance,var(--dsh-windows-titlebar-height,0px));background:var(--bt-leftcol-fill,var(--bt-sidebar));border-right:.5px solid var(--bt-line);box-sizing:border-box;padding:calc(var(--bt-lc-clear) + 6px) 12px 6px;color:var(--bt-ink);font-family:var(--bt-font)}
html[data-windows-titlebar] .bt-leftcol,html[data-platform=darwin] .bt-leftcol{border-right:none}
.bt-leftcol{animation:bt-leftcol-in ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing}}
+/* local: sidebar-coexistence. The column sits in the shell's own sidebar, which owns
+ the place, the fill, the width, the resize and the slide. */
+.bt-leftcol{position:relative;left:auto;top:auto;bottom:auto;z-index:auto;flex-direction:column;min-height:0;--bt-lc-clear:0px;background:none;border-right:none;padding:0;animation:none}
+.bt-leftcol>.bt-leftcol-grip{display:none}
.bt-leftcol[data-leaving]{transform:translateX(-100%);transition:transform ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing};pointer-events:none}
@keyframes bt-leftcol-in{from{transform:translateX(-100%)}}
@media (prefers-reduced-motion:reduce){.bt-leftcol{animation:none}.bt-leftcol[data-leaving],[class*="_centerCol"]{transition:none}}
@@ -3246,11 +3193,8 @@ html[data-windows-titlebar] .bt-leftcol,html[data-platform=darwin] .bt-leftcol{b
.bt-leftcol-grip:hover,.bt-leftcol-grip:active{background:linear-gradient(to right,transparent 3px,var(--bt-line-2) 3px,var(--bt-line-2) 5px,transparent 5px)}
/* The shell's collapsed sidebar keeps no track in the Bot view, so a hidden
column leaves nothing behind (the shell's right column, when open, keeps its
- own geometry). Narrow hosts may put the conversation in the first track,
- so only the desktop layout can force that track to zero. */
-@media (min-width:${DSH_NARROW}px){
-[class*="_frame"][data-sidebar-collapsed][data-rightbar-collapsed]:has(>[class*="_sidebarCol"]){grid-template-columns:0px minmax(0,1fr) 0px!important}
-}
+ own geometry). Our own collapse of it lands without the shell's slide. */
+/* local: sidebar-coexistence. The shell keeps its own tracks while the Bot list sits inside them. */
html[data-bt-collapsing] [class*="_frame"]:has(>[class*="_sidebarCol"]){transition:none!important}
.bt-leftcol[data-left=drawer]{background:var(--bt-sidebar);box-shadow:8px 0 24px rgba(0,0,0,.14)}
.bt-leftcol>.bt-side{width:100%}
@@ -4216,7 +4160,9 @@ body[data-bt-goal] [class*="_scroll"]:has(> [class*="_column"]){padding-top:calc
}
@keyframes bt-fade-in{from{opacity:0}to{opacity:1}}
@keyframes bt-fade-out{from{opacity:1}to{opacity:0}}
-[data-composer-card]{display:flex!important;flex-direction:row!important;flex-wrap:wrap!important;align-items:center!important;gap:0!important;min-height:44px!important;border-radius:22px!important;padding:7.5px!important;box-sizing:border-box;background:var(--bt-glass-bg)!important;-webkit-backdrop-filter:blur(20px) saturate(180%)!important;backdrop-filter:blur(20px) saturate(180%)!important;border:.5px solid var(--bt-glass-rim)!important;box-shadow:var(--bt-glass-shadow),0 0 0 1px rgba(228,228,228,.04)!important;transition:border-color .15s ease,background-color .15s ease,${spring(SPRING_SHAPE, "border-radius")}!important}
+[data-composer-card]{display:flex!important;flex-direction:row!important;flex-wrap:wrap!important;align-items:center!important;gap:0!important;min-height:44px!important;border-radius:22px!important;padding:7.5px!important;box-sizing:border-box;position:relative!important;isolation:isolate!important;background:transparent!important;-webkit-backdrop-filter:none!important;backdrop-filter:none!important;border:.5px solid var(--bt-glass-rim)!important;box-shadow:var(--bt-glass-shadow),0 0 0 1px rgba(228,228,228,.04)!important;transition:border-color .15s ease,${spring(SPRING_SHAPE, "border-radius")}!important}
+/* The glass sits on a layer behind the contents: a backdrop-filter on the card itself would make it a backdrop root, and the Harness menus that open inside it (the slash and skills picker, model, permission) would lose their own blur and show the chat sharp through a 58% fill. */
+[data-composer-card]::before{content:"";position:absolute;inset:0;z-index:-1;border-radius:inherit;pointer-events:none;background:var(--bt-glass-bg);-webkit-backdrop-filter:blur(20px) saturate(180%);backdrop-filter:blur(20px) saturate(180%)}
[data-composer-card]:hover,[data-composer-card]:focus-within{border-color:color-mix(in srgb,var(--bt-ink) 30%,transparent)!important}
[data-composer-card]:has(> [data-slot="conversation.input.attachments"] *),[data-composer-card]:has([data-composer-input] br + *),[data-composer-card]:has([data-composer-input] > :nth-child(2)){border-radius:18px!important}
[class*="_root"]:has(> [data-composer-card]){padding:0 11px 13px 16px!important}
@@ -4612,6 +4558,14 @@ function MainStar() {
(0, import_react2.createElement)("path", { d: "M10 2.4l2.29 5.04 5.51.63-4.09 3.74 1.11 5.42L10 14.5l-4.82 2.73 1.11-5.42L2.2 8.07l5.51-.63z" })
);
}
+function WaitIcon({ size = 9 }) {
+ return (0, import_react2.createElement)(
+ "svg",
+ { viewBox: "0 0 10 10", width: size, height: size, "aria-hidden": true },
+ (0, import_react2.createElement)("circle", { cx: 5, cy: 5, r: 3.45 }),
+ (0, import_react2.createElement)("path", { d: "M5 2.75v2.4l1.75 .95" })
+ );
+}
function useSettled(state) {
const prev = (0, import_react2.useRef)(state);
const [settled, setSettled] = (0, import_react2.useState)(false);
@@ -4640,7 +4594,8 @@ function BotAvatar({ bot, size, state = "idle", main, admin, badge = true, live
badgeKind === "working" ? (0, import_react2.createElement)("span", { className: "bt-badge bt-badge-working", "aria-label": t("Working"), role: "img" }) : null,
badgeKind === "alert" ? (0, import_react2.createElement)("span", { className: "bt-badge bt-badge-alert", "aria-label": t("Waiting for your answer"), role: "img" }, "?") : null,
badgeKind === "admin" ? (0, import_react2.createElement)("span", { className: "bt-badge bt-badge-admin", "aria-label": t("Admin"), role: "img" }, (0, import_react2.createElement)(StarIcon)) : null,
- badgeKind === "main" ? (0, import_react2.createElement)("span", { className: "bt-badge bt-badge-main", "aria-label": t("Main Bot"), role: "img" }, (0, import_react2.createElement)(MainStar)) : null
+ badgeKind === "main" ? (0, import_react2.createElement)("span", { className: "bt-badge bt-badge-main", "aria-label": t("Main Bot"), role: "img" }, (0, import_react2.createElement)(MainStar)) : null,
+ badge && state === "waiting" ? (0, import_react2.createElement)("span", { className: "bt-badge bt-badge-waiting", role: "img", "aria-label": t("Waiting for a teammate") }, (0, import_react2.createElement)(WaitIcon)) : null
);
}
function clusterSeats(count, frame) {
@@ -4778,6 +4733,7 @@ var ConnectorIcon = lineIcon(["M7 10a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z", "M18
var SignOutIcon = lineIcon(["M8.5 17H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h2.5", "M10 10h6.5", "M13.5 7l3 3-3 3"]);
var SignInIcon = lineIcon(["M11.5 3H14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-2.5", "M3.5 10H10", "M7 7l3 3-3 3"]);
var PaperclipIcon = lineIcon(["M15.5 9.5l-5.6 5.6a3.4 3.4 0 0 1-4.8-4.8l6.1-6.1a2.25 2.25 0 0 1 3.2 3.2l-6 6a1.1 1.1 0 0 1-1.6-1.6l5.5-5.5"]);
+var BulbIcon = lineIcon(["M7.5 14.5h5", "M8.25 17h3.5", "M7.5 12.5a5 5 0 1 1 5 0v2h-5z"]);
var ClockIcon = lineIcon(["M10 3.5a6.5 6.5 0 1 1 0 13 6.5 6.5 0 0 1 0-13z", "M10 6.5V10l2.5 1.5"]);
var GearIcon = lineIcon(["M10 7.4a2.6 2.6 0 1 1 0 5.2 2.6 2.6 0 0 1 0-5.2z", "M7.85 4.4l.29-1.87a7.7 7.7 0 0 1 3.72 0l.29 1.87a6 6 0 0 1 1.63.94l1.76-.69a7.7 7.7 0 0 1 1.86 3.23l-1.47 1.18a6 6 0 0 1 0 1.88l1.47 1.18a7.7 7.7 0 0 1-1.86 3.23l-1.76-.69a6 6 0 0 1-1.63.94l-.29 1.87a7.7 7.7 0 0 1-3.72 0l-.29-1.87a6 6 0 0 1-1.63-.94l-1.76.69a7.7 7.7 0 0 1-1.86-3.23l1.47-1.18a6 6 0 0 1 0-1.88L2.6 7.88a7.7 7.7 0 0 1 1.86-3.23l1.76.69a6 6 0 0 1 1.63-.94z"]);
var PinIcon = lineIcon(["M12.5 3l4.5 4.5-3 1.5-2.5 2.5.5 3.5-1.5 1.5L7 13 3.5 16.5", "M7 13l-3.5-3.5L5 8l3.5.5L11 6l1.5-3"]);
@@ -6240,11 +6196,11 @@ function ComputerIndicator({ useComputer, useRoster, actions }) {
const waiting = Object.entries(live.bots ?? {}).filter(([, entry]) => entry.waitingFor === "user-idle");
if (leases.length === 0 && waiting.length === 0) return null;
const botOf = (id) => roster.byId[id];
- const nameOf2 = (id) => botOf(id)?.name ?? t("a Bot");
+ const nameOf3 = (id) => botOf(id)?.name ?? t("a Bot");
const avatarOf = (id) => {
const look = lookOf(botOf(id));
if (typeof look.image === "string" && look.image.startsWith("data:image/")) return (0, import_react11.createElement)("img", { className: "bt-cbar-ava", src: look.image, alt: "" });
- return (0, import_react11.createElement)("span", { className: "bt-cbar-ava bt-cbar-ava-dot", style: { background: look.color } }, String(nameOf2(id)).slice(0, 1));
+ return (0, import_react11.createElement)("span", { className: "bt-cbar-ava bt-cbar-ava-dot", style: { background: look.color } }, String(nameOf3(id)).slice(0, 1));
};
const entries2 = [
...leases.map((entry) => ({ key: `l:${entry.botId}`, botId: entry.botId, waiting: false, app: entry.kind === "foreground" ? t("In the foreground") : entry.appName })),
@@ -6263,7 +6219,7 @@ function ComputerIndicator({ useComputer, useRoster, actions }) {
(0, import_react11.createElement)(
"span",
{ className: "bt-cbar-text" },
- (0, import_react11.createElement)("b", { className: "bt-cbar-name" }, nameOf2(entry.botId)),
+ (0, import_react11.createElement)("b", { className: "bt-cbar-name" }, nameOf3(entry.botId)),
(0, import_react11.createElement)("i", { className: "bt-cbar-app" }, entry.app)
),
entry.waiting ? (0, import_react11.createElement)("button", { type: "button", className: "bt-cbar-go", onClick: () => void actions.computerAllowForeground(entry.botId) }, t("Let it continue")) : (0, import_react11.createElement)(
@@ -15152,6 +15108,127 @@ function showsDshRow(dsh, app) {
return dsh.kind === "app" && APP_OFFER.has(app?.phase) && sameVersion(app.version, dsh.verified);
}
+// src/client/storage.js
+var STORAGE = {
+ unread: "ds-bot:unread",
+ reactions: "ds-bot:reactions",
+ seen: "ds-bot:seen",
+ prefs: "ds-bot:prefs",
+ surface: "ds-bot:surface",
+ agentSessions: "ds-bot:agent-sessions",
+ browserWidth: "ds-bot:browser-width",
+ sidebar: "ds-bot:sidebar",
+ browsers: "ds-bot.browser.v2"
+};
+var LEGACY_PREFIXES = ["dsh-bot:", "dsh-bot-team:"];
+var LEGACY_BROWSER_KEYS = ["ds-bot.browser.v1", "dsh-bot.browser.v1"];
+var LEGACY_THEMES = { grok: "mono" };
+function legacyKeys(key) {
+ if (key === STORAGE.browsers) return LEGACY_BROWSER_KEYS;
+ const name = key.slice(key.indexOf(":") + 1);
+ return LEGACY_PREFIXES.map((prefix) => `${prefix}${name}`);
+}
+var migrateBrowsers = (storage) => {
+ if (storage.getItem(STORAGE.browsers) !== null) {
+ for (const key of LEGACY_BROWSER_KEYS) storage.removeItem(key);
+ return;
+ }
+ for (const key of LEGACY_BROWSER_KEYS) {
+ try {
+ const value = storage.getItem(key);
+ if (value === null) continue;
+ const previous = JSON.parse(value) ?? {};
+ const tabs = Object.fromEntries(Object.entries(previous).filter(([, page]) => page && typeof page === "object").map(([botId, page]) => {
+ const tab = { id: `v1-${botId}`, url: page.url ?? "", title: page.title ?? "" };
+ return [botId, { tabs: [tab], active: tab.id }];
+ }));
+ storage.setItem(STORAGE.browsers, JSON.stringify(tabs));
+ for (const earlier of LEGACY_BROWSER_KEYS) storage.removeItem(earlier);
+ return;
+ } catch {
+ }
+ }
+};
+function migrateStorage(storage = globalThis.localStorage) {
+ for (const key of Object.values(STORAGE)) {
+ if (key === STORAGE.browsers) continue;
+ for (const legacy of legacyKeys(key)) {
+ try {
+ const value = storage.getItem(legacy);
+ if (value !== null && storage.getItem(key) === null) storage.setItem(key, value);
+ storage.removeItem(legacy);
+ } catch {
+ }
+ }
+ }
+ try {
+ migrateBrowsers(storage);
+ } catch {
+ }
+ try {
+ const prefs = JSON.parse(storage.getItem(STORAGE.prefs) ?? "null");
+ if (prefs && Object.hasOwn(LEGACY_THEMES, prefs.theme ?? "")) {
+ storage.setItem(STORAGE.prefs, JSON.stringify({ ...prefs, theme: LEGACY_THEMES[prefs.theme] }));
+ }
+ } catch {
+ }
+}
+
+// src/client/frame-layout.js
+var MIN_CHAT = 420;
+var RAIL_WIDTH = 88;
+var PANEL_MIN = { details: 320, browser: 360, side: 320 };
+var DSH_NARROW = 1024;
+var SIDEBAR_MIN = 264;
+var SIDEBAR_MAX = 420;
+var FALLBACK_SIDEBAR_WIDTH = 280;
+var RAIL_SNAP = (RAIL_WIDTH + SIDEBAR_MIN) / 2;
+function frameLayout({ viewport, sidebarWidth, pref, drawer = false, panel = null }) {
+ const fits = pref === "open" && viewport >= sidebarWidth + MIN_CHAT;
+ let left = pref === "hidden" ? "hidden" : fits ? "open" : drawer && pref === "open" ? "drawer" : "rail";
+ let occupied = left === "open" ? sidebarWidth : left === "hidden" ? 0 : RAIL_WIDTH;
+ let panelState = "none";
+ if (panel !== null) {
+ const need = (PANEL_MIN[panel.view] ?? PANEL_MIN.details) + MIN_CHAT;
+ if (occupied + need <= viewport) panelState = "shown";
+ else if (panel.yielded === true) {
+ if (left !== "hidden") {
+ left = "rail";
+ occupied = RAIL_WIDTH;
+ }
+ panelState = occupied + need <= viewport ? "shown" : "overlay";
+ } else panelState = "folded";
+ }
+ return { left, panel: panelState, column: occupied, room: Math.max(0, viewport - occupied) };
+}
+function dragColumn(x, viewport) {
+ if (x < RAIL_SNAP) return { left: "rail", width: RAIL_WIDTH };
+ const docks = viewport >= SIDEBAR_MIN + MIN_CHAT;
+ const high = docks ? Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, viewport - MIN_CHAT)) : SIDEBAR_MAX;
+ return { left: docks ? "open" : "drawer", width: Math.round(Math.max(SIDEBAR_MIN, Math.min(x, high))) };
+}
+var toggledPref = (pref, shown) => pref === "hidden" ? shown : "hidden";
+var RESIZE_SETTLE_MS = 500;
+var userSidebarToggle = ({ before, after, requested = false, sinceResize = Infinity }) => before.collapsed !== after.collapsed && !requested && sinceResize >= RESIZE_SETTLE_MS && before.viewport < DSH_NARROW === after.viewport < DSH_NARROW;
+var PREFS = ["open", "rail", "hidden"];
+function readSidebar(storage = globalThis.localStorage) {
+ try {
+ const saved = JSON.parse(storage.getItem(STORAGE.sidebar) ?? "null");
+ const pref = PREFS.includes(saved?.pref) ? saved.pref : "open";
+ const shown = saved?.shown === "rail" ? "rail" : "open";
+ const width = Number.isFinite(saved?.width) ? Math.max(SIDEBAR_MIN, Math.min(SIDEBAR_MAX, saved.width)) : FALLBACK_SIDEBAR_WIDTH;
+ return { pref, shown, width };
+ } catch {
+ return { pref: "open", shown: "open", width: FALLBACK_SIDEBAR_WIDTH };
+ }
+}
+function writeSidebar(value, storage = globalThis.localStorage) {
+ try {
+ storage.setItem(STORAGE.sidebar, JSON.stringify(value));
+ } catch {
+ }
+}
+
// src/client/frame-watch.js
var sidebarTrackWidth = () => typeof document === "undefined" ? null : document.querySelector('[class*="_sidebarCol"]')?.getBoundingClientRect().width ?? null;
var dshCollapsed = () => {
@@ -15286,7 +15363,7 @@ function BotRow({ bot, roster, actions, useSessions, useSessionStatus, useSessio
const unread = useSessionStatus((map) => map.get(part)?.completionUnread === true || map.get(part)?.pendingInteraction !== void 0) || marked && !active;
useMarkedUnread(id, active, marked, actions);
const main = isMainOf(roster, id);
- const tile = roster.mainBotId === id;
+ const tile = main || roster.mainBotId === id;
const approval = useApproval(useWork, (entry) => entry.botId === id);
const alert = roster.questions?.[part] !== void 0 || approval;
const doing = useActivity((map) => map[id]);
@@ -15773,13 +15850,13 @@ function useListGlide(listRef, layout, key) {
tops.current = { layout, map: next };
}, [layout, key]);
}
-function LeftColumn({ mode, width, onGrip, leaving, children }) {
- return (0, import_react_dom5.createPortal)((0, import_react34.createElement)(
+function LeftColumn({ mode, onGrip, leaving, children }) {
+ return (0, import_react34.createElement)(
"div",
- { className: "bt-leftcol", "data-left": mode, "data-leaving": leaving || void 0, "aria-hidden": leaving || void 0, style: { width: `${width}px` } },
+ { className: "bt-leftcol", "data-left": mode, "data-leaving": leaving || void 0, "aria-hidden": leaving || void 0 },
children,
(0, import_react34.createElement)("div", { className: "bt-leftcol-grip", role: "separator", "aria-orientation": "vertical", "aria-label": t("Resize sidebar"), title: t("Resize sidebar"), onPointerDown: onGrip })
- ), document.body);
+ );
}
function TitleToggle({ hidden, onToggle }) {
if (typeof document === "undefined") return null;
@@ -15809,6 +15886,7 @@ function TeamSidebar(props) {
const panelYield = useUi((value) => value.panelYield === true);
const bootFailed = useUi((value) => value.bootFailed === true);
const renameSection = useUi((value) => value.renameSection);
+ const accountSeated = useUi((value) => value.accountSeated === true);
props.useRegistry((value) => value);
const frameSnap = props.useFrame ? props.useFrame((value) => value) : { viewport: typeof window === "undefined" ? 0 : window.innerWidth, sidebarWidth: FALLBACK_SIDEBAR_WIDTH, collapsedWidth: 0 };
const pref = props.useSidebarPref ? props.useSidebarPref((value) => value) : "open";
@@ -15832,7 +15910,7 @@ function TeamSidebar(props) {
const order = (0, import_react34.useMemo)(() => {
const stamps = JSON.parse(updated);
const entries2 = [
- ...roster.bots.filter((bot) => bot.id !== roster.mainBotId).map((bot) => ({ kind: "bot", item: bot, at: stamps[currentPart(bot)] ?? bot.createdAt })),
+ ...roster.bots.filter((bot) => !isMainOf(roster, bot.id) && bot.id !== roster.mainBotId).map((bot) => ({ kind: "bot", item: bot, at: stamps[currentPart(bot)] ?? bot.createdAt })),
...roster.rooms.map((room2) => ({ kind: "room", item: room2, at: stamps[room2.id] ?? room2.createdAt })),
// The Agent sorts by its most recent Session, falling back to when it was added.
...(roster.agents ?? []).map((agent) => ({ kind: "agent", item: agent, at: Math.max(0, ...agent.sessions.map((id) => stamps[id] ?? 0)) || agent.createdAt }))
@@ -15846,6 +15924,7 @@ function TeamSidebar(props) {
[order, sectionSet]
);
const main = roster.byId[roster.mainBotId];
+ const tileBots = [main, ...(roster.mainBotIds ?? []).map((id) => roster.byId[id])].filter((bot, index, all) => bot !== void 0 && all.findIndex((other) => other?.id === bot.id) === index);
const glideKey = (0, import_react34.useMemo)(
() => `${sections.map((s) => `${s.id}:${s.collapsed ? 1 : 0}`).join(",")}|${order.map((entry) => `${entry.item.id}:${entry.item.sectionId ?? ""}`).join(",")}`,
[sections, order]
@@ -15883,11 +15962,10 @@ function TeamSidebar(props) {
}).catch((error) => actions.reportError(error, "section"));
};
const openWidth = drag?.width ?? frameSnap.sidebarWidth;
- const ourWidth = shown === "rail" ? RAIL_WIDTH : openWidth;
const pushed = mode === "open" ? openWidth : mode === "hidden" ? 0 : RAIL_WIDTH;
(0, import_react34.useLayoutEffect)(() => {
if (typeof document === "undefined") return;
- chatRoom.setLeft(Math.max(0, pushed - (frameSnap.collapsedWidth ?? 0)));
+ chatRoom.setLeft(null);
}, [pushed, frameSnap.collapsedWidth]);
(0, import_react34.useEffect)(() => () => {
if (typeof document !== "undefined") chatRoom.setLeft(null);
@@ -16019,7 +16097,6 @@ function TeamSidebar(props) {
if (requested.current) return void 0;
requested.current = true;
quiet(true);
- actions.toggleSidebar();
clearTimeout(requestLapse.current);
requestLapse.current = setTimeout(() => {
requested.current = false;
@@ -16065,7 +16142,7 @@ function TeamSidebar(props) {
event.preventDefault();
actions.openPalette(event.key);
};
- const onToggle = () => actions.toggleLeftHidden?.();
+ const onToggle = () => (actions.toggleSidebar ?? actions.toggleLeftHidden)?.();
const toggleRef = (0, import_react34.useRef)(onToggle);
toggleRef.current = onToggle;
(0, import_react34.useEffect)(() => {
@@ -16097,11 +16174,12 @@ function TeamSidebar(props) {
main ? (0, import_react34.createElement)(BotRow, { ...rowProps, bot: main, marked: markedUnread[main.id] === true }) : roster.ready ? null : (0, import_react34.createElement)("div", { className: "bt-hint" }, bootFailed ? bootHint() : t("Setting up your Main Bot…")),
(0, import_react34.createElement)("span", { className: "bt-rail-sep", "aria-hidden": true })
);
- const foot = wideContent ? (0, import_react34.createElement)("div", { className: "bt-leftcol-foot" }, (0, import_react34.createElement)(AccountLauncher, { seat: false, actions })) : (0, import_react34.createElement)(
+ const seated = accountSeated;
+ const foot = wideContent ? seated ? null : (0, import_react34.createElement)("div", { className: "bt-leftcol-foot" }, (0, import_react34.createElement)(AccountLauncher, { seat: false, actions })) : (0, import_react34.createElement)(
"div",
{ className: "bt-leftcol-foot bt-leftcol-foot-rail" },
(0, import_react34.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("New…"), title: t("New…"), onClick: () => actions.openNewChat("new") }, (0, import_react34.createElement)(PlusIcon)),
- (0, import_react34.createElement)(AccountLauncher, { seat: false, actions })
+ seated ? null : (0, import_react34.createElement)(AccountLauncher, { seat: false, actions })
);
const content = (0, import_react34.createElement)(
"div",
@@ -16123,7 +16201,8 @@ function TeamSidebar(props) {
if (!event.currentTarget.contains(event.relatedTarget)) setDropTarget(null);
}
},
- wideContent ? main ? (0, import_react34.createElement)(BotRow, { ...rowProps, bot: main, marked: markedUnread[main.id] === true }) : roster.ready ? null : (0, import_react34.createElement)("div", { className: "bt-hint" }, bootFailed ? bootHint() : t("Setting up your Main Bot…")) : null,
+ // local: sidebar-coexistence. Every Main Bot tiles in one grid above the sections.
+ wideContent ? tileBots.length > 0 ? (0, import_react34.createElement)("div", { className: "bt-tile-grid" }, tileBots.map((bot) => (0, import_react34.createElement)(BotRow, { key: bot.id, ...rowProps, bot, marked: markedUnread[bot.id] === true }))) : roster.ready ? null : (0, import_react34.createElement)("div", { className: "bt-hint" }, bootFailed ? bootHint() : t("Setting up your Main Bot…")) : null,
sections.length > 0 && wideContent ? (0, import_react34.createElement)("div", {
className: "bt-sec-ungrouped",
"data-dragging": dragId ? "true" : void 0,
@@ -16150,7 +16229,7 @@ function TeamSidebar(props) {
import_react34.Fragment,
null,
(0, import_react34.createElement)(TitleToggle, { hidden: mode === "hidden", onToggle }),
- shown === "hidden" ? null : (0, import_react34.createElement)(LeftColumn, { mode: shown, width: ourWidth, onGrip: startDrag, leaving }, content)
+ shown === "hidden" ? null : (0, import_react34.createElement)(LeftColumn, { mode: shown, onGrip: startDrag, leaving }, content)
);
}
function UpdateButton({ useUpdate, actions }) {
@@ -16520,7 +16599,7 @@ function useLandOnMainBot(roster, useSessions, actions) {
const lastBot = (0, import_react34.useRef)(null);
(0, import_react34.useEffect)(() => {
if (!roster.ready || !roster.mainBotId) return void 0;
- const [id, blank3] = mainView.split("|");
+ const [id] = mainView.split("|");
const bot = id === "" ? void 0 : roster.byId[id];
if (bot !== void 0) {
lastBot.current = { botId: bot.id, sessionId: id };
@@ -16533,7 +16612,7 @@ function useLandOnMainBot(roster, useSessions, actions) {
if ((room2.sessionId ?? room2.id) !== id) actions.openSession(room2.id);
return void 0;
}
- if (id !== "" && ((actions.isAgentSession?.(id) ?? roster.agentOf[id] !== void 0) || blank3 !== "1")) {
+ if (id !== "") {
lastBot.current = null;
return void 0;
}
@@ -22737,16 +22816,135 @@ var SETTINGS_SHELL_CSS = `
.bt-release-line.bt-release-done{border-top-style:solid;color:var(--bt-green);opacity:1}
`;
-// src/client/header.js
+// src/client/operator-tasks.js
var import_react49 = require("react");
-var import_react_dom8 = require("react-dom");
-var GoArrow = () => (0, import_react49.createElement)("svg", { width: 14, height: 14, viewBox: "-12 -12 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true }, (0, import_react49.createElement)("path", { d: "M-7 0H7M2 -5L7 0L2 5" }));
-var MEMORY_NOTICE_MS = 3200;
-var noNews = (select) => select({});
-function useMemoryNotice(ids, useMemoryNews) {
+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 nameOf2 = (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") }) : "";
+function unresolvedLine(item) {
+ switch (item.kind) {
+ case "question":
+ return { label: t("Question card"), text: item.text || t("A card waiting for your answer") };
+ case "view":
+ return { label: t("Answer card"), text: item.text || t("A card waiting for your answer") };
+ case "key":
+ return { label: t("Key request"), text: item.detail ? `${item.text}: ${item.detail}` : item.text };
+ case "approval":
+ return { label: t("Tool approval"), text: item.detail ? `${item.text}: ${item.detail}` : item.text };
+ case "decision":
+ return {
+ label: t("Decision {id}", { id: item.id }),
+ text: item.text,
+ note: [item.due ? t("due {date}", { date: item.due }) : "", item.carded ? "" : t("not shown on a card yet")].filter(Boolean).join(", ")
+ };
+ default:
+ return { label: "", text: item.text ?? "" };
+ }
+}
+var stepOf = (item) => {
+ if (item.switching) return t("Moving on to a fresh part");
+ if (item.tool === void 0) return void 0;
+ return item.target ? t("Running {tool} on {target}", { tool: item.tool, target: item.target }) : t("Running {tool}", { tool: item.tool });
+};
+var doingOf2 = (item) => stepOf(item) ?? item.text ?? t("Working");
+var askOf = (item) => {
+ const line = String(item.text ?? "").split(/\r?\n/).map((part) => part.trim()).find((part) => part !== "");
+ return line ?? t("The ask is not recorded");
+};
+function activeLine(item, roster) {
+ switch (item.kind) {
+ 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: nameOf2(roster, item.from) }) };
+ case "waiting":
+ return { label: t("Waiting on"), text: [...item.bots, ...item.rooms].map((id) => nameOf2(roster, id)).join(", ") };
+ default:
+ return { label: "", text: item.text ?? "" };
+ }
+}
+function operatorLine(item, roster) {
+ switch (item.kind) {
+ case "ask":
+ return { label: t("Your ask"), text: askOf(item), note: stepOf(item) };
+ case "relay":
+ return { label: t("Relayed by {name}", { name: item.via ?? t("a teammate") }), text: askOf(item), note: stepOf(item) };
+ default:
+ return activeLine(item, roster);
+ }
+}
+function TaskList({ title, items, line, roster, empty }) {
+ return (0, import_react49.createElement)(
+ "div",
+ { className: "bt-ops" },
+ (0, import_react49.createElement)("div", { className: "bt-section-title" }, items.length === 0 ? title : t("{title} · {count}", { title, count: items.length })),
+ items.length === 0 ? (0, import_react49.createElement)("div", { className: "bt-ops-empty" }, empty) : (0, import_react49.createElement)("ul", { className: "bt-ops-list" }, items.map((item) => {
+ const shown = line(item, roster);
+ return (0, import_react49.createElement)(
+ "li",
+ { key: item.key, className: "bt-ops-item", "data-kind": item.kind },
+ (0, import_react49.createElement)(
+ "div",
+ { className: "bt-ops-top" },
+ (0, import_react49.createElement)("span", { className: "bt-ops-label" }, shown.label),
+ item.at ? (0, import_react49.createElement)("span", { className: "bt-ops-age", title: new Date(item.at).toLocaleString() }, relativeShort(item.at)) : null
+ ),
+ shown.text ? (0, import_react49.createElement)("div", { className: "bt-ops-text" }, shown.text) : null,
+ shown.note ? (0, import_react49.createElement)("div", { className: "bt-ops-note" }, shown.note) : null
+ );
+ }))
+ );
+}
+function OperatorTasks({ bot, roster }) {
+ const tasks = operatorTasksOf(roster, bot.id);
+ return [
+ (0, import_react49.createElement)(TaskList, { key: "operator", title: t("Operator Tasks"), items: tasks.operator, line: operatorLine, roster, empty: t("Nothing of yours in hand.") }),
+ (0, import_react49.createElement)(TaskList, { key: "active", title: t("Active Tasks"), items: tasks.active, line: activeLine, roster, empty: t("Nothing running right now.") }),
+ (0, import_react49.createElement)(TaskList, { key: "unresolved", title: t("Unresolved Tasks"), items: tasks.unresolved, line: unresolvedLine, roster, empty: t("Nothing waiting on you.") })
+ ];
+}
+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_react49.createElement)(
+ "span",
+ { className: "bt-pill-tasks", title: label, "aria-label": label },
+ (0, import_react49.createElement)("span", { className: "bt-pill-yours" }, capped(yours)),
+ (0, import_react49.createElement)("span", { className: "bt-pill-dot", "aria-hidden": true }, "·"),
+ (0, import_react49.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}
+.bt-ops-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
+.bt-ops-item{padding:6px 8px;border-radius:8px;background:var(--bt-hover);min-width:0}
+.bt-ops-top{display:flex;align-items:baseline;gap:8px}
+.bt-ops-label{flex:1;min-width:0;font-size:12px;line-height:16px;font-weight:600;color:var(--bt-ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.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;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
+var import_react50 = require("react");
+var import_react_dom8 = require("react-dom");
+var GoArrow = () => (0, import_react50.createElement)("svg", { width: 14, height: 14, viewBox: "-12 -12 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true }, (0, import_react50.createElement)("path", { d: "M-7 0H7M2 -5L7 0L2 5" }));
+var MEMORY_NOTICE_MS = 3200;
+var noNews = (select) => select({});
+function useMemoryNotice(ids, useMemoryNews) {
const seen = useMemoryNews((map) => Math.max(0, ...ids.map((id) => map?.[id]?.seen ?? 0)));
- const [shown, setShown] = (0, import_react49.useState)(false);
- (0, import_react49.useEffect)(() => {
+ const [shown, setShown] = (0, import_react50.useState)(false);
+ (0, import_react50.useEffect)(() => {
const left = seen + MEMORY_NOTICE_MS - Date.now();
setShown(seen > 0 && left > 0);
if (seen === 0 || left <= 0) return void 0;
@@ -22756,16 +22954,16 @@ function useMemoryNotice(ids, useMemoryNews) {
return shown;
}
function MemoryNotice({ shown }) {
- const inner = (0, import_react49.useRef)(null);
- const [width, setWidth] = (0, import_react49.useState)(0);
+ const inner = (0, import_react50.useRef)(null);
+ const [width, setWidth] = (0, import_react50.useState)(0);
const label = t("Memory updated");
- (0, import_react49.useLayoutEffect)(() => {
+ (0, import_react50.useLayoutEffect)(() => {
if (shown) setWidth(inner.current?.scrollWidth ?? 0);
}, [label, shown]);
- return (0, import_react49.createElement)(
+ return (0, import_react50.createElement)(
"span",
{ className: "bt-pill-mem", "aria-hidden": true, style: { "--bt-mem-w": `${width}px` } },
- (0, import_react49.createElement)("span", { className: "bt-pill-mem-in", ref: inner }, (0, import_react49.createElement)("span", { className: "bt-pill-mem-ico" }, (0, import_react49.createElement)(MemoryIcon)), label)
+ (0, import_react50.createElement)("span", { className: "bt-pill-mem-in", ref: inner }, (0, import_react50.createElement)("span", { className: "bt-pill-mem-ico" }, (0, import_react50.createElement)(MemoryIcon)), label)
);
}
function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSession, useActivity, useMemoryNews, useTurnClock, useUi, useLive, useWork, useStore, useConversationViews, selectView, actions }) {
@@ -22783,7 +22981,7 @@ function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSe
const first = openingTurn(state[sessionId], firstTurns, hiddenTurns);
return first && !unseenSince(visit, first.start) ? clockLabel(first.start) : "";
});
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
if (opening) document.body.style.setProperty("--bt-first-sep", JSON.stringify(opening));
else document.body.style.removeProperty("--bt-first-sep");
return () => document.body.style.removeProperty("--bt-first-sep");
@@ -22806,17 +23004,17 @@ function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSe
const memoryIds = bot ? [bot.id] : room2 ? [room2.id, ...room2.members] : [];
const notice = useMemoryNotice(memoryIds, useNews);
const changed = useNews((map) => latestMemoryChange(map, memoryIds));
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
document.body.style.setProperty("--bt-placeholder", JSON.stringify(name ? t("Message {name}", { name }) : t("Message")));
}, [name, t("Message")]);
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
document.body.style.setProperty("--bt-steer-unread", JSON.stringify(t("Not read yet")));
}, [t("Not read yet")]);
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
actions.beginVisit(sessionId);
return () => actions.endVisit(sessionId);
}, [sessionId]);
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
if (room2) document.body.dataset.btRoom = "";
else delete document.body.dataset.btRoom;
return () => {
@@ -22825,14 +23023,14 @@ function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSe
}, [Boolean(room2)]);
const memoryNotice = !away && notice && changed !== null && roster.memory !== false;
const showGoal = room2 !== void 0 && !away && (goal !== void 0 || goalCompose);
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
if (showGoal) document.body.dataset.btGoal = "";
else delete document.body.dataset.btGoal;
return () => {
delete document.body.dataset.btGoal;
};
}, [showGoal]);
- const pill = (0, import_react49.createElement)(
+ const pill = (0, import_react50.createElement)(
"button",
{
type: "button",
@@ -22843,29 +23041,30 @@ function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSe
title: away ? name : void 0,
onClick: () => away ? selectView("chat") : memoryNotice ? actions.openMemory(changed) : actions.toggleDetails(sessionId)
},
- bot ? (0, import_react49.createElement)(BotAvatar, { bot, size: 24, state: botState(running, doing, roster.questions?.[currentPart(bot)] !== void 0), badge: false }) : room2 ? (0, import_react49.createElement)(RoomAvatar, { room: room2, roster, size: 24 }) : null,
- goalShown ? (0, import_react49.createElement)(
+ bot ? (0, import_react50.createElement)(BotAvatar, { bot, size: 24, state: botState(running, doing, roster.questions?.[currentPart(bot)] !== void 0), badge: false }) : room2 ? (0, import_react50.createElement)(RoomAvatar, { room: room2, roster, size: 24 }) : null,
+ goalShown ? (0, import_react50.createElement)(
"span",
{ className: "bt-pill-swap" },
- (0, import_react49.createElement)("span", { className: "bt-pill-goal" }, (0, import_react49.createElement)("span", { className: "bt-pill-ico", "aria-hidden": true }, (0, import_react49.createElement)(GoalIcon)), (0, import_react49.createElement)("span", { className: "bt-pill-title" }, view.title)),
- (0, import_react49.createElement)("span", { className: "bt-pill-name" }, name)
- ) : (0, import_react49.createElement)("span", { className: "bt-pill-name" }, away ? t("Back to chat") : bot?.name ?? room2?.name ?? (title || t("New chat")), !away && bot?.engine ? (0, import_react49.createElement)(AgentBadge, { engine: bot.engine }) : null),
- goalShown && view?.number !== void 0 ? (0, import_react49.createElement)("span", { className: "bt-pill-count" }, `${view.number}/${view.count}`) : null,
- (0, import_react49.createElement)(MemoryNotice, { shown: memoryNotice }),
- (0, import_react49.createElement)("span", { className: "bt-pill-go", "aria-hidden": true }, (0, import_react49.createElement)(GoArrow))
+ (0, import_react50.createElement)("span", { className: "bt-pill-goal" }, (0, import_react50.createElement)("span", { className: "bt-pill-ico", "aria-hidden": true }, (0, import_react50.createElement)(GoalIcon)), (0, import_react50.createElement)("span", { className: "bt-pill-title" }, view.title)),
+ (0, import_react50.createElement)("span", { className: "bt-pill-name" }, name)
+ ) : (0, import_react50.createElement)("span", { className: "bt-pill-name" }, away ? t("Back to chat") : bot?.name ?? room2?.name ?? (title || t("New chat")), !away && bot?.engine ? (0, import_react50.createElement)(AgentBadge, { engine: bot.engine }) : null),
+ bot && !away ? (0, import_react50.createElement)(OperatorBadge, { operator: operatorCount(roster, bot.id), unresolved: unresolvedCount(roster, bot.id) }) : null,
+ goalShown && view?.number !== void 0 ? (0, import_react50.createElement)("span", { className: "bt-pill-count" }, `${view.number}/${view.count}`) : null,
+ (0, import_react50.createElement)(MemoryNotice, { shown: memoryNotice }),
+ (0, import_react50.createElement)("span", { className: "bt-pill-go", "aria-hidden": true }, (0, import_react50.createElement)(GoArrow))
);
- return (0, import_react49.createElement)(
+ return (0, import_react50.createElement)(
"div",
{ className: "bt-head" },
- showGoal ? (0, import_react49.createElement)(GoalIsland, { room: room2, goal, view, open: goalOpen, composing: goalCompose, roomWork, roster, actions, pill }) : pill,
- (0, import_react49.createElement)("span", { className: "bt-sr", role: "status" }, memoryNotice ? t("Memory updated") : ""),
- (0, import_react49.createElement)(NewMessagePills, { key: sessionId, sessionId, useSessions, useUi, useTurnClock }),
- (0, import_react49.createElement)(ActivityIndicator, { key: `activity:${sessionId}`, sessionId, useRoster, useSessionStatus, useSession, useLive, useWork, actions })
+ showGoal ? (0, import_react50.createElement)(GoalIsland, { room: room2, goal, view, open: goalOpen, composing: goalCompose, roomWork, roster, actions, pill }) : pill,
+ (0, import_react50.createElement)("span", { className: "bt-sr", role: "status" }, memoryNotice ? t("Memory updated") : ""),
+ (0, import_react50.createElement)(NewMessagePills, { key: sessionId, sessionId, useSessions, useUi, useTurnClock }),
+ (0, import_react50.createElement)(ActivityIndicator, { key: `activity:${sessionId}`, sessionId, useRoster, useSessionStatus, useSession, useLive, useWork, actions })
);
}
function useTranscriptView() {
- const [view, setView] = (0, import_react49.useState)(null);
- (0, import_react49.useEffect)(() => {
+ const [view, setView] = (0, import_react50.useState)(null);
+ (0, import_react50.useEffect)(() => {
let frame = 0;
let watched = null;
const observer = new MutationObserver(() => schedule());
@@ -22934,18 +23133,18 @@ function NewMessagePills({ sessionId, useSessions, useUi, useTurnClock }) {
});
const view = useTranscriptView();
const unpinned = view?.unpinned === true;
- const [release, setRelease] = (0, import_react49.useState)({ base: null, dismissed: false });
- const [above, setAbove] = (0, import_react49.useState)({ seen: false, dismissed: false });
- (0, import_react49.useEffect)(() => {
+ const [release, setRelease] = (0, import_react50.useState)({ base: null, dismissed: false });
+ const [above, setAbove] = (0, import_react50.useState)({ seen: false, dismissed: false });
+ (0, import_react50.useEffect)(() => {
setRelease({ base: unpinned ? replies : null, dismissed: false });
}, [unpinned]);
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
if (view?.divider === "in-view") setAbove((state) => state.seen ? state : { ...state, seen: true });
}, [view?.divider]);
const fresh = release.base === null ? 0 : replies - release.base;
const showDown = unpinned && fresh > 0 && !release.dismissed;
const showUp = view?.divider === "above" && !above.seen && !above.dismissed;
- (0, import_react49.useEffect)(() => {
+ (0, import_react50.useEffect)(() => {
const scroller = document.querySelector("[data-conversation-scroll]");
if (!scroller) return void 0;
scroller.toggleAttribute("data-bt-news", showDown);
@@ -22953,16 +23152,16 @@ function NewMessagePills({ sessionId, useSessions, useUi, useTurnClock }) {
}, [showDown]);
if (!view || !showDown && !showUp) return null;
const label = (count) => count === 1 ? t("1 new message") : count > 0 ? t("{count} new messages", { count }) : t("New messages");
- const pill = (direction, count, style, onJump, onDismiss) => (0, import_react49.createElement)(
+ const pill = (direction, count, style, onJump, onDismiss) => (0, import_react50.createElement)(
"div",
{ className: "bt-news", "data-direction": direction, style },
- (0, import_react49.createElement)(
+ (0, import_react50.createElement)(
"button",
{ type: "button", className: "bt-news-jump", onClick: onJump },
- (0, import_react49.createElement)("span", { className: "bt-news-ico" }, (0, import_react49.createElement)(direction === "up" ? ArrowUpIcon : ArrowDownIcon)),
+ (0, import_react50.createElement)("span", { className: "bt-news-ico" }, (0, import_react50.createElement)(direction === "up" ? ArrowUpIcon : ArrowDownIcon)),
label(count)
),
- (0, import_react49.createElement)("button", {
+ (0, import_react50.createElement)("button", {
type: "button",
className: "bt-news-x",
"aria-label": t("Dismiss new messages"),
@@ -22970,7 +23169,7 @@ function NewMessagePills({ sessionId, useSessions, useUi, useTurnClock }) {
event.stopPropagation();
onDismiss();
}
- }, (0, import_react49.createElement)(CloseIcon))
+ }, (0, import_react50.createElement)(CloseIcon))
);
const toLatest = () => {
const scroller = document.querySelector("[data-conversation-scroll]");
@@ -22980,8 +23179,8 @@ function NewMessagePills({ sessionId, useSessions, useUi, useTurnClock }) {
};
const toDivider = () => document.querySelector("[data-conversation-scroll] .bt-new-sep")?.scrollIntoView({ block: "center", behavior: "smooth" });
return (0, import_react_dom8.createPortal)(
- (0, import_react49.createElement)(
- import_react49.Fragment,
+ (0, import_react50.createElement)(
+ import_react50.Fragment,
null,
showUp ? pill("up", unread, { left: view.center, top: view.top }, toDivider, () => setAbove((state) => ({ ...state, dismissed: true }))) : null,
showDown ? pill("down", fresh, { left: view.center, bottom: view.bottom }, toLatest, () => setRelease((state) => ({ ...state, dismissed: true }))) : null
@@ -23008,19 +23207,28 @@ var steerQueued = async (session) => {
}
};
+// src/client/brainstorm.js
+var BRAINSTORM_TEXT = "brainstorm ";
+var canBrainstorm = (inputActions) => typeof inputActions?.insertText === "function";
+function insertBrainstorm(inputActions) {
+ if (!canBrainstorm(inputActions)) return false;
+ inputActions.insertText(BRAINSTORM_TEXT, inputActions.captureInsertion?.());
+ return true;
+}
+
// src/client/composer.js
-var import_react50 = require("react");
+var import_react51 = require("react");
var import_react_dom9 = require("react-dom");
var speechApi = () => window.SpeechRecognition ?? window.webkitSpeechRecognition;
var keepComposerFocus = (event) => event.preventDefault();
function useDictation(onText) {
- const [listening, setListening] = (0, import_react50.useState)(false);
- const [note, setNote] = (0, import_react50.useState)("");
- const recognition = (0, import_react50.useRef)(null);
- const latest = (0, import_react50.useRef)(onText);
+ const [listening, setListening] = (0, import_react51.useState)(false);
+ const [note, setNote] = (0, import_react51.useState)("");
+ const recognition = (0, import_react51.useRef)(null);
+ const latest = (0, import_react51.useRef)(onText);
latest.current = onText;
- (0, import_react50.useEffect)(() => () => recognition.current?.abort(), []);
- (0, import_react50.useEffect)(() => {
+ (0, import_react51.useEffect)(() => () => recognition.current?.abort(), []);
+ (0, import_react51.useEffect)(() => {
if (!note) return void 0;
const timer = setTimeout(() => setNote(""), 2600);
return () => clearTimeout(timer);
@@ -23070,8 +23278,8 @@ function useDictation(onText) {
}
function ComposerVoice({ sessionId, inputActions, actions, useUi, useRoster }) {
const enterToSend = useRoster((state) => sendsOnEnter(state.prefs));
- const composerRoot = (0, import_react50.useRef)(null);
- (0, import_react50.useEffect)(() => {
+ const composerRoot = (0, import_react51.useRef)(null);
+ (0, import_react51.useEffect)(() => {
const root = composerRoot.current?.closest("[data-composer-card]");
if (enterToSend || !inputActions || !root) return void 0;
const onKey = (event) => insertComposerNewline(event, inputActions);
@@ -23082,7 +23290,7 @@ function ComposerVoice({ sessionId, inputActions, actions, useUi, useRoster }) {
if (final && inputActions) inputActions.insertText(text, inputActions.captureInsertion());
});
const quote = useUi((state) => state.quote?.sessionId === sessionId ? state.quote : null);
- (0, import_react50.useEffect)(() => {
+ (0, import_react51.useEffect)(() => {
if (!quote || !inputActions) return;
actions.clearQuote(quote.token);
const excerpt = quote.text.replace(/\s+/g, " ").trim();
@@ -23100,10 +23308,10 @@ function ComposerVoice({ sessionId, inputActions, actions, useUi, useRoster }) {
}, [quote?.token]);
if (sessionId === void 0) return null;
const pluginMic = actions.speech() !== void 0;
- return (0, import_react50.createElement)(
- import_react50.Fragment,
+ return (0, import_react51.createElement)(
+ import_react51.Fragment,
null,
- pluginMic ? null : (0, import_react50.createElement)("button", {
+ pluginMic ? null : (0, import_react51.createElement)("button", {
type: "button",
className: "bt-mic",
"aria-label": dictation.listening ? t("Stop dictation") : t("Dictate"),
@@ -23111,8 +23319,8 @@ function ComposerVoice({ sessionId, inputActions, actions, useUi, useRoster }) {
title: dictation.listening ? t("Stop dictation") : t("Dictate"),
onMouseDown: keepComposerFocus,
onClick: () => dictation.listening ? dictation.stop() : dictation.start()
- }, (0, import_react50.createElement)(MicIcon)),
- (0, import_react50.createElement)("button", {
+ }, (0, import_react51.createElement)(MicIcon)),
+ (0, import_react51.createElement)("button", {
ref: composerRoot,
type: "button",
className: "bt-voice",
@@ -23120,8 +23328,8 @@ function ComposerVoice({ sessionId, inputActions, actions, useUi, useRoster }) {
title: t("Voice chat"),
onMouseDown: keepComposerFocus,
onClick: () => actions.openVoice(sessionId)
- }, (0, import_react50.createElement)(WaveIcon, { size: 18 })),
- dictation.note ? (0, import_react50.createElement)("span", { className: "bt-mic-note", role: "status" }, dictation.note) : null
+ }, (0, import_react51.createElement)(WaveIcon, { size: 18 })),
+ dictation.note ? (0, import_react51.createElement)("span", { className: "bt-mic-note", role: "status" }, dictation.note) : null
);
}
function menuIcons(roster) {
@@ -23129,23 +23337,23 @@ function menuIcons(roster) {
return (row) => {
if (!row.bot) return PeopleIcon;
const id = row.bot.id;
- if (!marks.has(id)) marks.set(id, ({ size = 14 }) => (0, import_react50.createElement)(BotMark, { bot: roster.getSnapshot().byId[id] ?? row.bot, size }));
+ if (!marks.has(id)) marks.set(id, ({ size = 14 }) => (0, import_react51.createElement)(BotMark, { bot: roster.getSnapshot().byId[id] ?? row.bot, size }));
return marks.get(id);
};
}
function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions }) {
const roster = useRoster((value) => value);
- const [open, setOpen] = (0, import_react50.useState)(null);
+ const [open, setOpen] = (0, import_react51.useState)(null);
const [shown, leaving] = useLinger(open, 120);
- const button = (0, import_react50.useRef)(null);
- const menu = (0, import_react50.useRef)(null);
+ const button = (0, import_react51.useRef)(null);
+ const menu = (0, import_react51.useRef)(null);
const tick = useViewport();
- const inputNow = (0, import_react50.useRef)(void 0);
+ const inputNow = (0, import_react51.useRef)(void 0);
const ready = useInput?.((state) => {
inputNow.current = state;
return steerable(state);
}) === true;
- (0, import_react50.useEffect)(() => {
+ (0, import_react51.useEffect)(() => {
if (!open) return void 0;
const onDown = (event) => {
if (![button.current, menu.current].some((node) => node?.contains(event.target))) setOpen(null);
@@ -23164,13 +23372,13 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions })
window.removeEventListener("keydown", onKey, true);
};
}, [open]);
- (0, import_react50.useEffect)(() => {
+ (0, import_react51.useEffect)(() => {
const card = button.current?.closest("[data-composer-card]");
if (!ready || card === null || card === void 0) return void 0;
card.style.setProperty("--bt-placeholder", JSON.stringify(t("Press Enter to steer queued messages")));
return () => card.style.removeProperty("--bt-placeholder");
});
- (0, import_react50.useEffect)(() => {
+ (0, import_react51.useEffect)(() => {
let steering = false;
const onKey = (event) => {
if (steering || event.defaultPrevented || open) return;
@@ -23192,7 +23400,7 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions })
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, [open, sessionId]);
- const place = (0, import_react50.useMemo)(() => {
+ const place = (0, import_react51.useMemo)(() => {
if (!shown || !button.current) return null;
const rect = button.current.getBoundingClientRect();
return { left: rect.left, bottom: viewBottom() - rect.top + 8 };
@@ -23220,15 +23428,19 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions })
actions.referenceChat(sessionId, inputActions?.captureInsertion?.());
};
const canReference = typeof inputActions?.captureInsertion === "function" && actions.canReferenceChat();
+ const brainstorm = () => {
+ setOpen(null);
+ insertBrainstorm(inputActions);
+ };
const room2 = roster.roomsById?.[sessionId];
const goal = () => {
setOpen(null);
actions.composeGoal(room2.id);
};
- return (0, import_react50.createElement)(
- import_react50.Fragment,
+ return (0, import_react51.createElement)(
+ import_react51.Fragment,
null,
- (0, import_react50.createElement)("button", {
+ (0, import_react51.createElement)("button", {
ref: button,
type: "button",
className: "bt-plus",
@@ -23238,8 +23450,8 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions })
"aria-expanded": Boolean(open),
onMouseDown: keepComposerFocus,
onClick: toggle
- }, (0, import_react50.createElement)(PlusIcon)),
- shown ? (0, import_react_dom9.createPortal)((0, import_react50.createElement)(
+ }, (0, import_react51.createElement)(PlusIcon)),
+ shown ? (0, import_react_dom9.createPortal)((0, import_react51.createElement)(
"div",
{
ref: menu,
@@ -23249,10 +23461,11 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions })
style: place ?? {},
"data-leaving": leaving || void 0
},
- shown.files ? (0, import_react50.createElement)("button", { type: "button", role: "menuitem", onClick: attach }, (0, import_react50.createElement)(PaperclipIcon), (0, import_react50.createElement)("span", { className: "bt-menu-label" }, t("Add files"))) : null,
- canReference ? (0, import_react50.createElement)("button", { type: "button", role: "menuitem", onMouseDown: keepComposerFocus, onClick: reference }, (0, import_react50.createElement)(ChatsIcon), (0, import_react50.createElement)("span", { className: "bt-menu-label" }, t("Reference a chat"))) : null,
- canSetGoal(room2, roster) ? (0, import_react50.createElement)("button", { type: "button", role: "menuitem", onClick: goal }, (0, import_react50.createElement)(GoalIcon), (0, import_react50.createElement)("span", { className: "bt-menu-label" }, t("Set a goal"))) : null,
- (0, import_react50.createElement)("button", { type: "button", role: "menuitem", onClick: schedule }, (0, import_react50.createElement)(ClockIcon), (0, import_react50.createElement)("span", { className: "bt-menu-label" }, t("Scheduled task")))
+ shown.files ? (0, import_react51.createElement)("button", { type: "button", role: "menuitem", onClick: attach }, (0, import_react51.createElement)(PaperclipIcon), (0, import_react51.createElement)("span", { className: "bt-menu-label" }, t("Add files"))) : null,
+ canReference ? (0, import_react51.createElement)("button", { type: "button", role: "menuitem", onMouseDown: keepComposerFocus, onClick: reference }, (0, import_react51.createElement)(ChatsIcon), (0, import_react51.createElement)("span", { className: "bt-menu-label" }, t("Reference a chat"))) : null,
+ canBrainstorm(inputActions) ? (0, import_react51.createElement)("button", { type: "button", role: "menuitem", onMouseDown: keepComposerFocus, onClick: brainstorm }, (0, import_react51.createElement)(BulbIcon), (0, import_react51.createElement)("span", { className: "bt-menu-label" }, t("Brainstorm"))) : null,
+ canSetGoal(room2, roster) ? (0, import_react51.createElement)("button", { type: "button", role: "menuitem", onClick: goal }, (0, import_react51.createElement)(GoalIcon), (0, import_react51.createElement)("span", { className: "bt-menu-label" }, t("Set a goal"))) : null,
+ (0, import_react51.createElement)("button", { type: "button", role: "menuitem", onClick: schedule }, (0, import_react51.createElement)(ClockIcon), (0, import_react51.createElement)("span", { className: "bt-menu-label" }, t("Scheduled task")))
), document.body) : null
);
}
@@ -23478,9 +23691,9 @@ function drawerMenuKeys({ bot, room: room2, canBrowse, canTerminal, canFiles })
}
// src/client/side-chat.js
-var import_react51 = require("react");
+var import_react52 = require("react");
function SideEntry({ chatId, entry, actions }) {
- const [cancelling, setCancelling] = (0, import_react51.useState)(false);
+ const [cancelling, setCancelling] = (0, import_react52.useState)(false);
const question = typeof entry.question === "string" ? entry.question : "";
const answer = typeof entry.answer === "string" ? entry.answer : "";
const cancel = () => {
@@ -23489,15 +23702,15 @@ function SideEntry({ chatId, entry, actions }) {
Promise.resolve(actions.cancelSide(chatId, entry.id)).catch(() => {
}).finally(() => setCancelling(false));
};
- return (0, import_react51.createElement)(
+ return (0, import_react52.createElement)(
"div",
{ className: "bt-side-pair", "data-status": entry.status },
- (0, import_react51.createElement)("div", { className: "bt-side-qrow" }, (0, import_react51.createElement)("div", { className: "bt-side-q" }, question)),
- entry.status === "answering" ? (0, import_react51.createElement)(
+ (0, import_react52.createElement)("div", { className: "bt-side-qrow" }, (0, import_react52.createElement)("div", { className: "bt-side-q" }, question)),
+ entry.status === "answering" ? (0, import_react52.createElement)(
"div",
{ className: "bt-side-a" },
- (0, import_react51.createElement)("span", { className: "bt-shimmer" }, t("Answering…")),
- (0, import_react51.createElement)("button", {
+ (0, import_react52.createElement)("span", { className: "bt-shimmer" }, t("Answering…")),
+ (0, import_react52.createElement)("button", {
type: "button",
className: "bt-soft bt-soft-sm",
disabled: cancelling,
@@ -23505,23 +23718,23 @@ function SideEntry({ chatId, entry, actions }) {
"aria-label": t("Cancel this side question"),
onClick: cancel
}, t("Cancel"))
- ) : (0, import_react51.createElement)(
+ ) : (0, import_react52.createElement)(
"div",
{ className: "bt-side-a" },
- entry.status === "cancelled" ? (0, import_react51.createElement)("p", { className: "bt-side-status" }, t("Cancelled")) : null,
- entry.status === "failed" ? (0, import_react51.createElement)("p", { className: "bt-side-fail" }, failureText(entry)) : null,
- answer !== "" ? (0, import_react51.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: answer, labels: mdLabels2(), variant: "compact" }) : null
+ entry.status === "cancelled" ? (0, import_react52.createElement)("p", { className: "bt-side-status" }, t("Cancelled")) : null,
+ entry.status === "failed" ? (0, import_react52.createElement)("p", { className: "bt-side-fail" }, failureText(entry)) : null,
+ answer !== "" ? (0, import_react52.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: answer, labels: mdLabels2(), variant: "compact" }) : null
)
);
}
function SideChatView({ subject, chat, roster, actions }) {
- const scroll = (0, import_react51.useRef)(null);
- const [draft, setDraft] = (0, import_react51.useState)("");
- const [fail2, setFail] = (0, import_react51.useState)(null);
+ const scroll = (0, import_react52.useRef)(null);
+ const [draft, setDraft] = (0, import_react52.useState)("");
+ const [fail2, setFail] = (0, import_react52.useState)(null);
const entries2 = Array.isArray(chat?.entries) ? chat.entries : [];
const busy = entries2.some((entry) => entry?.status === "answering");
const last = entries2.at(-1);
- (0, import_react51.useEffect)(() => {
+ (0, import_react52.useEffect)(() => {
const node = scroll.current;
if (node) node.scrollTop = node.scrollHeight;
}, [chat?.id, entries2.length, last?.status]);
@@ -23536,19 +23749,19 @@ function SideChatView({ subject, chat, roster, actions }) {
setFail(hostText(error?.message ?? ""));
});
};
- return (0, import_react51.createElement)(
+ return (0, import_react52.createElement)(
"div",
{ className: "bt-side" },
- (0, import_react51.createElement)("p", { className: "bt-side-note" }, t("Answered from progress so far; nothing was run")),
- (0, import_react51.createElement)(
+ (0, import_react52.createElement)("p", { className: "bt-side-note" }, t("Answered from progress so far; nothing was run")),
+ (0, import_react52.createElement)(
"div",
{ className: "bt-side-scroll", ref: scroll },
- entries2.map((entry) => (0, import_react51.createElement)(SideEntry, { key: entry.id, chatId: chat.id, entry, actions }))
+ entries2.map((entry) => (0, import_react52.createElement)(SideEntry, { key: entry.id, chatId: chat.id, entry, actions }))
),
- (0, import_react51.createElement)(
+ (0, import_react52.createElement)(
"div",
{ className: "bt-side-form" },
- (0, import_react51.createElement)("textarea", {
+ (0, import_react52.createElement)("textarea", {
className: "bt-side-input",
rows: 1,
value: draft,
@@ -23566,14 +23779,14 @@ function SideChatView({ subject, chat, roster, actions }) {
}
}),
// With Enter sending off this is the only way to ask; on, it sends the same.
- (0, import_react51.createElement)("button", {
+ (0, import_react52.createElement)("button", {
type: "button",
className: "bt-side-send",
"aria-label": t("Send message"),
disabled: busy || draft.trim() === "" || typeof actions?.askSide !== "function",
onClick: ask
- }, (0, import_react51.createElement)(ArrowUpIcon)),
- fail2 !== null ? (0, import_react51.createElement)("p", { className: "bt-side-fail" }, fail2) : null
+ }, (0, import_react52.createElement)(ArrowUpIcon)),
+ fail2 !== null ? (0, import_react52.createElement)("p", { className: "bt-side-fail" }, fail2) : null
)
);
}
@@ -23926,7 +24139,7 @@ function installHeaderNavigation(slots, face, component, priority) {
}
// src/client/turn-error.js
-var import_react52 = require("react");
+var import_react53 = require("react");
var OFFICIAL = "deepseek-official";
var ACCOUNT = "deepseek-account";
var TOP_UP_URL = "https://platform.deepseek.com/top_up";
@@ -23996,10 +24209,10 @@ var NO_SUBSCRIBE2 = () => () => {
var NO_VIEW = () => null;
function useAccountView(actions) {
const entry = actions.signInEntry?.() ?? null;
- const ops = (0, import_react52.useMemo)(() => entry?.inject?.() ?? {}, [entry]);
+ const ops = (0, import_react53.useMemo)(() => entry?.inject?.() ?? {}, [entry]);
const source = ops.hooks?.account;
const read = source ? () => source.getSnapshot()?.view ?? null : NO_VIEW;
- return (0, import_react52.useSyncExternalStore)(source?.subscribe ?? NO_SUBSCRIBE2, read, read);
+ return (0, import_react53.useSyncExternalStore)(source?.subscribe ?? NO_SUBSCRIBE2, read, read);
}
var topUpOf = (view) => {
const url = view?.links?.topUpUrl;
@@ -24025,7 +24238,7 @@ function failureFacts(data, blocked) {
return facts;
}
function TechnicalDetails({ facts }) {
- const [copied, setCopied] = (0, import_react52.useState)(false);
+ const [copied, setCopied] = (0, import_react53.useState)(false);
if (facts.length === 0) return null;
const copy2 = () => {
const text = facts.map(([name, , value]) => `${name}: ${value}`).join("\n");
@@ -24035,12 +24248,12 @@ function TechnicalDetails({ facts }) {
}).catch(() => {
});
};
- return (0, import_react52.createElement)(
+ return (0, import_react53.createElement)(
"details",
{ className: "bt-fail-tech" },
- (0, import_react52.createElement)("summary", null, t("Technical details")),
- (0, import_react52.createElement)("dl", null, facts.map(([name, label, value]) => [(0, import_react52.createElement)("dt", { key: `${name}:t` }, label), (0, import_react52.createElement)("dd", { key: `${name}:d` }, value)])),
- (0, import_react52.createElement)("button", { type: "button", className: "bt-mini bt-fail-copy", onClick: copy2 }, copied ? (0, import_react52.createElement)(CheckIcon) : (0, import_react52.createElement)(CopyIcon), copied ? t("Copied") : t("Copy"))
+ (0, import_react53.createElement)("summary", null, t("Technical details")),
+ (0, import_react53.createElement)("dl", null, facts.map(([name, label, value]) => [(0, import_react53.createElement)("dt", { key: `${name}:t` }, label), (0, import_react53.createElement)("dd", { key: `${name}:d` }, value)])),
+ (0, import_react53.createElement)("button", { type: "button", className: "bt-mini bt-fail-copy", onClick: copy2 }, copied ? (0, import_react53.createElement)(CheckIcon) : (0, import_react53.createElement)(CopyIcon), copied ? t("Copied") : t("Copy"))
);
}
function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) {
@@ -24051,10 +24264,10 @@ function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) {
const account = useAccountView(actions);
const signedIn = account?.status === "credential-stored";
const topUp = topUpOf(account);
- const [keying, setKeying] = (0, import_react52.useState)(false);
- const [retry, setRetry] = (0, import_react52.useState)("idle");
- const [error, setError] = (0, import_react52.useState)("");
- const [joining, setJoining] = (0, import_react52.useState)(null);
+ const [keying, setKeying] = (0, import_react53.useState)(false);
+ const [retry, setRetry] = (0, import_react53.useState)("idle");
+ const [error, setError] = (0, import_react53.useState)("");
+ const [joining, setJoining] = (0, import_react53.useState)(null);
const blocked = bot?.blocked?.code === data.code ? bot.blocked : void 0;
const provider = blocked?.provider ?? providerOf(bot, roster);
const text = failureText2(data.code, { name: bot?.name ?? t("This Bot"), provider: providerName(roster, provider), status: blocked?.status });
@@ -24071,7 +24284,7 @@ function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) {
void Promise.resolve(actions.updateBot(bot.id, { model })).catch((failure) => setError(hostText(failure?.message ?? String(failure))));
};
const listed = accountModel(roster);
- (0, import_react52.useEffect)(() => {
+ (0, import_react53.useEffect)(() => {
if (joining === null || !signedIn) return void 0;
if (bot === void 0 || bot.model !== joining.from) {
setJoining(null);
@@ -24089,11 +24302,11 @@ function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) {
}, ACCOUNT_MODELS_WAIT_MS);
return () => clearTimeout(timer);
}, [joining, signedIn, listed]);
- const settled = () => (0, import_react52.createElement)(
+ const settled = () => (0, import_react53.createElement)(
"div",
{ className: "bt-fail", "data-settled": "", role: "status" },
- (0, import_react52.createElement)("div", { className: "bt-fail-head" }, (0, import_react52.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react52.createElement)("span", { className: "bt-fail-text" }, text)),
- (0, import_react52.createElement)(TechnicalDetails, { facts })
+ (0, import_react53.createElement)("div", { className: "bt-fail-head" }, (0, import_react53.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react53.createElement)("span", { className: "bt-fail-text" }, text)),
+ (0, import_react53.createElement)(TechnicalDetails, { facts })
);
if (!current) return settled();
const official = provider === OFFICIAL;
@@ -24131,22 +24344,22 @@ function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) {
const button = (fix, primary) => {
const className = primary ? "bt-send bt-fail-go" : "bt-soft bt-soft-sm";
if (fix === "top-up") {
- return (0, import_react52.createElement)("a", { key: fix, className: `${className} bt-fail-link`, href: data.code === "ACCOUNT_QUOTA" ? topUp : TOP_UP_URL, target: "_blank", rel: "noopener noreferrer" }, FIX_LABELS[fix]());
+ return (0, import_react53.createElement)("a", { key: fix, className: `${className} bt-fail-link`, href: data.code === "ACCOUNT_QUOTA" ? topUp : TOP_UP_URL, target: "_blank", rel: "noopener noreferrer" }, FIX_LABELS[fix]());
}
const toggles = keyHere && (fix === "key" || fix === "rekey");
- return (0, import_react52.createElement)("button", { key: fix, type: "button", className, "aria-expanded": toggles ? keying : void 0, onClick: () => runs[fix]() }, FIX_LABELS[fix](signedIn));
+ return (0, import_react53.createElement)("button", { key: fix, type: "button", className, "aria-expanded": toggles ? keying : void 0, onClick: () => runs[fix]() }, FIX_LABELS[fix](signedIn));
};
- const retryButton = (primary) => (0, import_react52.createElement)("button", { key: "retry", type: "button", className: primary ? "bt-send bt-fail-go" : "bt-soft bt-soft-sm", disabled: retry !== "idle", onClick: resume }, retry === "idle" ? t("Retry") : t("Retrying…"));
+ const retryButton = (primary) => (0, import_react53.createElement)("button", { key: "retry", type: "button", className: primary ? "bt-send bt-fail-go" : "bt-soft bt-soft-sm", disabled: retry !== "idle", onClick: resume }, retry === "idle" ? t("Retry") : t("Retrying…"));
const row = retryFirst ? [retryButton(true), ...fixes.map((fix) => button(fix, false))] : [...fixes.map((fix, index) => button(fix, index === 0)), retrying ? retryButton(false) : null];
if (!row.some(Boolean)) return settled();
- return (0, import_react52.createElement)(
+ return (0, import_react53.createElement)(
"div",
{ className: "bt-fail", role: "status" },
- (0, import_react52.createElement)("div", { className: "bt-fail-head" }, (0, import_react52.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react52.createElement)("span", { className: "bt-fail-text" }, text)),
- (0, import_react52.createElement)("div", { className: "bt-fail-actions" }, row),
- keying && keyHere ? (0, import_react52.createElement)(ModelKeyCard, { model: { provider, providerName: providerName(roster, provider) }, actions, onSaved: () => setKeying(false) }) : null,
- error ? (0, import_react52.createElement)("div", { className: "bt-fail-error", role: "alert" }, error) : null,
- (0, import_react52.createElement)(TechnicalDetails, { facts })
+ (0, import_react53.createElement)("div", { className: "bt-fail-head" }, (0, import_react53.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react53.createElement)("span", { className: "bt-fail-text" }, text)),
+ (0, import_react53.createElement)("div", { className: "bt-fail-actions" }, row),
+ keying && keyHere ? (0, import_react53.createElement)(ModelKeyCard, { model: { provider, providerName: providerName(roster, provider) }, actions, onSaved: () => setKeying(false) }) : null,
+ error ? (0, import_react53.createElement)("div", { className: "bt-fail-error", role: "alert" }, error) : null,
+ (0, import_react53.createElement)(TechnicalDetails, { facts })
);
}
var TURN_ERROR_CSS = `
@@ -24173,12 +24386,12 @@ var TURN_ERROR_CSS = `
`;
// src/client/palette.js
-var import_react53 = require("react");
+var import_react54 = require("react");
var PALETTE_EXIT_MS = 160;
function CommandPalette({ start, token, roster, actions, useSessions }) {
- const [query, setQuery] = (0, import_react53.useState)(start ?? "");
- const [cursor, setCursor] = (0, import_react53.useState)(0);
- const [leaving, setLeaving] = (0, import_react53.useState)(false);
+ const [query, setQuery] = (0, import_react54.useState)(start ?? "");
+ const [cursor, setCursor] = (0, import_react54.useState)(0);
+ const [leaving, setLeaving] = (0, import_react54.useState)(false);
const wanted = query.trim().toLowerCase();
const close = () => {
if (leaving) return;
@@ -24214,7 +24427,7 @@ function CommandPalette({ start, token, roster, actions, useSessions }) {
const people = [
...roster.bots.filter((bot) => matchesName(bot.name, bot.role)).map((bot) => ({
key: bot.id,
- avatar: (0, import_react53.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }),
+ avatar: (0, import_react54.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }),
title: bot.name,
subtitle: [bot.role, isMainOf(roster, bot.id) ? t("Main Bot") : ""].filter(Boolean).join(" · "),
badge: bot.hidden ? t("Hidden") : void 0,
@@ -24225,7 +24438,7 @@ function CommandPalette({ start, token, roster, actions, useSessions }) {
})),
...roster.rooms.filter((room2) => matchesName(room2.name)).map((room2) => ({
key: room2.id,
- avatar: (0, import_react53.createElement)(RoomAvatar, { room: room2, roster, size: 24 }),
+ avatar: (0, import_react54.createElement)(RoomAvatar, { room: room2, roster, size: 24 }),
title: room2.name,
subtitle: t("{count} members", { count: room2.members.length }),
badge: room2.hidden ? t("Hidden") : void 0,
@@ -24238,7 +24451,7 @@ function CommandPalette({ start, token, roster, actions, useSessions }) {
if (people.length) sections.push([t("Bots"), people]);
const agents = (roster.agents ?? []).filter(() => matchesName("DSH Agent")).map((agent) => ({
key: agent.id,
- avatar: (0, import_react53.createElement)("span", { className: "bt-palette-agent" }, (0, import_react53.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 18 })),
+ avatar: (0, import_react54.createElement)("span", { className: "bt-palette-agent" }, (0, import_react54.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 18 })),
title: "DSH Agent",
subtitle: t("Plain dsh session"),
run: () => actions.openAgent(agent.id)
@@ -24251,16 +24464,16 @@ function CommandPalette({ start, token, roster, actions, useSessions }) {
key: `${id}:${turn}`,
title: bot?.name ?? room2?.name ?? t("Bot"),
subtitle: snippet,
- avatar: bot ? (0, import_react53.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }) : (0, import_react53.createElement)(RoomAvatar, { room: room2, roster, size: 24 }),
+ avatar: bot ? (0, import_react54.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }) : (0, import_react54.createElement)(RoomAvatar, { room: room2, roster, size: 24 }),
run: () => actions.openSession(id)
};
});
if (messages.length) sections.push([t("Messages"), messages]);
const commands = [
- { key: "cmd:new", icon: (0, import_react53.createElement)(PlusIcon), title: t("New chat"), run: () => actions.openNewChat("new") },
- { key: "cmd:bot", icon: (0, import_react53.createElement)(PlusIcon), title: t("Create Bot"), run: () => actions.openNewChat("create") },
- { key: "cmd:group", icon: (0, import_react53.createElement)(PeopleIcon), title: t("Create group chat"), run: () => actions.openNewChat("group") },
- { key: "cmd:settings", icon: (0, import_react53.createElement)(GearIcon), title: t("Settings"), run: () => actions.openSettings("general") }
+ { key: "cmd:new", icon: (0, import_react54.createElement)(PlusIcon), title: t("New chat"), run: () => actions.openNewChat("new") },
+ { key: "cmd:bot", icon: (0, import_react54.createElement)(PlusIcon), title: t("Create Bot"), run: () => actions.openNewChat("create") },
+ { key: "cmd:group", icon: (0, import_react54.createElement)(PeopleIcon), title: t("Create group chat"), run: () => actions.openNewChat("group") },
+ { key: "cmd:settings", icon: (0, import_react54.createElement)(GearIcon), title: t("Settings"), run: () => actions.openSettings("general") }
].filter((command) => matchesName(command.title));
if (commands.length) sections.push([t("Commands"), commands]);
const rows2 = sections.flatMap(([, items]) => items);
@@ -24270,7 +24483,7 @@ function CommandPalette({ start, token, roster, actions, useSessions }) {
${shown}`, { axis: "y", ...QUICK_EDGES });
const listRef = glide.box;
useFlip(listRef, shown, "[data-flip]");
- (0, import_react53.useEffect)(() => {
+ (0, import_react54.useEffect)(() => {
listRef.current?.querySelector("[aria-selected=true]")?.scrollIntoView({ block: "nearest" });
}, [active, query]);
const choose = (row) => {
@@ -24279,18 +24492,18 @@ ${shown}`, { axis: "y", ...QUICK_EDGES });
close();
};
let index = -1;
- return (0, import_react53.createElement)(
+ return (0, import_react54.createElement)(
"div",
{ className: "bt-palette-layer", "data-leaving": leaving || void 0 },
- (0, import_react53.createElement)("div", { className: "bt-backdrop", onMouseDown: close }),
- (0, import_react53.createElement)(
+ (0, import_react54.createElement)("div", { className: "bt-backdrop", onMouseDown: close }),
+ (0, import_react54.createElement)(
"div",
{ className: "bt-palette", role: "dialog", "aria-label": t("Search"), "aria-modal": true },
- (0, import_react53.createElement)(
+ (0, import_react54.createElement)(
"div",
{ className: "bt-palette-head" },
- (0, import_react53.createElement)("span", { className: "bt-palette-glyph", "aria-hidden": true }, (0, import_react53.createElement)(SearchIcon)),
- (0, import_react53.createElement)("input", {
+ (0, import_react54.createElement)("span", { className: "bt-palette-glyph", "aria-hidden": true }, (0, import_react54.createElement)(SearchIcon)),
+ (0, import_react54.createElement)("input", {
autoFocus: true,
value: query,
placeholder: t("Search Bots, chats and messages"),
@@ -24316,29 +24529,29 @@ ${shown}`, { axis: "y", ...QUICK_EDGES });
}
}
}),
- query ? (0, import_react53.createElement)("button", { type: "button", className: "bt-palette-clear", "aria-label": t("Clear search"), onClick: () => {
+ query ? (0, import_react54.createElement)("button", { type: "button", className: "bt-palette-clear", "aria-label": t("Clear search"), onClick: () => {
setQuery("");
setCursor(0);
- } }, (0, import_react53.createElement)(CloseIcon)) : null
+ } }, (0, import_react54.createElement)(CloseIcon)) : null
),
- (0, import_react53.createElement)(
+ (0, import_react54.createElement)(
"div",
{ ref: listRef, id: "bt-palette-list", className: "bt-palette-list", role: "listbox", "aria-label": t("Results") },
- (0, import_react53.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }),
- rows2.length === 0 ? (0, import_react53.createElement)(
+ (0, import_react54.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }),
+ rows2.length === 0 ? (0, import_react54.createElement)(
"div",
{ className: "bt-palette-empty" },
- (0, import_react53.createElement)("span", { className: "bt-palette-empty-icon", "aria-hidden": true }, (0, import_react53.createElement)(SearchIcon)),
- (0, import_react53.createElement)("span", { className: "bt-palette-empty-label" }, t("No results")),
- (0, import_react53.createElement)("span", { className: "bt-palette-empty-hint" }, t("Try a Bot name or words from a message"))
- ) : sections.map(([title, items]) => (0, import_react53.createElement)(
- import_react53.Fragment,
+ (0, import_react54.createElement)("span", { className: "bt-palette-empty-icon", "aria-hidden": true }, (0, import_react54.createElement)(SearchIcon)),
+ (0, import_react54.createElement)("span", { className: "bt-palette-empty-label" }, t("No results")),
+ (0, import_react54.createElement)("span", { className: "bt-palette-empty-hint" }, t("Try a Bot name or words from a message"))
+ ) : sections.map(([title, items]) => (0, import_react54.createElement)(
+ import_react54.Fragment,
{ key: title },
- (0, import_react53.createElement)("div", { className: "bt-palette-section", role: "presentation", "data-flip": `section:${title}` }, title),
+ (0, import_react54.createElement)("div", { className: "bt-palette-section", role: "presentation", "data-flip": `section:${title}` }, title),
items.map((row) => {
index += 1;
const at = index;
- return (0, import_react53.createElement)(
+ return (0, import_react54.createElement)(
"button",
{
key: row.key,
@@ -24352,14 +24565,14 @@ ${shown}`, { axis: "y", ...QUICK_EDGES });
},
onClick: () => choose(row)
},
- (0, import_react53.createElement)("span", { className: "bt-palette-lead" }, row.avatar ?? (0, import_react53.createElement)("span", { className: "bt-palette-cmd" }, row.icon)),
- (0, import_react53.createElement)(
+ (0, import_react54.createElement)("span", { className: "bt-palette-lead" }, row.avatar ?? (0, import_react54.createElement)("span", { className: "bt-palette-cmd" }, row.icon)),
+ (0, import_react54.createElement)(
"span",
{ className: "bt-palette-text" },
- (0, import_react53.createElement)("span", { className: "bt-palette-title" }, row.title),
- row.subtitle ? (0, import_react53.createElement)("span", { className: "bt-palette-sub" }, row.subtitle) : null
+ (0, import_react54.createElement)("span", { className: "bt-palette-title" }, row.title),
+ row.subtitle ? (0, import_react54.createElement)("span", { className: "bt-palette-sub" }, row.subtitle) : null
),
- row.badge ? (0, import_react53.createElement)("span", { className: "bt-palette-badge" }, row.badge) : null
+ row.badge ? (0, import_react54.createElement)("span", { className: "bt-palette-badge" }, row.badge) : null
);
})
))
@@ -24369,18 +24582,18 @@ ${shown}`, { axis: "y", ...QUICK_EDGES });
}
// src/client/new-chat.js
-var import_react54 = require("react");
+var import_react55 = require("react");
function NewChat({ mode, sectionId = null, paneLeft, roster, actions }) {
- const [query, setQuery] = (0, import_react54.useState)("");
- const [picked, setPicked] = (0, import_react54.useState)([]);
- const [group, setGroup] = (0, import_react54.useState)(mode === "group");
- const [admin, setAdmin] = (0, import_react54.useState)(null);
- const [message, setMessage] = (0, import_react54.useState)("");
- const [busy, setBusy] = (0, import_react54.useState)(false);
- const [error, setError] = (0, import_react54.useState)("");
- const [cursor, setCursor] = (0, import_react54.useState)(0);
- const [draft, setDraft] = (0, import_react54.useState)(mode === "create" ? { name: "", fromList: false, sectionId } : null);
- const inputRef = (0, import_react54.useRef)(null);
+ const [query, setQuery] = (0, import_react55.useState)("");
+ const [picked, setPicked] = (0, import_react55.useState)([]);
+ const [group, setGroup] = (0, import_react55.useState)(mode === "group");
+ const [admin, setAdmin] = (0, import_react55.useState)(null);
+ const [message, setMessage] = (0, import_react55.useState)("");
+ const [busy, setBusy] = (0, import_react55.useState)(false);
+ const [error, setError] = (0, import_react55.useState)("");
+ const [cursor, setCursor] = (0, import_react55.useState)(0);
+ const [draft, setDraft] = (0, import_react55.useState)(mode === "create" ? { name: "", fromList: false, sectionId } : null);
+ const inputRef = (0, import_react55.useRef)(null);
const close = () => actions.closeOverlay();
useEscape(close);
const wanted = query.trim().toLowerCase();
@@ -24468,14 +24681,14 @@ function NewChat({ mode, sectionId = null, paneLeft, roster, actions }) {
});
const options = [];
if (!group && picked.length === 0 && mode !== "search" && wanted === "") {
- options.push({ key: "new", icon: (0, import_react54.createElement)(PlusIcon), label: t("Create new Bot"), run: createBot });
- options.push({ key: "group", icon: (0, import_react54.createElement)(PeopleIcon), label: t("Create group chat"), run: () => {
+ options.push({ key: "new", icon: (0, import_react55.createElement)(PlusIcon), label: t("Create new Bot"), run: createBot });
+ options.push({ key: "group", icon: (0, import_react55.createElement)(PeopleIcon), label: t("Create group chat"), run: () => {
setGroup(true);
setCursor(0);
inputRef.current?.focus();
} });
if ((roster.agents ?? []).length === 0 && actions.addAgent) {
- options.push({ key: "agent", icon: (0, import_react54.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 16 }), label: t("Add DSH Agent"), run: () => run2(async () => {
+ options.push({ key: "agent", icon: (0, import_react55.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 16 }), label: t("Add DSH Agent"), run: () => run2(async () => {
await actions.addAgent();
close();
}) });
@@ -24484,19 +24697,19 @@ function NewChat({ mode, sectionId = null, paneLeft, roster, actions }) {
for (const bot of matches2) {
options.push({ key: bot.id, bot, label: bot.name, hint: choosingAdmin ? t("Make admin") : group || picked.length > 0 ? t("Add to group chat") : void 0, run: () => openBot(bot) });
}
- if (wanted !== "" && !exact && mode !== "search") options.push({ key: "create", icon: (0, import_react54.createElement)(PlusIcon), label: t("Create new Bot “{name}”", { name: query.trim() }), run: createBot });
+ if (wanted !== "" && !exact && mode !== "search") options.push({ key: "create", icon: (0, import_react55.createElement)(PlusIcon), label: t("Create new Bot “{name}”", { name: query.trim() }), run: createBot });
const active = Math.min(cursor, Math.max(options.length - 1, 0));
const listed = options.map((option) => option.key).join("\n");
const glide = useGlide(`${active}
${listed}`, { axis: "y", ...QUICK_EDGES });
useFlip(glide.box, listed, "[data-flip]");
- const drop = (0, import_react54.useRef)(null);
+ const drop = (0, import_react55.useRef)(null);
useMorph(drop, listed);
if (draft) {
- return (0, import_react54.createElement)(
+ return (0, import_react55.createElement)(
"div",
{ className: "bt-pane", style: { left: paneLeft } },
- (0, import_react54.createElement)(CreateBot, {
+ (0, import_react55.createElement)(CreateBot, {
roster,
actions,
start: draft,
@@ -24517,33 +24730,33 @@ ${listed}`, { axis: "y", ...QUICK_EDGES });
if (picked.length > 0) setPicked((current) => current.slice(0, -1));
else if (admin !== null) setAdmin(null);
};
- return (0, import_react54.createElement)(
+ return (0, import_react55.createElement)(
"div",
{ className: "bt-pane", style: { left: paneLeft } },
- (0, import_react54.createElement)(
+ (0, import_react55.createElement)(
"div",
{ className: "bt-newchat", role: "dialog", "aria-label": mode === "search" ? t("Search") : t("New chat") },
- (0, import_react54.createElement)(
+ (0, import_react55.createElement)(
"div",
{ className: "bt-to" },
- (0, import_react54.createElement)("span", { className: "bt-to-label" }, t("To:")),
- adminBot ? (0, import_react54.createElement)(
+ (0, import_react55.createElement)("span", { className: "bt-to-label" }, t("To:")),
+ adminBot ? (0, import_react55.createElement)(
"span",
{ key: adminBot.id, className: "bt-token bt-token-admin", title: t("Admin") },
- (0, import_react54.createElement)(BotMark, { bot: adminBot, size: 16 }),
+ (0, import_react55.createElement)(BotMark, { bot: adminBot, size: 16 }),
adminBot.name,
- (0, import_react54.createElement)(AdminStar),
- (0, import_react54.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: adminBot.name }), onClick: () => setAdmin(null) }, "×")
+ (0, import_react55.createElement)(AdminStar),
+ (0, import_react55.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: adminBot.name }), onClick: () => setAdmin(null) }, "×")
) : null,
- choosingAdmin ? (0, import_react54.createElement)("span", { className: "bt-to-star", "aria-hidden": true }, (0, import_react54.createElement)(AdminStar)) : null,
- pickedBots.map((bot) => (0, import_react54.createElement)(
+ choosingAdmin ? (0, import_react55.createElement)("span", { className: "bt-to-star", "aria-hidden": true }, (0, import_react55.createElement)(AdminStar)) : null,
+ pickedBots.map((bot) => (0, import_react55.createElement)(
"span",
{ key: bot.id, className: "bt-token" },
- (0, import_react54.createElement)(BotMark, { bot, size: 16 }),
+ (0, import_react55.createElement)(BotMark, { bot, size: 16 }),
bot.name,
- (0, import_react54.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: bot.name }), onClick: () => setPicked((current) => current.filter((id) => id !== bot.id)) }, "×")
+ (0, import_react55.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: bot.name }), onClick: () => setPicked((current) => current.filter((id) => id !== bot.id)) }, "×")
)),
- (0, import_react54.createElement)("input", {
+ (0, import_react55.createElement)("input", {
ref: inputRef,
autoFocus: true,
value: query,
@@ -24567,20 +24780,20 @@ ${listed}`, { axis: "y", ...QUICK_EDGES });
} else if (event.key === "Backspace" && query === "") unpick();
}
}),
- group && admin !== null ? (0, import_react54.createElement)("button", {
+ group && admin !== null ? (0, import_react55.createElement)("button", {
type: "button",
className: "bt-send bt-to-create",
disabled: busy || picked.length === 0,
title: picked.length === 0 ? t("Add at least one more Bot") : void 0,
onClick: createGroup
}, t("Create group chat")) : null,
- (0, import_react54.createElement)("button", { type: "button", className: "bt-x", "aria-label": t("Close new chat"), onClick: close }, "×")
+ (0, import_react55.createElement)("button", { type: "button", className: "bt-x", "aria-label": t("Close new chat"), onClick: close }, "×")
),
- (0, import_react54.createElement)("div", { ref: drop, className: "bt-drop" }, (0, import_react54.createElement)(
+ (0, import_react55.createElement)("div", { ref: drop, className: "bt-drop" }, (0, import_react55.createElement)(
"div",
{ ref: glide.box, role: "listbox", "aria-label": t("Recipients"), className: "bt-drop-list" },
- (0, import_react54.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }),
- options.length === 0 ? (0, import_react54.createElement)("div", { className: "bt-hint" }, mode === "search" ? t("No Bots match") : t("Type a name to create a Bot")) : options.map((option, index) => (0, import_react54.createElement)(
+ (0, import_react55.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }),
+ options.length === 0 ? (0, import_react55.createElement)("div", { className: "bt-hint" }, mode === "search" ? t("No Bots match") : t("Type a name to create a Bot")) : options.map((option, index) => (0, import_react55.createElement)(
"button",
{
key: option.key,
@@ -24592,21 +24805,21 @@ ${listed}`, { axis: "y", ...QUICK_EDGES });
onMouseEnter: () => setCursor(index),
onClick: option.run
},
- option.bot ? (0, import_react54.createElement)(BotMark, { bot: option.bot, size: 22 }) : (0, import_react54.createElement)("span", { className: "bt-option-icon" }, option.icon),
- (0, import_react54.createElement)("span", { className: "bt-option-label" }, option.label),
- option.hint && index === active ? (0, import_react54.createElement)("span", { className: "bt-option-hint" }, option.hint) : null
+ option.bot ? (0, import_react55.createElement)(BotMark, { bot: option.bot, size: 22 }) : (0, import_react55.createElement)("span", { className: "bt-option-icon" }, option.icon),
+ (0, import_react55.createElement)("span", { className: "bt-option-label" }, option.label),
+ option.hint && index === active ? (0, import_react55.createElement)("span", { className: "bt-option-hint" }, option.hint) : null
))
)),
- (0, import_react54.createElement)("div", { className: "bt-nc-spacer" }),
- error ? (0, import_react54.createElement)("div", { className: "bt-error" }, error) : null,
- (0, import_react54.createElement)(
+ (0, import_react55.createElement)("div", { className: "bt-nc-spacer" }),
+ error ? (0, import_react55.createElement)("div", { className: "bt-error" }, error) : null,
+ (0, import_react55.createElement)(
"div",
{ className: "bt-nc-compose" },
- (0, import_react54.createElement)(
+ (0, import_react55.createElement)(
"div",
{ className: "bt-nc-card" },
- (0, import_react54.createElement)("span", { className: "bt-nc-plus", "aria-hidden": true }, (0, import_react54.createElement)(PlusIcon)),
- (0, import_react54.createElement)("textarea", {
+ (0, import_react55.createElement)("span", { className: "bt-nc-plus", "aria-hidden": true }, (0, import_react55.createElement)(PlusIcon)),
+ (0, import_react55.createElement)("textarea", {
rows: 1,
value: message,
placeholder,
@@ -24619,7 +24832,7 @@ ${listed}`, { axis: "y", ...QUICK_EDGES });
}
}
}),
- (0, import_react54.createElement)("button", { type: "button", className: "bt-nc-send", "aria-label": t("Send message"), disabled: busy || message.trim() === "" || picked.length === 0, onClick: sendMessage }, (0, import_react54.createElement)(ArrowUpIcon))
+ (0, import_react55.createElement)("button", { type: "button", className: "bt-nc-send", "aria-label": t("Send message"), disabled: busy || message.trim() === "" || picked.length === 0, onClick: sendMessage }, (0, import_react55.createElement)(ArrowUpIcon))
)
)
)
@@ -24627,14 +24840,14 @@ ${listed}`, { axis: "y", ...QUICK_EDGES });
}
// src/client/exchange.js
-var import_react55 = require("react");
+var import_react56 = require("react");
var SHEET_EXIT_MS = 220;
function ExchangeDialog({ pair, paneLeft, roster, actions }) {
- const [entries2, setEntries] = (0, import_react55.useState)(null);
- const [leaving, setLeaving] = (0, import_react55.useState)(false);
- const log = (0, import_react55.useRef)(null);
- const atEnd = (0, import_react55.useRef)(true);
- (0, import_react55.useLayoutEffect)(() => {
+ const [entries2, setEntries] = (0, import_react56.useState)(null);
+ const [leaving, setLeaving] = (0, import_react56.useState)(false);
+ const log = (0, import_react56.useRef)(null);
+ const atEnd = (0, import_react56.useRef)(true);
+ (0, import_react56.useLayoutEffect)(() => {
if (entries2 !== null && atEnd.current && log.current) log.current.scrollTop = log.current.scrollHeight;
}, [entries2]);
const close = () => {
@@ -24643,7 +24856,7 @@ function ExchangeDialog({ pair, paneLeft, roster, actions }) {
setTimeout(() => actions.closeOverlay(), SHEET_EXIT_MS);
};
useEscape(close);
- (0, import_react55.useEffect)(() => {
+ (0, import_react56.useEffect)(() => {
let stop = false;
let timer;
let seen = null;
@@ -24669,53 +24882,53 @@ function ExchangeDialog({ pair, paneLeft, roster, actions }) {
const right = roster.byId[pair[1]];
const flat = layoutOf(roster.prefs) === "flat";
let lastDay = 0;
- return (0, import_react55.createElement)(
+ return (0, import_react56.createElement)(
"div",
{ className: "bt-pane bt-exchange", style: { left: paneLeft }, "data-leaving": leaving || void 0 },
- (0, import_react55.createElement)(
+ (0, import_react56.createElement)(
"div",
{ className: "bt-dialog", role: "dialog", "aria-label": t("Bot exchange") },
- (0, import_react55.createElement)("div", { className: "bt-head" }, (0, import_react55.createElement)(
+ (0, import_react56.createElement)("div", { className: "bt-head" }, (0, import_react56.createElement)(
"span",
{ className: "bt-pill", style: { cursor: "default" } },
- left ? (0, import_react55.createElement)(BotMark, { bot: left, size: 22 }) : null,
+ left ? (0, import_react56.createElement)(BotMark, { bot: left, size: 22 }) : null,
left?.name ?? "?",
- (0, import_react55.createElement)("span", { className: "bt-swap" }, "⇄"),
- right ? (0, import_react55.createElement)(BotMark, { bot: right, size: 22 }) : null,
+ (0, import_react56.createElement)("span", { className: "bt-swap" }, "⇄"),
+ right ? (0, import_react56.createElement)(BotMark, { bot: right, size: 22 }) : null,
right?.name ?? "?"
)),
- (0, import_react55.createElement)(
+ (0, import_react56.createElement)(
"div",
{ ref: log, className: "bt-dialog-log", role: "log", "aria-label": t("Bot exchange transcript"), onScroll: (event) => {
const node = event.currentTarget;
atEnd.current = node.scrollHeight - node.scrollTop - node.clientHeight < 2;
} },
- entries2 === null ? (0, import_react55.createElement)("div", { className: "bt-hint" }, t("Loading…")) : entries2.length === 0 ? (0, import_react55.createElement)("div", { className: "bt-hint" }, t("No messages yet")) : entries2.map((entry) => {
+ entries2 === null ? (0, import_react56.createElement)("div", { className: "bt-hint" }, t("Loading…")) : entries2.length === 0 ? (0, import_react56.createElement)("div", { className: "bt-hint" }, t("No messages yet")) : entries2.map((entry) => {
const bot = roster.byId[entry.from] ?? { id: entry.from, name: t("You"), color: "gray" };
const showDay = entry.time - lastDay > 30 * 60 * 1e3;
lastDay = entry.time;
const whole = entry.length === void 0 ? void 0 : { length: entry.length, load: () => actions.exchangeText(entry.id) };
- const lead = (0, import_react55.createElement)("span", { className: "bt-lead" }, (0, import_react55.createElement)(BotMark, { bot, size: 22 }));
- return (0, import_react55.createElement)(
- import_react55.Fragment,
+ const lead = (0, import_react56.createElement)("span", { className: "bt-lead" }, (0, import_react56.createElement)(BotMark, { bot, size: 22 }));
+ return (0, import_react56.createElement)(
+ import_react56.Fragment,
{ key: entry.id },
- showDay ? (0, import_react55.createElement)("time", { className: "bt-time" }, dayLabel(entry.time)) : null,
- (0, import_react55.createElement)(
+ showDay ? (0, import_react56.createElement)("time", { className: "bt-time" }, dayLabel(entry.time)) : null,
+ (0, import_react56.createElement)(
"div",
{ className: "bt-group-msg" },
- (0, import_react55.createElement)("span", { className: "bt-group-name", style: flat ? void 0 : { color: inkText(colorOf(bot)) } }, flat ? lead : null, bot.name),
- (0, import_react55.createElement)(Bubbles, { texts: [stripLongNote(entry.text)], roster, selfId: bot.id, actions, whole, lead: flat ? null : lead })
+ (0, import_react56.createElement)("span", { className: "bt-group-name", style: flat ? void 0 : { color: inkText(colorOf(bot)) } }, flat ? lead : null, bot.name),
+ (0, import_react56.createElement)(Bubbles, { texts: [stripLongNote(entry.text)], roster, selfId: bot.id, actions, whole, lead: flat ? null : lead })
)
);
})
),
- (0, import_react55.createElement)("div", { className: "bt-dialog-foot" }, (0, import_react55.createElement)("button", { type: "button", className: "bt-soft", onClick: close }, t("Close Chat")))
+ (0, import_react56.createElement)("div", { className: "bt-dialog-foot" }, (0, import_react56.createElement)("button", { type: "button", className: "bt-soft", onClick: close }, t("Close Chat")))
)
);
}
// src/client/voice.js
-var import_react56 = require("react");
+var import_react57 = require("react");
var plainSpeech = (text) => stripHeader(text).replace(/```[\s\S]*?```/g, " ").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[*_`#>|~-]+/g, " ").replace(/\s+/g, " ").trim();
var VOICE_LABELS = {
listening: "Listening",
@@ -24747,8 +24960,8 @@ function watchReply(read, watch, consume) {
};
}
function useMicLevel(enabled) {
- const [level, setLevel] = (0, import_react56.useState)(0);
- (0, import_react56.useEffect)(() => {
+ const [level, setLevel] = (0, import_react57.useState)(0);
+ (0, import_react57.useEffect)(() => {
if (!enabled || !navigator.mediaDevices?.getUserMedia) return void 0;
let stream = null;
let audio = null;
@@ -24798,18 +25011,18 @@ function VoiceMode({ sessionId, paneLeft, roster, actions, useSessions, useSessi
const entry = Array.isArray(outline) ? outline[outline.length - 1] : void 0;
return entry ? `${outline.length}|${entry.turn}` : "0|";
});
- const [speech] = (0, import_react56.useState)(() => actions.speech());
- const [phase, setPhase] = (0, import_react56.useState)(speech ? "starting" : speechApi() ? "listening" : "unsupported");
- const [catalog, setCatalog] = (0, import_react56.useState)(null);
- const [heard, setHeard] = (0, import_react56.useState)("");
- const [said, setSaid] = (0, import_react56.useState)("");
- const [note, setNote] = (0, import_react56.useState)("");
- const [serviceLevel, setServiceLevel] = (0, import_react56.useState)(0);
- const [cycle, setCycle] = (0, import_react56.useState)(0);
- const waiting = (0, import_react56.useRef)(null);
- const reply = (0, import_react56.useRef)(lastReply);
+ const [speech] = (0, import_react57.useState)(() => actions.speech());
+ const [phase, setPhase] = (0, import_react57.useState)(speech ? "starting" : speechApi() ? "listening" : "unsupported");
+ const [catalog, setCatalog] = (0, import_react57.useState)(null);
+ const [heard, setHeard] = (0, import_react57.useState)("");
+ const [said, setSaid] = (0, import_react57.useState)("");
+ const [note, setNote] = (0, import_react57.useState)("");
+ const [serviceLevel, setServiceLevel] = (0, import_react57.useState)(0);
+ const [cycle, setCycle] = (0, import_react57.useState)(0);
+ const waiting = (0, import_react57.useRef)(null);
+ const reply = (0, import_react57.useRef)(lastReply);
reply.current = lastReply;
- const turn = (0, import_react56.useRef)(0);
+ const turn = (0, import_react57.useRef)(0);
const close = () => {
turn.current += 1;
window.speechSynthesis?.cancel();
@@ -24828,12 +25041,12 @@ function VoiceMode({ sessionId, paneLeft, roster, actions, useSessions, useSessi
dictation.stop();
submit(text);
});
- (0, import_react56.useEffect)(() => {
+ (0, import_react57.useEffect)(() => {
if (!note) return void 0;
const timer = setTimeout(() => setNote(""), 2600);
return () => clearTimeout(timer);
}, [note]);
- (0, import_react56.useEffect)(() => {
+ (0, import_react57.useEffect)(() => {
if (!speech) return void 0;
let live = true;
speechCatalog(speech).then(({ catalog: next, usable }) => {
@@ -24848,16 +25061,16 @@ function VoiceMode({ sessionId, paneLeft, roster, actions, useSessions, useSessi
};
}, [speech]);
const listen = phase === "listening";
- (0, import_react56.useEffect)(() => {
+ (0, import_react57.useEffect)(() => {
if (speech || !listen || dictation.listening) return void 0;
const timer = setTimeout(() => dictation.start({ continuous: false, onEnd: () => {
} }), 250);
return () => clearTimeout(timer);
}, [listen, dictation.listening]);
- (0, import_react56.useEffect)(() => {
+ (0, import_react57.useEffect)(() => {
if (phase !== "listening") dictation.stop();
}, [phase]);
- (0, import_react56.useEffect)(() => {
+ (0, import_react57.useEffect)(() => {
if (!speech || !catalog || !listen) return void 0;
const own = turn.current;
let capture = null;
@@ -24919,7 +25132,7 @@ function VoiceMode({ sessionId, paneLeft, roster, actions, useSessions, useSessi
setServiceLevel(0);
};
}, [speech, catalog, listen, cycle]);
- (0, import_react56.useEffect)(() => {
+ (0, import_react57.useEffect)(() => {
if (phase !== "thinking" || running || waiting.current === null) return void 0;
const count = lastReply.slice(0, lastReply.indexOf("|"));
const turn2 = Number(lastReply.slice(lastReply.indexOf("|") + 1));
@@ -24954,7 +25167,7 @@ function VoiceMode({ sessionId, paneLeft, roster, actions, useSessions, useSessi
}
);
}, [phase, running, lastReply]);
- (0, import_react56.useEffect)(() => () => window.speechSynthesis?.cancel(), []);
+ (0, import_react57.useEffect)(() => () => window.speechSynthesis?.cancel(), []);
const micLevel = useMicLevel(!speech && phase === "listening" && dictation.listening);
const level = speech ? serviceLevel : micLevel;
const markState = phase === "thinking" || phase === "transcribing" ? "thinking" : phase === "speaking" ? "sending" : "idle";
@@ -24968,7 +25181,7 @@ function VoiceMode({ sessionId, paneLeft, roster, actions, useSessions, useSessi
window.speechSynthesis?.cancel();
setPhase("paused");
};
- (0, import_react56.useEffect)(() => {
+ (0, import_react57.useEffect)(() => {
if (phase !== "preparing" || !speech) return void 0;
let stopped = false;
let timer;
@@ -25020,47 +25233,47 @@ function VoiceMode({ sessionId, paneLeft, roster, actions, useSessions, useSessi
};
const caption = phase === "speaking" ? said : heard;
const shownNote = note || dictation.note;
- return (0, import_react56.createElement)(
+ return (0, import_react57.createElement)(
"div",
{ className: "bt-pane bt-voice-pane", style: { left: paneLeft } },
- (0, import_react56.createElement)(
+ (0, import_react57.createElement)(
"div",
{ className: "bt-voice-stage", role: "dialog", "aria-label": t("Voice chat with {name}", { name }), "data-phase": phase === "transcribing" ? "thinking" : phase },
- (0, import_react56.createElement)(
+ (0, import_react57.createElement)(
"div",
{ className: "bt-voice-orb", style: { "--bt-level": level } },
- (0, import_react56.createElement)("span", { className: "bt-voice-ring", "aria-hidden": true }),
- (0, import_react56.createElement)("span", { className: "bt-voice-ring bt-voice-ring-2", "aria-hidden": true }),
- bot ? (0, import_react56.createElement)(BotMark, { bot, size: 112, state: markState, live: true, gaze: phase === "listening" }) : room2 ? (0, import_react56.createElement)(RoomAvatar, { room: room2, roster, size: 112 }) : null
+ (0, import_react57.createElement)("span", { className: "bt-voice-ring", "aria-hidden": true }),
+ (0, import_react57.createElement)("span", { className: "bt-voice-ring bt-voice-ring-2", "aria-hidden": true }),
+ bot ? (0, import_react57.createElement)(BotMark, { bot, size: 112, state: markState, live: true, gaze: phase === "listening" }) : room2 ? (0, import_react57.createElement)(RoomAvatar, { room: room2, roster, size: 112 }) : null
),
- (0, import_react56.createElement)("div", { className: "bt-voice-name" }, name),
- (0, import_react56.createElement)(
+ (0, import_react57.createElement)("div", { className: "bt-voice-name" }, name),
+ (0, import_react57.createElement)(
"div",
{ className: "bt-voice-status", role: "status" },
- phase === "thinking" ? (0, import_react56.createElement)(Shimmer, null, t("Thinking…")) : phase === "transcribing" ? (0, import_react56.createElement)(Shimmer, null, t("Recognizing…")) : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : ""
+ phase === "thinking" ? (0, import_react57.createElement)(Shimmer, null, t("Thinking…")) : phase === "transcribing" ? (0, import_react57.createElement)(Shimmer, null, t("Recognizing…")) : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : ""
),
- (0, import_react56.createElement)("div", { className: "bt-voice-caption", key: `${phase}:${caption.slice(0, 12)}` }, caption),
- openSetup ? (0, import_react56.createElement)("button", { type: "button", className: "bt-voice-setup", onClick: startSetup }, t("Set up voice input")) : null,
- shownNote ? (0, import_react56.createElement)("div", { className: "bt-voice-note" }, shownNote) : null
+ (0, import_react57.createElement)("div", { className: "bt-voice-caption", key: `${phase}:${caption.slice(0, 12)}` }, caption),
+ openSetup ? (0, import_react57.createElement)("button", { type: "button", className: "bt-voice-setup", onClick: startSetup }, t("Set up voice input")) : null,
+ shownNote ? (0, import_react57.createElement)("div", { className: "bt-voice-note" }, shownNote) : null
),
- (0, import_react56.createElement)(
+ (0, import_react57.createElement)(
"div",
{ className: "bt-voice-bar" },
- (0, import_react56.createElement)("button", {
+ (0, import_react57.createElement)("button", {
type: "button",
className: "bt-voice-btn",
"aria-pressed": phase === "paused",
disabled: blocked,
"aria-label": phase === "paused" ? t("Resume listening") : t("Pause"),
onClick: togglePause
- }, (0, import_react56.createElement)(MicIcon, { size: 20 }), phase === "paused" ? (0, import_react56.createElement)("span", { className: "bt-voice-slash", "aria-hidden": true }) : null),
- (0, import_react56.createElement)("button", { type: "button", className: "bt-voice-btn bt-voice-end", "aria-label": t("End voice chat"), onClick: close }, (0, import_react56.createElement)(CloseIcon))
+ }, (0, import_react57.createElement)(MicIcon, { size: 20 }), phase === "paused" ? (0, import_react57.createElement)("span", { className: "bt-voice-slash", "aria-hidden": true }) : null),
+ (0, import_react57.createElement)("button", { type: "button", className: "bt-voice-btn bt-voice-end", "aria-label": t("End voice chat"), onClick: close }, (0, import_react57.createElement)(CloseIcon))
)
);
}
// src/client/context-menu.js
-var import_react57 = require("react");
+var import_react58 = require("react");
var SECTION_COLORS = ["blue", "orange", "green", "violet", "rose"];
function sectionMoveItems(entry, roster, actions) {
const sections = roster.sections ?? [];
@@ -25081,9 +25294,9 @@ function sectionMoveItems(entry, roster, actions) {
}
function ContextMenu({ menu, roster, actions, useWork, leaving = false }) {
useEscape(() => actions.closeMenu());
- const ref = (0, import_react57.useRef)(null);
- const trigger = (0, import_react57.useRef)(typeof document === "undefined" ? null : document.activeElement);
- (0, import_react57.useEffect)(() => {
+ const ref = (0, import_react58.useRef)(null);
+ const trigger = (0, import_react58.useRef)(typeof document === "undefined" ? null : document.activeElement);
+ (0, import_react58.useEffect)(() => {
const onDown = (event) => {
if (!(event.target instanceof Element) || !event.target.closest(".bt-menu")) actions.closeMenu();
};
@@ -25097,20 +25310,20 @@ function ContextMenu({ menu, roster, actions, useWork, leaving = false }) {
window.removeEventListener("keydown", onKey, true);
};
}, []);
- const [place, setPlace] = (0, import_react57.useState)({ left: menu.x, top: menu.y });
+ const [place, setPlace] = (0, import_react58.useState)({ left: menu.x, top: menu.y });
const tick = useViewport();
- (0, import_react57.useLayoutEffect)(() => {
+ (0, import_react58.useLayoutEffect)(() => {
const box = ref.current?.getBoundingClientRect();
if (!box) return;
setPlace({ left: Math.max(8, Math.min(menu.x, window.innerWidth - box.width - 8)), top: Math.max(8, Math.min(menu.y, viewBottom() - box.height - 8)) });
}, [menu.x, menu.y, tick]);
- if (menu.kind === "agent" || menu.kind === "agent-session") return (0, import_react57.createElement)(AgentMenu, { menu, roster, actions, leaving });
- if (menu.kind === "section" || menu.kind === "section-add") return (0, import_react57.createElement)(SectionMenu, { menu, roster, actions, leaving });
+ if (menu.kind === "agent" || menu.kind === "agent-session") return (0, import_react58.createElement)(AgentMenu, { menu, roster, actions, leaving });
+ if (menu.kind === "section" || menu.kind === "section-add") return (0, import_react58.createElement)(SectionMenu, { menu, roster, actions, leaving });
const bot = roster.byId[menu.id];
const room2 = roster.roomsById[menu.id];
const entry = bot ?? room2;
const waitsRaw = useWork && bot ? useWork((work) => JSON.stringify(work.waiting?.[bot.id] ?? null)) : "null";
- const waits = (0, import_react57.useMemo)(() => JSON.parse(waitsRaw), [waitsRaw]);
+ const waits = (0, import_react58.useMemo)(() => JSON.parse(waitsRaw), [waitsRaw]);
if (entry === void 0) return null;
const isMainBot = isMainOf(roster, menu.id);
const isTile = roster.mainBotId === menu.id;
@@ -25140,14 +25353,14 @@ function ContextMenu({ menu, roster, actions, useWork, leaving = false }) {
isMainBot ? null : [room2 ? t("Delete group") : t("Delete"), TrashIcon, () => bot ? actions.deleteBot(bot.id) : actions.deleteRoom(menu.id), true]
]
].map((group) => group.filter(Boolean)).filter((group) => group.length > 0);
- return (0, import_react57.createElement)(
+ return (0, import_react58.createElement)(
"div",
{ ref, className: "bt-menu", role: "menu", "aria-label": t("{name} actions", { name: bot?.name ?? room2.name }), style: place, "data-leaving": leaving || void 0 },
- groups.map((group, index) => (0, import_react57.createElement)(
- import_react57.Fragment,
+ groups.map((group, index) => (0, import_react58.createElement)(
+ import_react58.Fragment,
{ key: index },
- index > 0 ? (0, import_react57.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null,
- group.map(([label, Icon, run2, danger, checked]) => (0, import_react57.createElement)("button", {
+ index > 0 ? (0, import_react58.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null,
+ group.map(([label, Icon, run2, danger, checked]) => (0, import_react58.createElement)("button", {
key: label,
type: "button",
role: "menuitem",
@@ -25156,23 +25369,23 @@ function ContextMenu({ menu, roster, actions, useWork, leaving = false }) {
actions.closeMenu();
void Promise.resolve(run2()).catch((error) => actions.reportError(error, "menu"));
}
- }, (0, import_react57.createElement)(Icon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, label), checked ? (0, import_react57.createElement)("span", { className: "bt-menu-check" }, (0, import_react57.createElement)(CheckIcon)) : null))
+ }, (0, import_react58.createElement)(Icon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, label), checked ? (0, import_react58.createElement)("span", { className: "bt-menu-check" }, (0, import_react58.createElement)(CheckIcon)) : null))
))
);
}
function SectionMenu({ menu, roster, actions, leaving }) {
- const ref = (0, import_react57.useRef)(null);
- const trigger = (0, import_react57.useRef)(typeof document === "undefined" ? null : document.activeElement);
- (0, import_react57.useEffect)(() => {
+ const ref = (0, import_react58.useRef)(null);
+ const trigger = (0, import_react58.useRef)(typeof document === "undefined" ? null : document.activeElement);
+ (0, import_react58.useEffect)(() => {
const onKey = (event) => {
stepMenuFocus(ref.current, event, trigger.current);
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, []);
- const [place, setPlace] = (0, import_react57.useState)({ left: menu.x, top: menu.y });
+ const [place, setPlace] = (0, import_react58.useState)({ left: menu.x, top: menu.y });
const tick = useViewport();
- (0, import_react57.useLayoutEffect)(() => {
+ (0, import_react58.useLayoutEffect)(() => {
const box = ref.current?.getBoundingClientRect();
if (!box) return;
setPlace({ left: Math.max(8, Math.min(menu.x, window.innerWidth - box.width - 8)), top: Math.max(8, Math.min(menu.y, viewBottom() - box.height - 8)) });
@@ -25186,37 +25399,37 @@ function SectionMenu({ menu, roster, actions, leaving }) {
...roster.bots.filter((bot) => bot.id !== roster.mainBotId && !bot.hidden).map((bot) => ({ kind: "bot", item: bot })),
...roster.rooms.filter((room2) => !room2.hidden).map((room2) => ({ kind: "room", item: room2 }))
];
- return (0, import_react57.createElement)(
+ return (0, import_react58.createElement)(
"div",
{ ref, className: "bt-menu bt-sec-add-menu", role: "menu", "aria-label": t("Add to {name}", { name: sec.name }), style: place, "data-leaving": leaving || void 0 },
- (0, import_react57.createElement)("button", {
+ (0, import_react58.createElement)("button", {
type: "button",
role: "menuitem",
onClick: () => {
actions.closeMenu();
actions.openNewChat("create", sec.id);
}
- }, (0, import_react57.createElement)(PlusIcon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, t("Create new Bot"))),
- (0, import_react57.createElement)("button", {
+ }, (0, import_react58.createElement)(PlusIcon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, t("Create new Bot"))),
+ (0, import_react58.createElement)("button", {
type: "button",
role: "menuitem",
onClick: () => {
actions.closeMenu();
actions.openNewChat("group", sec.id);
}
- }, (0, import_react57.createElement)(PeopleIcon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, t("Create group chat"))),
- candidates.length > 0 ? (0, import_react57.createElement)(
- import_react57.Fragment,
+ }, (0, import_react58.createElement)(PeopleIcon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, t("Create group chat"))),
+ candidates.length > 0 ? (0, import_react58.createElement)(
+ import_react58.Fragment,
null,
- (0, import_react57.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
- (0, import_react57.createElement)("div", { className: "bt-menu-sub-head" }, t("Add existing")),
- (0, import_react57.createElement)(
+ (0, import_react58.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
+ (0, import_react58.createElement)("div", { className: "bt-menu-sub-head" }, t("Add existing")),
+ (0, import_react58.createElement)(
"div",
{ className: "bt-sec-add-list" },
candidates.map(({ kind, item }) => {
const inside = item.sectionId === sec.id;
const otherSec = item.sectionId && !inside ? sections.find((s) => s.id === item.sectionId)?.name : void 0;
- return (0, import_react57.createElement)(
+ return (0, import_react58.createElement)(
"button",
{
key: item.id,
@@ -25227,9 +25440,9 @@ function SectionMenu({ menu, roster, actions, leaving }) {
void Promise.resolve(actions.setFlags(item.id, { sectionId: inside ? null : sec.id })).catch((error) => actions.reportError(error, "menu"));
}
},
- kind === "room" ? (0, import_react57.createElement)(RoomAvatar, { room: item, roster, size: 18 }) : (0, import_react57.createElement)(BotMark, { bot: item, size: 18 }),
- (0, import_react57.createElement)("span", { className: "bt-menu-label" }, item.name),
- inside ? (0, import_react57.createElement)("span", { className: "bt-menu-check" }, (0, import_react57.createElement)(CheckIcon)) : otherSec ? (0, import_react57.createElement)("span", { className: "bt-menu-hint" }, otherSec) : null
+ kind === "room" ? (0, import_react58.createElement)(RoomAvatar, { room: item, roster, size: 18 }) : (0, import_react58.createElement)(BotMark, { bot: item, size: 18 }),
+ (0, import_react58.createElement)("span", { className: "bt-menu-label" }, item.name),
+ inside ? (0, import_react58.createElement)("span", { className: "bt-menu-check" }, (0, import_react58.createElement)(CheckIcon)) : otherSec ? (0, import_react58.createElement)("span", { className: "bt-menu-hint" }, otherSec) : null
);
})
)
@@ -25244,31 +25457,31 @@ function SectionMenu({ menu, roster, actions, leaving }) {
next.splice(target, 0, picked);
void Promise.resolve(actions.reorderSections(next)).catch((error) => actions.reportError(error, "menu"));
};
- return (0, import_react57.createElement)(
+ return (0, import_react58.createElement)(
"div",
{ ref, className: "bt-menu", role: "menu", "aria-label": t("{name} actions", { name: sec.name }), style: place, "data-leaving": leaving || void 0 },
- (0, import_react57.createElement)("button", {
+ (0, import_react58.createElement)("button", {
type: "button",
role: "menuitem",
onClick: () => {
actions.closeMenu();
actions.beginSectionRename(sec.id);
}
- }, (0, import_react57.createElement)(PencilIcon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, t("Rename section"))),
- (0, import_react57.createElement)("button", {
+ }, (0, import_react58.createElement)(PencilIcon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, t("Rename section"))),
+ (0, import_react58.createElement)("button", {
type: "button",
role: "menuitem",
onClick: () => {
actions.closeMenu();
actions.openNewChat("create", sec.id);
}
- }, (0, import_react57.createElement)(PlusIcon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, t("Create new Bot"))),
- (0, import_react57.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
- (0, import_react57.createElement)("div", { className: "bt-menu-sub-head" }, t("Section color")),
- (0, import_react57.createElement)(
+ }, (0, import_react58.createElement)(PlusIcon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, t("Create new Bot"))),
+ (0, import_react58.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
+ (0, import_react58.createElement)("div", { className: "bt-menu-sub-head" }, t("Section color")),
+ (0, import_react58.createElement)(
"div",
{ className: "bt-menu-colors" },
- (0, import_react57.createElement)("button", {
+ (0, import_react58.createElement)("button", {
type: "button",
className: "bt-menu-color-dot",
"aria-label": t("None"),
@@ -25280,7 +25493,7 @@ function SectionMenu({ menu, roster, actions, leaving }) {
void Promise.resolve(actions.saveSection({ id: sec.id, color: null })).catch((error) => actions.reportError(error, "menu"));
}
}),
- SECTION_COLORS.map((color) => (0, import_react57.createElement)("button", {
+ SECTION_COLORS.map((color) => (0, import_react58.createElement)("button", {
key: color,
type: "button",
className: "bt-menu-color-dot",
@@ -25294,16 +25507,16 @@ function SectionMenu({ menu, roster, actions, leaving }) {
}
}))
),
- index > 0 ? (0, import_react57.createElement)("button", { type: "button", role: "menuitem", onClick: () => {
+ index > 0 ? (0, import_react58.createElement)("button", { type: "button", role: "menuitem", onClick: () => {
actions.closeMenu();
move(-1);
- } }, (0, import_react57.createElement)(FolderIcon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, t("Move section up"))) : null,
- index < sections.length - 1 ? (0, import_react57.createElement)("button", { type: "button", role: "menuitem", onClick: () => {
+ } }, (0, import_react58.createElement)(FolderIcon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, t("Move section up"))) : null,
+ index < sections.length - 1 ? (0, import_react58.createElement)("button", { type: "button", role: "menuitem", onClick: () => {
actions.closeMenu();
move(1);
- } }, (0, import_react57.createElement)(FolderIcon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, t("Move section down"))) : null,
- (0, import_react57.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
- (0, import_react57.createElement)("button", {
+ } }, (0, import_react58.createElement)(FolderIcon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, t("Move section down"))) : null,
+ (0, import_react58.createElement)("div", { className: "bt-menu-sep", role: "separator" }),
+ (0, import_react58.createElement)("button", {
type: "button",
role: "menuitem",
className: "bt-danger",
@@ -25311,22 +25524,22 @@ function SectionMenu({ menu, roster, actions, leaving }) {
actions.closeMenu();
void Promise.resolve(actions.deleteSection(sec.id)).catch((error) => actions.reportError(error, "menu"));
}
- }, (0, import_react57.createElement)(TrashIcon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, t("Ungroup section")))
+ }, (0, import_react58.createElement)(TrashIcon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, t("Ungroup section")))
);
}
function AgentMenu({ menu, roster, actions, leaving }) {
- const ref = (0, import_react57.useRef)(null);
- const trigger = (0, import_react57.useRef)(typeof document === "undefined" ? null : document.activeElement);
- (0, import_react57.useEffect)(() => {
+ const ref = (0, import_react58.useRef)(null);
+ const trigger = (0, import_react58.useRef)(typeof document === "undefined" ? null : document.activeElement);
+ (0, import_react58.useEffect)(() => {
const onKey = (event) => {
stepMenuFocus(ref.current, event, trigger.current);
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, []);
- const [place, setPlace] = (0, import_react57.useState)({ left: menu.x, top: menu.y });
+ const [place, setPlace] = (0, import_react58.useState)({ left: menu.x, top: menu.y });
const tick = useViewport();
- (0, import_react57.useLayoutEffect)(() => {
+ (0, import_react58.useLayoutEffect)(() => {
const box = ref.current?.getBoundingClientRect();
if (!box) return;
setPlace({ left: Math.max(8, Math.min(menu.x, window.innerWidth - box.width - 8)), top: Math.max(8, Math.min(menu.y, viewBottom() - box.height - 8)) });
@@ -25349,14 +25562,14 @@ function AgentMenu({ menu, roster, actions, leaving }) {
[t("Archive"), TrashIcon, () => actions.archiveAgentSession(agent.id, menu.id), true]
]
];
- return (0, import_react57.createElement)(
+ return (0, import_react58.createElement)(
"div",
{ ref, className: "bt-menu", role: "menu", "aria-label": menu.kind === "agent" ? "DSH Agent" : t("Session actions"), style: place, "data-leaving": leaving || void 0 },
- groups.map((group, index) => (0, import_react57.createElement)(
- import_react57.Fragment,
+ groups.map((group, index) => (0, import_react58.createElement)(
+ import_react58.Fragment,
{ key: index },
- index > 0 ? (0, import_react57.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null,
- group.map(([label, Icon, run2, danger, checked]) => (0, import_react57.createElement)("button", {
+ index > 0 ? (0, import_react58.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null,
+ group.map(([label, Icon, run2, danger, checked]) => (0, import_react58.createElement)("button", {
key: label,
type: "button",
role: "menuitem",
@@ -25365,13 +25578,13 @@ function AgentMenu({ menu, roster, actions, leaving }) {
actions.closeMenu();
void Promise.resolve(run2()).catch((error) => console.warn("[ds-bot]", error));
}
- }, (0, import_react57.createElement)(Icon), (0, import_react57.createElement)("span", { className: "bt-menu-label" }, label), checked ? (0, import_react57.createElement)("span", { className: "bt-menu-check" }, (0, import_react57.createElement)(CheckIcon)) : null))
+ }, (0, import_react58.createElement)(Icon), (0, import_react58.createElement)("span", { className: "bt-menu-label" }, label), checked ? (0, import_react58.createElement)("span", { className: "bt-menu-check" }, (0, import_react58.createElement)(CheckIcon)) : null))
))
);
}
// src/client/member-status.js
-var import_react58 = require("react");
+var import_react59 = require("react");
var NO_WORK = { bots: {}, rooms: {}, approvals: [] };
var FACES_MAX2 = 3;
var DOCK_EXIT_MS = 160;
@@ -25432,15 +25645,15 @@ function dockModel(sessionId, roster, work) {
};
}
function Face({ bot, ask, state }) {
- return (0, import_react58.createElement)(
+ return (0, import_react59.createElement)(
"span",
{ className: "bt-mw-face", "data-ask": ask || void 0 },
- (0, import_react58.createElement)(BotMark, { bot, size: 20, state: ask ? "alert" : state })
+ (0, import_react59.createElement)(BotMark, { bot, size: 20, state: ask ? "alert" : state })
);
}
function useFitWidth(inner, key) {
- const [width, setWidth] = (0, import_react58.useState)(null);
- (0, import_react58.useLayoutEffect)(() => {
+ const [width, setWidth] = (0, import_react59.useState)(null);
+ (0, import_react59.useLayoutEffect)(() => {
setWidth(key && inner.current ? inner.current.offsetWidth : null);
}, [key]);
return width;
@@ -25451,93 +25664,93 @@ function MemberDock({ sessionId, useRoster, useWork, actions }) {
const live = dockModel(sessionId, roster, work);
const [kept, leaving] = useLinger(live ? JSON.stringify(live) : null, DOCK_EXIT_MS);
const model = kept ? JSON.parse(kept) : null;
- const inner = (0, import_react58.useRef)(null);
+ const inner = (0, import_react59.useRef)(null);
const width = useFitWidth(inner, kept);
if (!model) return null;
const faces = model.faces.map((face) => ({ ...face, bot: roster.byId[face.id] })).filter((face) => face.bot);
const label = [model.waiting, model.doing].filter(Boolean).join(" · ");
const open = () => model.open.details ? actions.showDetails(model.open.details) : actions.openSession(model.open.session);
- return (0, import_react58.createElement)(
+ return (0, import_react59.createElement)(
"div",
{ className: "bt-mw-dock", "data-leaving": leaving || void 0 },
- (0, import_react58.createElement)(
+ (0, import_react59.createElement)(
"button",
{ type: "button", className: "bt-mw-pill", "aria-label": label, onClick: open, disabled: leaving, style: width ? { width } : void 0 },
- (0, import_react58.createElement)(
+ (0, import_react59.createElement)(
"span",
{ ref: inner, className: "bt-mw-pill-in" },
- (0, import_react58.createElement)("span", { className: "bt-mw-faces", "aria-hidden": true }, faces.map((face) => (0, import_react58.createElement)(Face, { key: face.id, ...face }))),
- (0, import_react58.createElement)(
+ (0, import_react59.createElement)("span", { className: "bt-mw-faces", "aria-hidden": true }, faces.map((face) => (0, import_react59.createElement)(Face, { key: face.id, ...face }))),
+ (0, import_react59.createElement)(
"span",
{ key: label, className: "bt-mw-label", "aria-hidden": true },
- model.waiting ? (0, import_react58.createElement)("span", { className: "bt-mw-ask" }, model.waiting) : null,
- model.waiting && model.doing ? (0, import_react58.createElement)("span", { className: "bt-mw-dot" }, "·") : null,
- model.doing ? (0, import_react58.createElement)("span", { className: "bt-mw-doing" }, (0, import_react58.createElement)(Shimmer, null, model.doing)) : null
+ model.waiting ? (0, import_react59.createElement)("span", { className: "bt-mw-ask" }, model.waiting) : null,
+ model.waiting && model.doing ? (0, import_react59.createElement)("span", { className: "bt-mw-dot" }, "·") : null,
+ model.doing ? (0, import_react59.createElement)("span", { className: "bt-mw-doing" }, (0, import_react59.createElement)(Shimmer, null, model.doing)) : null
)
)
)
);
}
-var stateLine = (className, at, ...what) => (0, import_react58.createElement)(
+var stateLine = (className, at, ...what) => (0, import_react59.createElement)(
"span",
{ className },
- (0, import_react58.createElement)("span", { className: "bt-member-what" }, ...what),
- typeof at === "number" ? (0, import_react58.createElement)(Elapsed, { at, className: "bt-member-time" }) : null
+ (0, import_react59.createElement)("span", { className: "bt-member-what" }, ...what),
+ typeof at === "number" ? (0, import_react59.createElement)(Elapsed, { at, className: "bt-member-time" }) : null
);
function ApprovalCard({ approval, bot, actions }) {
- const [busy, setBusy] = (0, import_react58.useState)(false);
+ const [busy, setBusy] = (0, import_react59.useState)(false);
const answer = (choice) => {
setBusy(true);
void Promise.resolve(actions.answerApproval(approval.id, choice)).catch((error) => actions.reportError(error, "approval")).finally(() => setBusy(false));
};
- return (0, import_react58.createElement)(
+ return (0, import_react59.createElement)(
"div",
{ className: "bt-mw-card", role: "group", "aria-label": t("{name} is waiting for your approval", { name: bot.name }) },
- (0, import_react58.createElement)("div", { className: "bt-mw-tool" }, approval.tool),
- approval.detail?.text ? (0, import_react58.createElement)("div", { className: "bt-mw-text" }, approval.detail.text) : null,
- approval.reason ? (0, import_react58.createElement)("div", { className: "bt-mw-reason" }, approval.reason) : null,
- approval.detail?.code ? (0, import_react58.createElement)("code", { className: "bt-mw-code", title: approval.detail.code }, approval.detail.code) : null,
+ (0, import_react59.createElement)("div", { className: "bt-mw-tool" }, approval.tool),
+ approval.detail?.text ? (0, import_react59.createElement)("div", { className: "bt-mw-text" }, approval.detail.text) : null,
+ approval.reason ? (0, import_react59.createElement)("div", { className: "bt-mw-reason" }, approval.reason) : null,
+ approval.detail?.code ? (0, import_react59.createElement)("code", { className: "bt-mw-code", title: approval.detail.code }, approval.detail.code) : null,
// Own-chat approvals are answerable for IM and the phone app; here the Bot's
// own DSH card stays the place to answer, so the row still opens that chat.
- approval.answerable && approval.roomId !== void 0 ? (0, import_react58.createElement)(
+ approval.answerable && approval.roomId !== void 0 ? (0, import_react59.createElement)(
"div",
{ className: "bt-mw-actions" },
- (0, import_react58.createElement)("button", { type: "button", className: "bt-q-btn", disabled: busy, onClick: () => answer("reject") }, t("Reject")),
- (0, import_react58.createElement)("button", { type: "button", className: "bt-q-submit", disabled: busy, onClick: () => answer("allow") }, t("Allow once"))
- ) : (0, import_react58.createElement)(
+ (0, import_react59.createElement)("button", { type: "button", className: "bt-q-btn", disabled: busy, onClick: () => answer("reject") }, t("Reject")),
+ (0, import_react59.createElement)("button", { type: "button", className: "bt-q-submit", disabled: busy, onClick: () => answer("allow") }, t("Allow once"))
+ ) : (0, import_react59.createElement)(
"div",
{ className: "bt-mw-actions" },
- (0, import_react58.createElement)("button", { type: "button", className: "bt-q-btn", onClick: () => actions.openSession(bot.id) }, t("Open {name}'s chat", { name: bot.name }))
+ (0, import_react59.createElement)("button", { type: "button", className: "bt-q-btn", onClick: () => actions.openSession(bot.id) }, t("Open {name}'s chat", { name: bot.name }))
)
);
}
function MemberState({ entry, bot }) {
if (entry?.state === "ask") return stateLine("bt-member-state bt-mw-ask", entry.approvals[0].at, t("Waiting for your approval"));
if (entry?.state !== "work") return bot.role ? stateLine("bt-member-state", void 0, bot.role) : null;
- return stateLine("bt-member-state", entry.doing.since, (0, import_react58.createElement)(Shimmer, null, `${workPhrase(entry.doing)}…`));
+ return stateLine("bt-member-state", entry.doing.since, (0, import_react59.createElement)(Shimmer, null, `${workPhrase(entry.doing)}…`));
}
function StopMemberWork({ entry, bot, room: room2, actions }) {
- const [stopping, setStopping] = (0, import_react58.useState)(false);
+ const [stopping, setStopping] = (0, import_react59.useState)(false);
if (!entry?.here || entry.state !== "work" && entry.state !== "ask") return null;
const stop = () => {
setStopping(true);
void Promise.resolve(actions.stopMemberWork(room2.id, bot.id)).catch((error) => actions.reportError(error, "stop")).finally(() => setStopping(false));
};
- return (0, import_react58.createElement)("button", { type: "button", className: "bt-member-stop", disabled: stopping, "aria-label": `${t("Stop")} · ${bot.name}`, onClick: stop }, t("Stop"));
+ return (0, import_react59.createElement)("button", { type: "button", className: "bt-member-stop", disabled: stopping, "aria-label": `${t("Stop")} · ${bot.name}`, onClick: stop }, t("Stop"));
}
function StopRoomWork({ room: room2, entries: entries2, actions }) {
- const [stopping, setStopping] = (0, import_react58.useState)(false);
+ const [stopping, setStopping] = (0, import_react59.useState)(false);
if (!entries2.some((entry) => entry.here)) return null;
const stop = () => {
setStopping(true);
void Promise.resolve(actions.stopRoomWork(room2.id)).catch((error) => actions.reportError(error, "stop")).finally(() => setStopping(false));
};
const label = t("Stop all work in this group");
- return (0, import_react58.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: stopping, "aria-label": label, title: label, onClick: stop }, t("Stop all"));
+ return (0, import_react59.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: stopping, "aria-label": label, title: label, onClick: stop }, t("Stop all"));
}
function MemberApprovals({ entry, bot, actions }) {
if (entry?.state !== "ask") return null;
- return (0, import_react58.createElement)("div", { className: "bt-member-cards" }, entry.approvals.map((approval) => (0, import_react58.createElement)(ApprovalCard, { key: approval.id, approval, bot, actions })));
+ return (0, import_react59.createElement)("div", { className: "bt-member-cards" }, entry.approvals.map((approval) => (0, import_react59.createElement)(ApprovalCard, { key: approval.id, approval, bot, actions })));
}
function useMemberWork(room2, useWork) {
const work = useWork?.((value) => value) ?? NO_WORK;
@@ -25601,7 +25814,7 @@ body[data-ds-dark-theme] .bt-member-state.bt-mw-ask{color:#f0b84a}
`;
// src/client/details-drawer.js
-var import_react59 = require("react");
+var import_react60 = require("react");
function transcriptOf(list, id, name, hiddenTurns = []) {
const outline = list.projectionsBySession?.[id]?.values?.turnOutline ?? list.byId[id]?.projectionValues?.turnOutline;
if (!Array.isArray(outline)) return "";
@@ -25626,17 +25839,17 @@ var EMPTY_TABS = { ids: [], active: null };
function PermissionRow({ bot, roster, actions, run: run2 }) {
const catalog = roster.permissions;
if (!catalog?.options?.length) return null;
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
{ className: "bt-drawer-permission" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Permissions")),
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Permissions")),
// A Bot without its own preset may run on another one set in DSH, so its first pick always applies.
- (0, import_react59.createElement)(PermissionPicker, { catalog, saved: bot.permission ?? catalog.defaultPreset, repick: bot.permission === void 0, onPick: (permission) => run2(actions.updateBot(bot.id, { permission })) })
+ (0, import_react60.createElement)(PermissionPicker, { catalog, saved: bot.permission ?? catalog.defaultPreset, repick: bot.permission === void 0, onPick: (permission) => run2(actions.updateBot(bot.id, { permission })) })
);
}
function RunStats({ bot, part, running, actions }) {
- const [values, setValues] = (0, import_react59.useState)(null);
- (0, import_react59.useEffect)(() => {
+ const [values, setValues] = (0, import_react60.useState)(null);
+ (0, import_react60.useEffect)(() => {
if (!actions.runStats) return void 0;
let current = true;
actions.runStats(bot.id).then(
@@ -25653,56 +25866,56 @@ function RunStats({ bot, part, running, actions }) {
}, [bot.id, part, running]);
const shown = runStatsOf(values);
if (shown.length === 0) return null;
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
{ className: "bt-run-stats" },
- shown.map((entry, index) => (0, import_react59.createElement)(
- import_react59.Fragment,
+ shown.map((entry, index) => (0, import_react60.createElement)(
+ import_react60.Fragment,
{ key: entry.key },
- index > 0 ? (0, import_react59.createElement)("span", { className: "bt-run-sep", "aria-hidden": true }, "·") : null,
- (0, import_react59.createElement)("span", { title: entry.title }, entry.text)
+ index > 0 ? (0, import_react60.createElement)("span", { className: "bt-run-sep", "aria-hidden": true }, "·") : null,
+ (0, import_react60.createElement)("span", { title: entry.title }, entry.text)
))
);
}
function BrowserCards({ bot, sessionId, roster, actions, useBrowserTabs, useBrowserPages }) {
const state = useBrowserTabs((map) => map[bot.id] ?? EMPTY_TABS);
const pages = useBrowserPages((map) => map);
- (0, import_react59.useEffect)(() => {
+ (0, import_react60.useEffect)(() => {
actions.browserEnsure?.(bot.id);
}, [bot.id]);
if (roster.browser !== true || !actions.browserShow) {
- return (0, import_react59.createElement)("div", { className: "bt-muted" }, t("The browser is in DSH Desktop and the DS Bot app."));
+ return (0, import_react60.createElement)("div", { className: "bt-muted" }, t("The browser is in DSH Desktop and the DS Bot app."));
}
if (state.ids.length === 0) {
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
{ className: "bt-browser-empty-mark" },
- (0, import_react59.createElement)(BotMark, { bot, size: 40, state: "idle", live: true }),
- (0, import_react59.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })),
- (0, import_react59.createElement)("div", { className: "bt-muted" }, t("Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.", { name: bot.name })),
- (0, import_react59.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => actions.openBrowser(sessionId) }, t("Open browser"))
+ (0, import_react60.createElement)(BotMark, { bot, size: 40, state: "idle", live: true }),
+ (0, import_react60.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })),
+ (0, import_react60.createElement)("div", { className: "bt-muted" }, t("Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.", { name: bot.name })),
+ (0, import_react60.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => actions.openBrowser(sessionId) }, t("Open browser"))
);
}
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
{ className: "bt-bcards" },
state.ids.map((tabId, index) => {
const page = pages[tabId] ?? {};
const label = page.title || shortUrl(page.url) || t("New tab");
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
{ key: tabId, className: "bt-bcard", "data-active": state.active === tabId || void 0, style: { animationDelay: `${index * 30}ms` } },
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"button",
{ type: "button", className: "bt-bcard-shot", "aria-label": t("Open {title}", { title: label }), title: page.url, onClick: () => actions.browserPick(sessionId, tabId) },
- page.excerpt ? (0, import_react59.createElement)(
+ page.excerpt ? (0, import_react60.createElement)(
"span",
{ className: "bt-bcard-preview" },
- (0, import_react59.createElement)("span", { className: "bt-bcard-ptitle" }, label),
- (0, import_react59.createElement)("span", { className: "bt-bcard-excerpt" }, page.excerpt)
- ) : (0, import_react59.createElement)("span", { className: "bt-bcard-blank" }, (0, import_react59.createElement)(GlobeIcon2), (0, import_react59.createElement)("span", null, label))
+ (0, import_react60.createElement)("span", { className: "bt-bcard-ptitle" }, label),
+ (0, import_react60.createElement)("span", { className: "bt-bcard-excerpt" }, page.excerpt)
+ ) : (0, import_react60.createElement)("span", { className: "bt-bcard-blank" }, (0, import_react60.createElement)(GlobeIcon2), (0, import_react60.createElement)("span", null, label))
),
- (0, import_react59.createElement)("button", {
+ (0, import_react60.createElement)("button", {
type: "button",
className: "bt-bcard-x",
"aria-label": t("Close tab"),
@@ -25711,29 +25924,29 @@ function BrowserCards({ bot, sessionId, roster, actions, useBrowserTabs, useBrow
void actions.browserCloseTab(bot.id, tabId);
}
}, "×"),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ className: "bt-bcard-row" },
- (0, import_react59.createElement)(Favicon, { src: page.favicon, className: "bt-bcard-fav" }),
- (0, import_react59.createElement)("span", { className: "bt-bcard-title" }, label),
- page.url ? (0, import_react59.createElement)("span", { className: "bt-bcard-host" }, hostOf2(page.url)) : null
+ (0, import_react60.createElement)(Favicon, { src: page.favicon, className: "bt-bcard-fav" }),
+ (0, import_react60.createElement)("span", { className: "bt-bcard-title" }, label),
+ page.url ? (0, import_react60.createElement)("span", { className: "bt-bcard-host" }, hostOf2(page.url)) : null
)
);
}),
- (0, import_react59.createElement)("button", { type: "button", className: "bt-bcard-new", style: { animationDelay: `${state.ids.length * 30}ms` }, onClick: () => actions.browserNewTab(sessionId) }, (0, import_react59.createElement)(PlusIcon), t("New tab"))
+ (0, import_react60.createElement)("button", { type: "button", className: "bt-bcard-new", style: { animationDelay: `${state.ids.length * 30}ms` }, onClick: () => actions.browserNewTab(sessionId) }, (0, import_react60.createElement)(PlusIcon), t("New tab"))
);
}
function About({ text, title = "About" }) {
- const [open, setOpen] = (0, import_react59.useState)(false);
+ const [open, setOpen] = (0, import_react60.useState)(false);
const long = text.split("\n").length > 5 || text.length > 240;
- const body = (0, import_react59.useRef)(null);
+ const body = (0, import_react60.useRef)(null);
useMorph(body, open);
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
null,
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t(title)),
- (0, import_react59.createElement)("div", { ref: body, className: "bt-about", "data-open": open || void 0 }, text),
- long ? (0, import_react59.createElement)("button", { type: "button", className: "bt-more", onClick: () => setOpen((value) => !value) }, open ? t("Show less") : t("Show more")) : null
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t(title)),
+ (0, import_react60.createElement)("div", { ref: body, className: "bt-about", "data-open": open || void 0 }, text),
+ long ? (0, import_react60.createElement)("button", { type: "button", className: "bt-more", onClick: () => setOpen((value) => !value) }, open ? t("Show less") : t("Show more")) : null
);
}
var PILE_MAX = 4;
@@ -25741,57 +25954,57 @@ function MemberPile({ room: room2, roster }) {
const members = room2.members.map((id) => roster.byId[id]).filter(Boolean);
const shown = members.length > PILE_MAX ? members.slice(0, PILE_MAX - 1) : members;
const more = members.length - shown.length;
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"span",
{ className: "bt-pile", "aria-hidden": true },
- shown.map((bot, index) => (0, import_react59.createElement)("span", { key: bot.id, className: "bt-pile-face", style: { animationDelay: `${index * 40}ms` } }, (0, import_react59.createElement)(BotMark, { bot, size: 44, live: true }))),
- more > 0 ? (0, import_react59.createElement)("span", { key: "more", className: "bt-pile-face bt-pile-more", style: { animationDelay: `${shown.length * 40}ms` } }, `+${more}`) : null
+ shown.map((bot, index) => (0, import_react60.createElement)("span", { key: bot.id, className: "bt-pile-face", style: { animationDelay: `${index * 40}ms` } }, (0, import_react60.createElement)(BotMark, { bot, size: 44, live: true }))),
+ more > 0 ? (0, import_react60.createElement)("span", { key: "more", className: "bt-pile-face bt-pile-more", style: { animationDelay: `${shown.length * 40}ms` } }, `+${more}`) : null
);
}
var markOf = (entry) => entry?.state === "ask" ? "alert" : entry?.state === "work" ? workState(entry.doing) : "idle";
function MemberRow({ member, entry, room: room2, roster, actions }) {
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
{ role: "listitem", className: "bt-member" },
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ className: "bt-member-row" },
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"button",
{ type: "button", className: "bt-member-open", title: t("Open {name}'s chat", { name: member.name }), onClick: () => actions.openSession(member.id) },
- (0, import_react59.createElement)(BotMark, { bot: member, size: 32, state: markOf(entry) }),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(BotMark, { bot: member, size: 32, state: markOf(entry) }),
+ (0, import_react60.createElement)(
"span",
{ className: "bt-member-text" },
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"span",
{ className: "bt-member-line" },
- (0, import_react59.createElement)("span", { className: "bt-member-name" }, member.name),
- room2.admin === member.id ? (0, import_react59.createElement)("span", { className: "bt-tag" }, t("Admin")) : null
+ (0, import_react60.createElement)("span", { className: "bt-member-name" }, member.name),
+ room2.admin === member.id ? (0, import_react60.createElement)("span", { className: "bt-tag" }, t("Admin")) : null
),
- (0, import_react59.createElement)(MemberState, { entry, bot: member, room: room2, roster })
+ (0, import_react60.createElement)(MemberState, { entry, bot: member, room: room2, roster })
)
),
- (0, import_react59.createElement)(StopMemberWork, { entry, bot: member, room: room2, actions })
+ (0, import_react60.createElement)(StopMemberWork, { entry, bot: member, room: room2, actions })
),
- (0, import_react59.createElement)(MemberApprovals, { entry, bot: member, actions })
+ (0, import_react60.createElement)(MemberApprovals, { entry, bot: member, actions })
);
}
function GroupOverview({ room: room2, roster, actions, usage, useWork, openSettings }) {
const members = room2.members.map((id) => roster.byId[id]).filter(Boolean);
const { entries: entries2 } = useMemberWork(room2, useWork);
return [
- room2.notice ? (0, import_react59.createElement)(About, { key: "notice", title: "Notice", text: room2.notice }) : (0, import_react59.createElement)("button", { key: "notice", type: "button", className: "bt-more", onClick: openSettings }, t("Add a notice in group settings")),
- (0, import_react59.createElement)(
+ room2.notice ? (0, import_react60.createElement)(About, { key: "notice", title: "Notice", text: room2.notice }) : (0, import_react60.createElement)("button", { key: "notice", type: "button", className: "bt-more", onClick: openSettings }, t("Add a notice in group settings")),
+ (0, import_react60.createElement)(
"div",
{ key: "members" },
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ className: "bt-members-head" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Members · {count}", { count: members.length })),
- (0, import_react59.createElement)(StopRoomWork, { room: room2, entries: entries2, actions })
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Members · {count}", { count: members.length })),
+ (0, import_react60.createElement)(StopRoomWork, { room: room2, entries: entries2, actions })
),
- (0, import_react59.createElement)("div", { className: "bt-members", role: "list" }, members.map((member) => (0, import_react59.createElement)(MemberRow, {
+ (0, import_react60.createElement)("div", { className: "bt-members", role: "list" }, members.map((member) => (0, import_react60.createElement)(MemberRow, {
key: member.id,
member,
entry: entries2.find((item) => item.id === member.id),
@@ -25800,16 +26013,16 @@ function GroupOverview({ room: room2, roster, actions, usage, useWork, openSetti
actions
})))
),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ key: "goal" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Goal")),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Goal")),
+ (0, import_react60.createElement)(
"div",
{ className: "bt-kv" },
room2.goal ? [
- (0, import_react59.createElement)("span", { key: "t" }, room2.goal.title, " ", (0, import_react59.createElement)("span", { className: "bt-note" }, goalView(room2.goal, { roster })?.barLabel ?? "")),
- (0, import_react59.createElement)("button", {
+ (0, import_react60.createElement)("span", { key: "t" }, room2.goal.title, " ", (0, import_react60.createElement)("span", { className: "bt-note" }, goalView(room2.goal, { roster })?.barLabel ?? "")),
+ (0, import_react60.createElement)("button", {
key: "s",
type: "button",
className: "bt-soft bt-soft-sm",
@@ -25818,7 +26031,7 @@ function GroupOverview({ room: room2, roster, actions, usage, useWork, openSetti
if (typeof document !== "undefined" && document.querySelector("[data-rightbar-fullscreen]")) actions.closeOverlay();
}
}, t("Show"))
- ] : (0, import_react59.createElement)("button", {
+ ] : (0, import_react60.createElement)("button", {
type: "button",
className: "bt-soft bt-soft-sm",
disabled: !canSetGoal(room2, roster),
@@ -25827,24 +26040,24 @@ function GroupOverview({ room: room2, roster, actions, usage, useWork, openSetti
}, t("Set a goal"))
)
),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ key: "mode" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Who answers")),
- (0, import_react59.createElement)("div", { className: "bt-kv" }, (0, import_react59.createElement)("span", null, t(ROOM_MODES.find(([id]) => id === shownMode(room2, roster))?.[1] ?? "Everyone")))
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Who answers")),
+ (0, import_react60.createElement)("div", { className: "bt-kv" }, (0, import_react60.createElement)("span", null, t(ROOM_MODES.find(([id]) => id === shownMode(room2, roster))?.[1] ?? "Everyone")))
),
- room2.permission ? (0, import_react59.createElement)(
+ room2.permission ? (0, import_react60.createElement)(
"div",
{ key: "permission" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Permissions")),
- (0, import_react59.createElement)("div", { className: "bt-kv" }, (0, import_react59.createElement)("span", { className: presetDanger(room2.permission) ? "bt-perm-danger" : void 0 }, presetName(room2.permission, roster.permissions)))
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Permissions")),
+ (0, import_react60.createElement)("div", { className: "bt-kv" }, (0, import_react60.createElement)("span", { className: presetDanger(room2.permission) ? "bt-perm-danger" : void 0 }, presetName(room2.permission, roster.permissions)))
) : null,
- roster.memory === false ? null : (0, import_react59.createElement)(MemoryRow, { key: "memory", owner: { id: room2.id, name: room2.name, group: true }, actions }),
- usage ? (0, import_react59.createElement)(
+ roster.memory === false ? null : (0, import_react60.createElement)(MemoryRow, { key: "memory", owner: { id: room2.id, name: room2.name, group: true }, actions }),
+ usage ? (0, import_react60.createElement)(
"div",
{ key: "usage" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Usage")),
- (0, import_react59.createElement)("div", { className: "bt-kv" }, (0, import_react59.createElement)("span", null, room2.name), (0, import_react59.createElement)("span", null, usage))
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Usage")),
+ (0, import_react60.createElement)("div", { className: "bt-kv" }, (0, import_react60.createElement)("span", null, room2.name), (0, import_react60.createElement)("span", null, usage))
) : null
];
}
@@ -25852,21 +26065,21 @@ function AgentSessions({ bot, part, run: run2, useSessions }) {
const ids = [part, ...(bot.parts ?? []).filter((id) => id !== part).slice().reverse()];
const rows2 = useSessions((list) => ids.map((id) => list.byId?.[id]), rowsEqual);
const total = ids.length;
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"div",
{ className: "bt-drawer-model" },
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ className: "bt-agent-sessions-head" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Sessions")),
- (0, import_react59.createElement)("button", { type: "button", className: "bt-agent-sessions-new", onClick: () => run2(call("bot-new-part", { botId: bot.id })) }, (0, import_react59.createElement)(PlusIcon), t("New session"))
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Sessions")),
+ (0, import_react60.createElement)("button", { type: "button", className: "bt-agent-sessions-new", onClick: () => run2(call("bot-new-part", { botId: bot.id })) }, (0, import_react60.createElement)(PlusIcon), t("New session"))
),
- (0, import_react59.createElement)("div", { className: "bt-agent-sessions" }, ids.map((id, index) => {
+ (0, import_react60.createElement)("div", { className: "bt-agent-sessions" }, ids.map((id, index) => {
const row = rows2[index];
const current = index === 0;
const when3 = row?.updatedAt ?? row?.createdAt;
const label = row?.title && row.title.trim() !== "" ? row.title : t("Session {number}", { number: total - index });
- return (0, import_react59.createElement)(
+ return (0, import_react60.createElement)(
"button",
{
key: id,
@@ -25876,8 +26089,8 @@ function AgentSessions({ bot, part, run: run2, useSessions }) {
title: current ? t("Current session") : t("Open this earlier session"),
onClick: current ? void 0 : () => run2(call("bot-open-part", { botId: bot.id, sessionId: id }))
},
- (0, import_react59.createElement)("span", { className: "bt-agent-session-name" }, label),
- (0, import_react59.createElement)("span", { className: "bt-agent-session-meta" }, current ? t("Current") : when3 ? new Date(when3).toLocaleString(void 0, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) : "")
+ (0, import_react60.createElement)("span", { className: "bt-agent-session-name" }, label),
+ (0, import_react60.createElement)("span", { className: "bt-agent-session-meta" }, current ? t("Current") : when3 ? new Date(when3).toLocaleString(void 0, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) : "")
);
}))
);
@@ -25887,15 +26100,15 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a
const owner = roster.byId[sessionId];
const part = owner ? currentPart(owner) : sessionId;
const isMainBot = isMainOf(roster, owner?.id);
- const [tab, setTab] = (0, import_react59.useState)("details");
+ const [tab, setTab] = (0, import_react60.useState)("details");
const room2 = roster.roomsById[sessionId];
- const [view, setView] = (0, import_react59.useState)(startTab === "settings" && (owner || room2) ? "settings" : "overview");
- const [editing, setEditing] = (0, import_react59.useState)(Boolean(startRenaming && (roster.byId[sessionId] || roster.roomsById[sessionId])));
- const [draftName, setDraftName] = (0, import_react59.useState)(roster.byId[sessionId]?.name ?? (roster.roomsById[sessionId]?.named ? roster.roomsById[sessionId].name : ""));
- const [copied, setCopied] = (0, import_react59.useState)(false);
- const [error, setError] = (0, import_react59.useState)("");
+ const [view, setView] = (0, import_react60.useState)(startTab === "settings" && (owner || room2) ? "settings" : "overview");
+ const [editing, setEditing] = (0, import_react60.useState)(Boolean(startRenaming && (roster.byId[sessionId] || roster.roomsById[sessionId])));
+ const [draftName, setDraftName] = (0, import_react60.useState)(roster.byId[sessionId]?.name ?? (roster.roomsById[sessionId]?.named ? roster.roomsById[sessionId].name : ""));
+ const [copied, setCopied] = (0, import_react60.useState)(false);
+ const [error, setError] = (0, import_react60.useState)("");
const glide = useGlide(tab);
- const last = (0, import_react59.useRef)({ view, tab, move: void 0 });
+ const last = (0, import_react60.useRef)({ view, tab, move: void 0 });
if (last.current.view !== view) last.current = { view, tab, move: view === "settings" ? "in" : "out" };
else if (last.current.tab !== tab) last.current = { view, tab, move: "tab" };
const move = last.current.move;
@@ -25920,21 +26133,21 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a
setTimeout(() => setCopied(false), 1600);
});
};
- const errorLine = error ? (0, import_react59.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null;
+ const errorLine = error ? (0, import_react60.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null;
if ((bot || room2) && view === "settings") {
return [
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ key: "head", className: "bt-subhead", "data-move": move },
- (0, import_react59.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to details"), onClick: () => setView("overview") }, (0, import_react59.createElement)(ChevronLeftIcon)),
- (0, import_react59.createElement)("span", { className: "bt-subhead-title" }, bot ? t("Settings") : t("Group settings")),
- hasStrip ? null : (0, import_react59.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close details"), onClick: close }, (0, import_react59.createElement)(CloseIcon))
+ (0, import_react60.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to details"), onClick: () => setView("overview") }, (0, import_react60.createElement)(ChevronLeftIcon)),
+ (0, import_react60.createElement)("span", { className: "bt-subhead-title" }, bot ? t("Settings") : t("Group settings")),
+ hasStrip ? null : (0, import_react60.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close details"), onClick: close }, (0, import_react60.createElement)(CloseIcon))
),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ key: "set-body", className: "bt-drawer-body bt-set-body", "data-move": move },
errorLine,
- bot ? (0, import_react59.createElement)(BotSettingsForm, { bot, roster, actions, run: run2 }) : (0, import_react59.createElement)(GroupSettingsForm, { room: room2, roster, actions, run: run2, onDeleted: close })
+ bot ? (0, import_react60.createElement)(BotSettingsForm, { bot, roster, actions, run: run2 }) : (0, import_react60.createElement)(GroupSettingsForm, { room: room2, roster, actions, run: run2, onDeleted: close })
)
];
}
@@ -25945,18 +26158,18 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a
canTerminal: actions.canOpenTerminal?.() === true,
canFiles: actions.canOpenFiles?.() === true
}).map((key) => menuItemFor(key, actions, sessionId));
- const top = (0, import_react59.createElement)(
+ const top = (0, import_react60.createElement)(
"div",
{ className: "bt-drawer-top", "data-move": side },
- bot || room2 ? (0, import_react59.createElement)("button", { type: "button", className: "bt-round", "aria-label": bot ? t("Edit Bot") : t("Group settings"), title: bot ? t("Edit Bot") : t("Group settings"), "data-info-row": "settings", onClick: () => setView("settings") }, (0, import_react59.createElement)(GearIcon)) : null,
- more.length > 0 ? (0, import_react59.createElement)("span", { "data-info-row": "more" }, (0, import_react59.createElement)(PanelMenu, { items: more, className: "bt-round", "aria-label": t("More") })) : null,
- bot || room2 ? (0, import_react59.createElement)("button", { type: "button", className: "bt-round", "aria-label": copied ? t("Copied conversation") : t("Share conversation"), title: copied ? t("Copied") : t("Copy conversation as Markdown"), onClick: share }, copied ? (0, import_react59.createElement)("span", { key: "copied", className: "bt-pop-in" }, "✓") : (0, import_react59.createElement)(ShareIcon)) : null,
- hasStrip ? null : (0, import_react59.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("Close details"), onClick: close }, (0, import_react59.createElement)(CloseIcon))
+ bot || room2 ? (0, import_react60.createElement)("button", { type: "button", className: "bt-round", "aria-label": bot ? t("Edit Bot") : t("Group settings"), title: bot ? t("Edit Bot") : t("Group settings"), "data-info-row": "settings", onClick: () => setView("settings") }, (0, import_react60.createElement)(GearIcon)) : null,
+ more.length > 0 ? (0, import_react60.createElement)("span", { "data-info-row": "more" }, (0, import_react60.createElement)(PanelMenu, { items: more, className: "bt-round", "aria-label": t("More") })) : null,
+ bot || room2 ? (0, import_react60.createElement)("button", { type: "button", className: "bt-round", "aria-label": copied ? t("Copied conversation") : t("Share conversation"), title: copied ? t("Copied") : t("Copy conversation as Markdown"), onClick: share }, copied ? (0, import_react60.createElement)("span", { key: "copied", className: "bt-pop-in" }, "✓") : (0, import_react60.createElement)(ShareIcon)) : null,
+ hasStrip ? null : (0, import_react60.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("Close details"), onClick: close }, (0, import_react60.createElement)(CloseIcon))
);
if (!bot && !room2) {
return [
- (0, import_react59.createElement)(import_react59.Fragment, { key: "top" }, top),
- (0, import_react59.createElement)("div", { key: "body", className: "bt-drawer-body" }, (0, import_react59.createElement)("div", { className: "bt-muted" }, t("This conversation is not part of your Bot team.")))
+ (0, import_react60.createElement)(import_react60.Fragment, { key: "top" }, top),
+ (0, import_react60.createElement)("div", { key: "body", className: "bt-drawer-body" }, (0, import_react60.createElement)("div", { className: "bt-muted" }, t("This conversation is not part of your Bot team.")))
];
}
const current = bot?.name ?? room2.name;
@@ -25970,12 +26183,12 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a
const subtitle = bot ? bot.role : roomSubtitle(room2, roster);
const tabs = bot ? roster.computer?.enabled === true ? ["details", "browser", "computer"] : ["details", "browser"] : ["details"];
return [
- (0, import_react59.createElement)(import_react59.Fragment, { key: "top" }, top),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(import_react60.Fragment, { key: "top" }, top),
+ (0, import_react60.createElement)(
"div",
{ key: "id", className: "bt-drawer-id", "data-move": side },
- bot ? (0, import_react59.createElement)(BotAvatar, { bot, size: 64, state: botState(running, doing, roster.questions?.[part] !== void 0), main: isMainBot, badge: false, gaze: true, pokeable: true }) : (0, import_react59.createElement)(MemberPile, { room: room2, roster }),
- editing ? (0, import_react59.createElement)("input", {
+ bot ? (0, import_react60.createElement)(BotAvatar, { bot, size: 64, state: botState(running, doing, roster.questions?.[part] !== void 0), main: isMainBot, badge: false, gaze: true, pokeable: true }) : (0, import_react60.createElement)(MemberPile, { room: room2, roster }),
+ editing ? (0, import_react60.createElement)("input", {
className: "bt-drawer-name-input",
autoFocus: true,
value: draftName,
@@ -25990,53 +26203,54 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a
setEditing(false);
}
}
- }) : (0, import_react59.createElement)("button", { type: "button", className: "bt-drawer-name", "aria-label": t("Rename {name}", { name: current }), title: t("Rename"), onClick: () => {
+ }) : (0, import_react60.createElement)("button", { type: "button", className: "bt-drawer-name", "aria-label": t("Rename {name}", { name: current }), title: t("Rename"), onClick: () => {
setDraftName(room2 && !room2.named ? "" : current);
setEditing(true);
} }, current),
- subtitle ? (0, import_react59.createElement)("span", { className: "bt-drawer-role" }, subtitle) : null
+ subtitle ? (0, import_react60.createElement)("span", { className: "bt-drawer-role" }, subtitle) : null
),
- tabs.length > 1 ? (0, import_react59.createElement)(
+ tabs.length > 1 ? (0, import_react60.createElement)(
"div",
{ key: "tabs", ref: glide.box, className: "bt-tabs", role: "tablist", "data-move": side },
- (0, import_react59.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }),
- tabs.map((key) => (0, import_react59.createElement)("button", { key, type: "button", role: "tab", className: "bt-tab", "aria-selected": tab === key, onClick: () => setTab(key) }, t(TAB_LABELS[key])))
+ (0, import_react60.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }),
+ tabs.map((key) => (0, import_react60.createElement)("button", { key, type: "button", role: "tab", className: "bt-tab", "aria-selected": tab === key, onClick: () => setTab(key) }, t(TAB_LABELS[key])))
) : null,
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(
"div",
{ key: `body:${tab}`, className: "bt-drawer-body", "data-move": move },
errorLine,
- room2 && tab === "details" ? (0, import_react59.createElement)(GroupOverview, { room: room2, roster, actions, usage, useWork, openSettings: () => setView("settings") }) : null,
- bot && tab === "computer" ? (0, import_react59.createElement)(ComputerView, { bot, actions, hooks: { useComputer } }) : null,
+ room2 && tab === "details" ? (0, import_react60.createElement)(GroupOverview, { room: room2, roster, actions, usage, useWork, openSettings: () => setView("settings") }) : null,
+ bot && tab === "computer" ? (0, import_react60.createElement)(ComputerView, { bot, actions, hooks: { useComputer } }) : null,
bot && tab === "details" ? [
- (0, import_react59.createElement)(RunStats, { key: "stats", bot, part, running, actions }),
- (0, import_react59.createElement)(
+ (0, import_react60.createElement)(RunStats, { key: "stats", bot, part, running, actions }),
+ (0, import_react60.createElement)(
"div",
{ key: "model", className: "bt-drawer-model" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Model")),
- (0, import_react59.createElement)(ModelMenu, { bot, roster, actions, run: run2, wide: true }),
- modelOf(bot, roster) ? null : (0, import_react59.createElement)("div", { className: "bt-note" }, t("Pick a model and {name} can start.", { name: bot.name }))
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Model")),
+ (0, import_react60.createElement)(ModelMenu, { bot, roster, actions, run: run2, wide: true }),
+ modelOf(bot, roster) ? null : (0, import_react60.createElement)("div", { className: "bt-note" }, t("Pick a model and {name} can start.", { name: bot.name }))
),
- bot.engine ? (0, import_react59.createElement)(AgentSessions, { key: "sessions", bot, part, run: run2, useSessions }) : null,
- (0, import_react59.createElement)(PermissionRow, { key: "permission", bot, roster, actions, run: run2 }),
- (0, import_react59.createElement)(BotConnectors, { key: "connectors", bot, roster, actions, run: run2 }),
- (0, import_react59.createElement)(
+ bot.engine ? (0, import_react60.createElement)(AgentSessions, { key: "sessions", bot, part, run: run2, useSessions }) : null,
+ (0, import_react60.createElement)(PermissionRow, { key: "permission", bot, roster, actions, run: run2 }),
+ (0, import_react60.createElement)(BotConnectors, { key: "connectors", bot, roster, actions, run: run2 }),
+ (0, import_react60.createElement)(
"div",
{ key: "folder", className: "bt-drawer-model" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Working folder")),
- (0, import_react59.createElement)(FolderMenu, { value: bot.workDir, actions, run: run2, wide: true, onPick: (workDir) => run2(actions.updateBot(bot.id, { workDir })) })
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Working folder")),
+ (0, import_react60.createElement)(FolderMenu, { value: bot.workDir, actions, run: run2, wide: true, onPick: (workDir) => run2(actions.updateBot(bot.id, { workDir })) })
),
- bot.instructions ? (0, import_react59.createElement)(About, { key: "about", text: bot.instructions }) : (0, import_react59.createElement)("button", { key: "about", type: "button", className: "bt-more", onClick: () => setView("settings") }, t("Add instructions in Bot settings")),
- roster.memory === false ? null : (0, import_react59.createElement)(MemoryRow, { key: "memory", owner: { id: bot.id, name: bot.name }, actions }),
- usage ? (0, import_react59.createElement)(
+ bot.instructions ? (0, import_react60.createElement)(About, { key: "about", text: bot.instructions }) : (0, import_react60.createElement)("button", { key: "about", type: "button", className: "bt-more", onClick: () => setView("settings") }, t("Add instructions in Bot settings")),
+ roster.memory === false ? null : (0, import_react60.createElement)(MemoryRow, { key: "memory", owner: { id: bot.id, name: bot.name }, actions }),
+ usage ? (0, import_react60.createElement)(
"div",
{ key: "usage" },
- (0, import_react59.createElement)("div", { className: "bt-section-title" }, t("Usage")),
- (0, import_react59.createElement)("div", { className: "bt-kv" }, (0, import_react59.createElement)("span", null, bot.name), (0, import_react59.createElement)("span", null, usage))
+ (0, import_react60.createElement)("div", { className: "bt-section-title" }, t("Usage")),
+ (0, import_react60.createElement)("div", { className: "bt-kv" }, (0, import_react60.createElement)("span", null, bot.name), (0, import_react60.createElement)("span", null, usage))
) : null,
- (0, import_react59.createElement)(ScheduleSummary, { key: "routines", bot, actions })
+ (0, import_react60.createElement)(ScheduleSummary, { key: "routines", bot, actions }),
+ (0, import_react60.createElement)(OperatorTasks, { key: "operator-tasks", bot, roster })
] : null,
- bot && tab === "browser" ? (0, import_react59.createElement)(BrowserCards, { bot, sessionId, roster, actions, useBrowserTabs, useBrowserPages }) : null
+ bot && tab === "browser" ? (0, import_react60.createElement)(BrowserCards, { bot, sessionId, roster, actions, useBrowserTabs, useBrowserPages }) : null
)
];
}
@@ -26047,7 +26261,7 @@ function rectsOverlap(a, b) {
}
// src/client/browser-pane.js
-var import_react60 = require("react");
+var import_react61 = require("react");
var import_react_dom10 = require("react-dom");
var PANEL_LINGER_MS = 300;
var WIDTH_KEY = STORAGE.browserWidth;
@@ -26059,10 +26273,10 @@ var READ_FLASH_MS = 2400;
var EMPTY_PAGE = { url: "", title: "", favicon: null, loading: false, canGoBack: false, canGoForward: false, error: null, excerpt: "" };
var EMPTY_TABS2 = { ids: [], active: null };
var icon = (paths) => function BrowserIcon() {
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"svg",
{ width: 16, height: 16, viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true },
- paths.map((d, index) => (0, import_react60.createElement)("path", { key: index, d }))
+ paths.map((d, index) => (0, import_react61.createElement)("path", { key: index, d }))
);
};
var GlobeIcon2 = icon(["M10 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14z", "M3 10h14", "M10 3c2 2.2 2.9 4.5 2.9 7S12 14.8 10 17c-2-2.2-2.9-4.5-2.9-7S8 5.2 10 3z"]);
@@ -26077,9 +26291,9 @@ var ImportIcon = icon(["M10 3.5v8.5", "M6 8.5l4 4 4-4", "M4.5 14v1.5a1.5 1.5 0 0
var FileIcon = icon(["M6 3.5h5.5L14.5 6.5v10H6z", "M11 3.5v3.5h3.5"]);
var WindowIcon = icon(["M4 5h12v9.5H4z", "M4 7.5h12"]);
function Favicon({ src, className }) {
- const [failed, setFailed] = (0, import_react60.useState)(null);
- if (!src || failed === src) return (0, import_react60.createElement)("span", { className: `${className} bt-ptab-globe` }, (0, import_react60.createElement)(GlobeIcon2));
- return (0, import_react60.createElement)("img", { className, src, alt: "", "aria-hidden": true, onError: () => setFailed(src) });
+ const [failed, setFailed] = (0, import_react61.useState)(null);
+ if (!src || failed === src) return (0, import_react61.createElement)("span", { className: `${className} bt-ptab-globe` }, (0, import_react61.createElement)(GlobeIcon2));
+ return (0, import_react61.createElement)("img", { className, src, alt: "", "aria-hidden": true, onError: () => setFailed(src) });
}
var savedWidth = () => {
try {
@@ -26095,11 +26309,11 @@ var shortAddress = (url) => String(url ?? "").replace(/^https?:\/\//i, "").repla
var reducedMotion2 = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
var tabLabel = (page) => page.title || shortAddress(page.url) || t("New tab");
function PanelMenu({ items, className, "aria-label": label }) {
- const [open, setOpen] = (0, import_react60.useState)(false);
+ const [open, setOpen] = (0, import_react61.useState)(false);
const [shown, leaving] = useLinger(open, 120);
- const wrap = (0, import_react60.useRef)(null);
- const button = (0, import_react60.useRef)(null);
- (0, import_react60.useEffect)(() => {
+ const wrap = (0, import_react61.useRef)(null);
+ const button = (0, import_react61.useRef)(null);
+ (0, import_react61.useEffect)(() => {
if (!open) return void 0;
const onDown = (event) => {
if (wrap.current && !wrap.current.contains(event.target)) setOpen(false);
@@ -26118,10 +26332,10 @@ function PanelMenu({ items, className, "aria-label": label }) {
};
}, [open]);
if (items.length === 0) return null;
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"span",
{ className: "bt-pmenu", ref: wrap },
- (0, import_react60.createElement)("button", {
+ (0, import_react61.createElement)("button", {
ref: button,
type: "button",
className,
@@ -26130,11 +26344,11 @@ function PanelMenu({ items, className, "aria-label": label }) {
"aria-haspopup": "menu",
"aria-expanded": open,
onClick: () => setOpen((value) => !value)
- }, (0, import_react60.createElement)(DotsIcon)),
- shown ? (0, import_react60.createElement)(
+ }, (0, import_react61.createElement)(DotsIcon)),
+ shown ? (0, import_react61.createElement)(
"div",
{ className: "bt-pmenu-pop", role: "menu", "data-leaving": leaving || void 0 },
- items.map((item, index) => item.sep ? (0, import_react60.createElement)("span", { key: `sep-${index}`, className: "bt-pmenu-sep", role: "separator" }) : (0, import_react60.createElement)("button", {
+ items.map((item, index) => item.sep ? (0, import_react61.createElement)("span", { key: `sep-${index}`, className: "bt-pmenu-sep", role: "separator" }) : (0, import_react61.createElement)("button", {
key: item.key,
type: "button",
role: "menuitem",
@@ -26143,7 +26357,7 @@ function PanelMenu({ items, className, "aria-label": label }) {
setOpen(false);
item.onPick();
}
- }, (0, import_react60.createElement)(item.icon), (0, import_react60.createElement)("span", null, item.label)))
+ }, (0, import_react61.createElement)(item.icon), (0, import_react61.createElement)("span", null, item.label)))
) : null
);
}
@@ -26169,12 +26383,12 @@ function menuItemFor(key, actions, subject) {
var sideTitle = (chat) => chat?.entries?.[0]?.question?.trim() || t("Side chat");
function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, reading, onView, actions, useBrowserPages }) {
const pages = useBrowserPages((map) => map);
- const wrap = (0, import_react60.useRef)(null);
- const ind = (0, import_react60.useRef)(null);
- const spot = (0, import_react60.useRef)(null);
- const under = (0, import_react60.useRef)(null);
- const watcher = (0, import_react60.useRef)(null);
- (0, import_react60.useLayoutEffect)(() => {
+ const wrap = (0, import_react61.useRef)(null);
+ const ind = (0, import_react61.useRef)(null);
+ const spot = (0, import_react61.useRef)(null);
+ const under = (0, import_react61.useRef)(null);
+ const watcher = (0, import_react61.useRef)(null);
+ (0, import_react61.useLayoutEffect)(() => {
const box = wrap.current;
const capsule = ind.current;
if (!box || !capsule) return void 0;
@@ -26207,7 +26421,7 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r
trail.cancel();
};
});
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
const box = wrap.current;
if (!box) return void 0;
const observer = new ResizeObserver(() => {
@@ -26231,13 +26445,13 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r
canTerminal: actions.canOpenTerminal?.() === true,
canFiles: actions.canOpenFiles?.() === true
}).map((key) => menuItemFor(key, actions, subject));
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"div",
{ className: "bt-ptabs", role: "tablist", "aria-label": t("Panel tabs") },
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)(
"div",
{ className: "bt-ptabs-in", ref: wrap },
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)(
"button",
{
type: "button",
@@ -26247,13 +26461,13 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r
title: bot.name,
onClick: () => onView("details")
},
- (0, import_react60.createElement)(BotMark, { bot, size: 20, state: reading ? "searching" : "idle" }),
- view === "details" ? (0, import_react60.createElement)("span", { className: "bt-ptab-name" }, bot.name) : null
+ (0, import_react61.createElement)(BotMark, { bot, size: 20, state: reading ? "searching" : "idle" }),
+ view === "details" ? (0, import_react61.createElement)("span", { className: "bt-ptab-name" }, bot.name) : null
),
ids.map((tabId) => {
const page = pages[tabId] ?? EMPTY_PAGE;
const on = view === "browser" && tabId === active;
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"button",
{
key: tabId,
@@ -26274,9 +26488,9 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r
}
}
},
- (0, import_react60.createElement)(Favicon, { src: page.favicon, className: "bt-ptab-fav" }),
- (0, import_react60.createElement)("span", { className: "bt-ptab-title" }, tabLabel(page)),
- (0, import_react60.createElement)("span", {
+ (0, import_react61.createElement)(Favicon, { src: page.favicon, className: "bt-ptab-fav" }),
+ (0, import_react61.createElement)("span", { className: "bt-ptab-title" }, tabLabel(page)),
+ (0, import_react61.createElement)("span", {
className: "bt-ptab-x",
role: "button",
"aria-label": t("Close tab"),
@@ -26290,7 +26504,7 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r
}),
sides.map((chat) => {
const on = view === "side" && chat.id === side;
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"button",
{
key: chat.id,
@@ -26308,9 +26522,9 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r
}
}
},
- (0, import_react60.createElement)("span", { className: "bt-ptab-globe", "aria-hidden": true }, (0, import_react60.createElement)(SideIcon)),
- (0, import_react60.createElement)("span", { className: "bt-ptab-title" }, sideTitle(chat)),
- (0, import_react60.createElement)("span", {
+ (0, import_react61.createElement)("span", { className: "bt-ptab-globe", "aria-hidden": true }, (0, import_react61.createElement)(SideIcon)),
+ (0, import_react61.createElement)("span", { className: "bt-ptab-title" }, sideTitle(chat)),
+ (0, import_react61.createElement)("span", {
className: "bt-ptab-x",
role: "button",
"aria-label": t("Close side chat"),
@@ -26322,30 +26536,30 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r
}, "×")
);
}),
- (0, import_react60.createElement)("span", { ref: ind, className: "bt-ptab-ind", "aria-hidden": true })
+ (0, import_react61.createElement)("span", { ref: ind, className: "bt-ptab-ind", "aria-hidden": true })
),
// The `···` and Close stay outside the scrolling tabs, so a narrow panel keeps both.
- (0, import_react60.createElement)(PanelMenu, { items, className: "bt-ptab-new", "aria-label": t("More") }),
- (0, import_react60.createElement)("button", { type: "button", className: "bt-icon-btn bt-ptab-close", "aria-label": t("Close panel"), title: t("Close panel"), onClick: () => actions.closePanel() }, (0, import_react60.createElement)(CloseIcon3))
+ (0, import_react61.createElement)(PanelMenu, { items, className: "bt-ptab-new", "aria-label": t("More") }),
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-icon-btn bt-ptab-close", "aria-label": t("Close panel"), title: t("Close panel"), onClick: () => actions.closePanel() }, (0, import_react61.createElement)(CloseIcon3))
);
}
function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, hold }) {
const page = useBrowserPages((pages) => pages[tabId ?? ""]) ?? EMPTY_PAGE;
- const frame = (0, import_react60.useRef)(null);
- const input = (0, import_react60.useRef)(null);
- const [draft, setDraft] = (0, import_react60.useState)(null);
- const [covered, setCovered] = (0, import_react60.useState)(false);
+ const frame = (0, import_react61.useRef)(null);
+ const input = (0, import_react61.useRef)(null);
+ const [draft, setDraft] = (0, import_react61.useState)(null);
+ const [covered, setCovered] = (0, import_react61.useState)(false);
const imports = actions.browserImport;
- const [flow, setFlow] = (0, import_react60.useState)(null);
- const flowRef = (0, import_react60.useRef)(null);
- const [sources, setSources] = (0, import_react60.useState)(null);
- const [busy, setBusy] = (0, import_react60.useState)(false);
+ const [flow, setFlow] = (0, import_react61.useState)(null);
+ const flowRef = (0, import_react61.useRef)(null);
+ const [sources, setSources] = (0, import_react61.useState)(null);
+ const [busy, setBusy] = (0, import_react61.useState)(false);
const setFlowTracked = (next) => {
flowRef.current = typeof next === "function" ? next(flowRef.current) : next;
setFlow(flowRef.current);
};
const showGuest = landed && !leaving && !covered && Boolean(page.url) && !page.error && flow === null;
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
const update = () => {
const panel = frame.current?.getBoundingClientRect();
const overlaps2 = panel && [...document.querySelectorAll('[role="dialog"],[role="menu"],[role="listbox"]')].some((element) => rectsOverlap(panel, element.getBoundingClientRect()));
@@ -26360,7 +26574,7 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho
window.removeEventListener("resize", update);
};
}, []);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
setFlowTracked(null);
return () => {
const id = typeof flowRef.current === "object" && flowRef.current !== null ? flowRef.current.id : null;
@@ -26404,7 +26618,7 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho
if (id) void imports?.cancel(id).catch(() => {
});
};
- (0, import_react60.useLayoutEffect)(() => {
+ (0, import_react61.useLayoutEffect)(() => {
const element = frame.current;
if (!element || leaving || !tabId) {
void actions.browserShow(null);
@@ -26430,7 +26644,7 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho
window.removeEventListener("resize", schedule);
};
}, [tabId, showGuest, leaving]);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
setDraft(null);
if (landed && !page.url) input.current?.focus();
}, [tabId, landed]);
@@ -26446,38 +26660,38 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho
};
const editing = draft !== null;
const secure = /^https:/i.test(page.url);
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"div",
{ className: "bt-panel-view bt-panel-browser", "aria-label": t("{name}'s browser", { name: bot.name }) },
- actions.browserTakeover ? (0, import_react60.createElement)(
+ actions.browserTakeover ? (0, import_react61.createElement)(
"div",
{ className: "bt-browser-takeover", "data-held": hold?.by === "user" || void 0 },
- (0, import_react60.createElement)("span", null, hold?.by === "user" ? t("You control this browser") : hold?.by === "bot" ? t("The Bot handed this browser to you: {reason}", { reason: hold.reason }) : t("The Bot controls this browser")),
- hold?.by ? (0, import_react60.createElement)("button", { type: "button", onClick: () => void actions.browserGiveBack(bot.id) }, t("Give back")) : (0, import_react60.createElement)(
+ (0, import_react61.createElement)("span", null, hold?.by === "user" ? t("You control this browser") : hold?.by === "bot" ? t("The Bot handed this browser to you: {reason}", { reason: hold.reason }) : t("The Bot controls this browser")),
+ hold?.by ? (0, import_react61.createElement)("button", { type: "button", onClick: () => void actions.browserGiveBack(bot.id) }, t("Give back")) : (0, import_react61.createElement)(
"span",
{ className: "bt-browser-takeover-actions" },
- (0, import_react60.createElement)("button", { type: "button", onClick: () => void actions.browserTakeover(bot.id) }, t("Take over")),
- (0, import_react60.createElement)("button", { type: "button", onClick: () => void actions.browserStop(bot.id) }, t("Stop"))
+ (0, import_react61.createElement)("button", { type: "button", onClick: () => void actions.browserTakeover(bot.id) }, t("Take over")),
+ (0, import_react61.createElement)("button", { type: "button", onClick: () => void actions.browserStop(bot.id) }, t("Stop"))
)
) : null,
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)(
"div",
{ className: "bt-browser-bar" },
- (0, import_react60.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back"), title: t("Back"), disabled: !page.canGoBack, onClick: () => actions.browserCommand(tabId, "back") }, (0, import_react60.createElement)(BackIcon)),
- (0, import_react60.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Forward"), title: t("Forward"), disabled: !page.canGoForward, onClick: () => actions.browserCommand(tabId, "forward") }, (0, import_react60.createElement)(ForwardIcon)),
- (0, import_react60.createElement)("button", {
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back"), title: t("Back"), disabled: !page.canGoBack, onClick: () => actions.browserCommand(tabId, "back") }, (0, import_react61.createElement)(BackIcon)),
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Forward"), title: t("Forward"), disabled: !page.canGoForward, onClick: () => actions.browserCommand(tabId, "forward") }, (0, import_react61.createElement)(ForwardIcon)),
+ (0, import_react61.createElement)("button", {
type: "button",
className: "bt-icon-btn",
disabled: !page.url,
"aria-label": page.loading ? t("Stop") : t("Reload"),
title: page.loading ? t("Stop") : t("Reload"),
onClick: () => actions.browserCommand(tabId, page.loading ? "stop" : "reload")
- }, (0, import_react60.createElement)(page.loading ? StopIcon : ReloadIcon)),
- (0, import_react60.createElement)(
+ }, (0, import_react61.createElement)(page.loading ? StopIcon : ReloadIcon)),
+ (0, import_react61.createElement)(
"form",
{ className: "bt-browser-address", onSubmit: go, "data-editing": editing || void 0 },
- (0, import_react60.createElement)("span", { className: "bt-browser-scheme", "aria-hidden": true }, (0, import_react60.createElement)(secure && !editing ? LockIcon2 : GlobeIcon2)),
- (0, import_react60.createElement)("input", {
+ (0, import_react61.createElement)("span", { className: "bt-browser-scheme", "aria-hidden": true }, (0, import_react61.createElement)(secure && !editing ? LockIcon2 : GlobeIcon2)),
+ (0, import_react61.createElement)("input", {
ref: input,
type: "text",
spellCheck: false,
@@ -26501,14 +26715,14 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho
}
})
),
- (0, import_react60.createElement)("button", {
+ (0, import_react61.createElement)("button", {
type: "button",
className: "bt-icon-btn",
"aria-label": t("New browser tab"),
title: t("New browser tab"),
onClick: () => actions.browserNewTab(bot.id)
- }, (0, import_react60.createElement)(PlusTabIcon)),
- imports ? (0, import_react60.createElement)("button", {
+ }, (0, import_react61.createElement)(PlusTabIcon)),
+ imports ? (0, import_react61.createElement)("button", {
type: "button",
className: "bt-icon-btn bt-import-btn",
"aria-label": t("Import cookies"),
@@ -26519,29 +26733,29 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho
if (flow === "menu") setFlowTracked(null);
else openImport();
}
- }, (0, import_react60.createElement)(ImportIcon)) : null,
- page.loading ? (0, import_react60.createElement)("span", { className: "bt-browser-progress", "aria-hidden": true }) : null
+ }, (0, import_react61.createElement)(ImportIcon)) : null,
+ page.loading ? (0, import_react61.createElement)("span", { className: "bt-browser-progress", "aria-hidden": true }) : null
),
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)(
"div",
{ ref: frame, className: "bt-browser-frame", "data-guest": showGuest || void 0 },
- flow === "menu" ? (0, import_react60.createElement)(ImportMenu, { sources, busy, onFile: pickFile, onSource: pickSource, onClose: () => setFlowTracked(null) }) : null,
- typeof flow === "object" && flow !== null ? (0, import_react60.createElement)(ImportCard, { flow, page, busy, onApply: applyImport, onCancel: cancelImport, onCloseAndImport: closeAndImport, onDone: () => setFlowTracked(null), onReload: () => actions.browserCommand(tabId, "reload") }) : null,
- flow === null && page.error ? (0, import_react60.createElement)(
+ flow === "menu" ? (0, import_react61.createElement)(ImportMenu, { sources, busy, onFile: pickFile, onSource: pickSource, onClose: () => setFlowTracked(null) }) : null,
+ typeof flow === "object" && flow !== null ? (0, import_react61.createElement)(ImportCard, { flow, page, busy, onApply: applyImport, onCancel: cancelImport, onCloseAndImport: closeAndImport, onDone: () => setFlowTracked(null), onReload: () => actions.browserCommand(tabId, "reload") }) : null,
+ flow === null && page.error ? (0, import_react61.createElement)(
"div",
{ className: "bt-browser-empty" },
- (0, import_react60.createElement)("div", { className: "bt-browser-empty-title" }, t("This page didn’t load")),
- (0, import_react60.createElement)("div", { className: "bt-browser-empty-text" }, t(page.error)),
- page.url ? (0, import_react60.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => {
+ (0, import_react61.createElement)("div", { className: "bt-browser-empty-title" }, t("This page didn’t load")),
+ (0, import_react61.createElement)("div", { className: "bt-browser-empty-text" }, t(page.error)),
+ page.url ? (0, import_react61.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => {
void actions.browserNavigate(tabId, page.url);
} }, t("Try again")) : null
- ) : flow === null && !page.url ? (0, import_react60.createElement)(
+ ) : flow === null && !page.url ? (0, import_react61.createElement)(
"div",
{ className: "bt-browser-empty" },
- (0, import_react60.createElement)(BotMark, { bot, size: 48, state: "idle", live: true }),
- (0, import_react60.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })),
- (0, import_react60.createElement)("div", { className: "bt-browser-empty-text" }, t("Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.", { name: bot.name })),
- imports ? (0, import_react60.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: openImport }, t("Import cookies")) : null
+ (0, import_react61.createElement)(BotMark, { bot, size: 48, state: "idle", live: true }),
+ (0, import_react61.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })),
+ (0, import_react61.createElement)("div", { className: "bt-browser-empty-text" }, t("Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.", { name: bot.name })),
+ imports ? (0, import_react61.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: openImport }, t("Import cookies")) : null
) : null
)
);
@@ -26553,25 +26767,25 @@ function importError(error) {
return String(error);
}
function ImportMenu({ sources, busy, onFile, onSource, onClose }) {
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
const close = (event) => {
if (event.key === "Escape") onClose();
};
window.addEventListener("keydown", close);
return () => window.removeEventListener("keydown", close);
}, [onClose]);
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"div",
{ className: "bt-import-menu", role: "menu", "aria-label": t("Import cookies") },
- (0, import_react60.createElement)("div", { className: "bt-import-menu-title" }, t("Import cookies")),
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)("div", { className: "bt-import-menu-title" }, t("Import cookies")),
+ (0, import_react61.createElement)(
"button",
{ type: "button", className: "bt-import-item", role: "menuitem", disabled: busy, onClick: onFile },
- (0, import_react60.createElement)(FileIcon, { className: "bt-import-item-icon" }),
- (0, import_react60.createElement)("span", { className: "bt-import-item-name" }, t("From a file…")),
- (0, import_react60.createElement)("span", { className: "bt-import-item-sub" }, t("cookies.txt, JSON, storageState"))
+ (0, import_react61.createElement)(FileIcon, { className: "bt-import-item-icon" }),
+ (0, import_react61.createElement)("span", { className: "bt-import-item-name" }, t("From a file…")),
+ (0, import_react61.createElement)("span", { className: "bt-import-item-sub" }, t("cookies.txt, JSON, storageState"))
),
- sources === null ? (0, import_react60.createElement)("div", { className: "bt-import-menu-note" }, t("Loading…")) : sources.length === 0 ? (0, import_react60.createElement)("div", { className: "bt-import-menu-note" }, t("No browsers found")) : sources.map((source) => (0, import_react60.createElement)(
+ sources === null ? (0, import_react61.createElement)("div", { className: "bt-import-menu-note" }, t("Loading…")) : sources.length === 0 ? (0, import_react61.createElement)("div", { className: "bt-import-menu-note" }, t("No browsers found")) : sources.map((source) => (0, import_react61.createElement)(
"button",
{
key: source.id,
@@ -26581,83 +26795,83 @@ function ImportMenu({ sources, busy, onFile, onSource, onClose }) {
disabled: busy,
onClick: () => onSource(source)
},
- (0, import_react60.createElement)(WindowIcon, { className: "bt-import-item-icon" }),
- (0, import_react60.createElement)("span", { className: "bt-import-item-name" }, source.label),
- (0, import_react60.createElement)("span", { className: "bt-import-item-sub" }, t("Copy of its cookies"))
+ (0, import_react61.createElement)(WindowIcon, { className: "bt-import-item-icon" }),
+ (0, import_react61.createElement)("span", { className: "bt-import-item-name" }, source.label),
+ (0, import_react61.createElement)("span", { className: "bt-import-item-sub" }, t("Copy of its cookies"))
))
);
}
function ImportCard({ flow, page, busy, onApply, onCancel, onCloseAndImport, onDone, onReload }) {
const { stage } = flow;
if (stage === "running") {
- return (0, import_react60.createElement)("div", { className: "bt-import-card" }, (0, import_react60.createElement)(
+ return (0, import_react61.createElement)("div", { className: "bt-import-card" }, (0, import_react61.createElement)(
"div",
{ className: "bt-import-box" },
- (0, import_react60.createElement)("div", { className: "bt-import-title" }, t("{name} is running", { name: flow.source.name })),
- (0, import_react60.createElement)("div", { className: "bt-import-text" }, t("It must close for a moment so its cookies can be copied. It will reopen with your tabs.")),
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)("div", { className: "bt-import-title" }, t("{name} is running", { name: flow.source.name })),
+ (0, import_react61.createElement)("div", { className: "bt-import-text" }, t("It must close for a moment so its cookies can be copied. It will reopen with your tabs.")),
+ (0, import_react61.createElement)(
"div",
{ className: "bt-import-actions" },
- (0, import_react60.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onCloseAndImport }, busy ? t("Closing…") : t("Close {name} and import", { name: flow.source.name })),
- (0, import_react60.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel"))
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onCloseAndImport }, busy ? t("Closing…") : t("Close {name} and import", { name: flow.source.name })),
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel"))
)
));
}
if (stage === "error") {
- return (0, import_react60.createElement)("div", { className: "bt-import-card" }, (0, import_react60.createElement)(
+ return (0, import_react61.createElement)("div", { className: "bt-import-card" }, (0, import_react61.createElement)(
"div",
{ className: "bt-import-box" },
- (0, import_react60.createElement)("div", { className: "bt-import-title" }, t("Import failed")),
- (0, import_react60.createElement)("div", { className: "bt-import-text" }, flow.message),
- (0, import_react60.createElement)("div", { className: "bt-import-actions" }, (0, import_react60.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onCancel }, t("Close")))
+ (0, import_react61.createElement)("div", { className: "bt-import-title" }, t("Import failed")),
+ (0, import_react61.createElement)("div", { className: "bt-import-text" }, flow.message),
+ (0, import_react61.createElement)("div", { className: "bt-import-actions" }, (0, import_react61.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onCancel }, t("Close")))
));
}
if (stage === "result") {
const { report } = flow;
const problems = [...report.dropped ?? [], ...report.failed ?? []];
- return (0, import_react60.createElement)("div", { className: "bt-import-card" }, (0, import_react60.createElement)(
+ return (0, import_react61.createElement)("div", { className: "bt-import-card" }, (0, import_react61.createElement)(
"div",
{ className: "bt-import-box" },
- (0, import_react60.createElement)("div", { className: "bt-import-title" }, report.stored > 0 ? t("Imported {count} cookies", { count: report.stored }) : t("No cookies were stored")),
- flow.label ? (0, import_react60.createElement)("div", { className: "bt-import-sub" }, flow.label) : null,
- problems.length ? (0, import_react60.createElement)(
+ (0, import_react61.createElement)("div", { className: "bt-import-title" }, report.stored > 0 ? t("Imported {count} cookies", { count: report.stored }) : t("No cookies were stored")),
+ flow.label ? (0, import_react61.createElement)("div", { className: "bt-import-sub" }, flow.label) : null,
+ problems.length ? (0, import_react61.createElement)(
"div",
{ className: "bt-import-list" },
- problems.slice(0, 8).map((item, index) => (0, import_react60.createElement)(
+ problems.slice(0, 8).map((item, index) => (0, import_react61.createElement)(
"div",
{ key: index, className: "bt-import-line" },
- (0, import_react60.createElement)("span", { className: "bt-import-line-name" }, item.name ?? "—"),
- (0, import_react60.createElement)("span", { className: "bt-import-line-reason" }, item.reason)
+ (0, import_react61.createElement)("span", { className: "bt-import-line-name" }, item.name ?? "—"),
+ (0, import_react61.createElement)("span", { className: "bt-import-line-reason" }, item.reason)
)),
- problems.length > 8 ? (0, import_react60.createElement)("div", { className: "bt-import-line" }, (0, import_react60.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: problems.length - 8 }))) : null
+ problems.length > 8 ? (0, import_react61.createElement)("div", { className: "bt-import-line" }, (0, import_react61.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: problems.length - 8 }))) : null
) : null,
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)(
"div",
{ className: "bt-import-actions" },
- page.url ? (0, import_react60.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onReload }, t("Reload the page")) : null,
- (0, import_react60.createElement)("button", { type: "button", className: "bt-import-primary", onClick: onDone }, t("Done"))
+ page.url ? (0, import_react61.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onReload }, t("Reload the page")) : null,
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-import-primary", onClick: onDone }, t("Done"))
)
));
}
const { preview } = flow;
- return (0, import_react60.createElement)("div", { className: "bt-import-card" }, (0, import_react60.createElement)(
+ return (0, import_react61.createElement)("div", { className: "bt-import-card" }, (0, import_react61.createElement)(
"div",
{ className: "bt-import-box" },
- (0, import_react60.createElement)("div", { className: "bt-import-title" }, t("Import {count} cookies", { count: preview.cookies })),
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)("div", { className: "bt-import-title" }, t("Import {count} cookies", { count: preview.cookies })),
+ (0, import_react61.createElement)(
"div",
{ className: "bt-import-sub" },
preview.source?.label ?? "",
flow.restarted ? ` · ${t("the browser was restarted")}` : ""
),
- preview.sites.length ? (0, import_react60.createElement)(
+ preview.sites.length ? (0, import_react61.createElement)(
"div",
{ className: "bt-import-list" },
- preview.sites.map((site) => (0, import_react60.createElement)(
+ preview.sites.map((site) => (0, import_react61.createElement)(
"div",
{ key: site.site, className: "bt-import-line" },
- (0, import_react60.createElement)("span", { className: "bt-import-line-name" }, site.site),
- (0, import_react60.createElement)(
+ (0, import_react61.createElement)("span", { className: "bt-import-line-name" }, site.site),
+ (0, import_react61.createElement)(
"span",
{ className: "bt-import-line-count" },
t("{count}", { count: site.cookies }),
@@ -26665,35 +26879,35 @@ function ImportCard({ flow, page, busy, onApply, onCancel, onCloseAndImport, onD
)
))
) : null,
- preview.skipped.length ? (0, import_react60.createElement)(
+ preview.skipped.length ? (0, import_react61.createElement)(
"div",
{ className: "bt-import-list" },
- (0, import_react60.createElement)("div", { className: "bt-import-note" }, t("{count} skipped", { count: preview.skipped.length })),
- preview.skipped.slice(0, 5).map((item, index) => (0, import_react60.createElement)(
+ (0, import_react61.createElement)("div", { className: "bt-import-note" }, t("{count} skipped", { count: preview.skipped.length })),
+ preview.skipped.slice(0, 5).map((item, index) => (0, import_react61.createElement)(
"div",
{ key: index, className: "bt-import-line" },
- (0, import_react60.createElement)("span", { className: "bt-import-line-name" }, item.name ?? item.where),
- (0, import_react60.createElement)("span", { className: "bt-import-line-reason" }, item.reason)
+ (0, import_react61.createElement)("span", { className: "bt-import-line-name" }, item.name ?? item.where),
+ (0, import_react61.createElement)("span", { className: "bt-import-line-reason" }, item.reason)
)),
- preview.skipped.length > 5 ? (0, import_react60.createElement)("div", { className: "bt-import-line" }, (0, import_react60.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: preview.skipped.length - 5 }))) : null
+ preview.skipped.length > 5 ? (0, import_react61.createElement)("div", { className: "bt-import-line" }, (0, import_react61.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: preview.skipped.length - 5 }))) : null
) : null,
- preview.warnings.length ? (0, import_react60.createElement)(
+ preview.warnings.length ? (0, import_react61.createElement)(
"details",
{ className: "bt-import-warns" },
- (0, import_react60.createElement)("summary", null, t("{count} adjusted", { count: preview.warnings.reduce((n, w) => n + w.count, 0) })),
- preview.warnings.map((w, index) => (0, import_react60.createElement)(
+ (0, import_react61.createElement)("summary", null, t("{count} adjusted", { count: preview.warnings.reduce((n, w) => n + w.count, 0) })),
+ preview.warnings.map((w, index) => (0, import_react61.createElement)(
"div",
{ key: index, className: "bt-import-line" },
- (0, import_react60.createElement)("span", { className: "bt-import-line-reason" }, `${w.count} × ${w.message}`)
+ (0, import_react61.createElement)("span", { className: "bt-import-line-reason" }, `${w.count} × ${w.message}`)
))
) : null,
- preview.notes.includes("session-cookies") ? (0, import_react60.createElement)("div", { className: "bt-import-note" }, t("Cookies without an expiry stay until the app closes.")) : null,
- preview.notes.includes("local-storage-left") ? (0, import_react60.createElement)("div", { className: "bt-import-note" }, t("Some sites also keep sign-in outside cookies; you may need to sign in again there.")) : null,
- (0, import_react60.createElement)(
+ preview.notes.includes("session-cookies") ? (0, import_react61.createElement)("div", { className: "bt-import-note" }, t("Cookies without an expiry stay until the app closes.")) : null,
+ preview.notes.includes("local-storage-left") ? (0, import_react61.createElement)("div", { className: "bt-import-note" }, t("Some sites also keep sign-in outside cookies; you may need to sign in again there.")) : null,
+ (0, import_react61.createElement)(
"div",
{ className: "bt-import-actions" },
- (0, import_react60.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onApply }, busy ? t("Importing…") : t("Import")),
- (0, import_react60.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel"))
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onApply }, busy ? t("Importing…") : t("Import")),
+ (0, import_react61.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel"))
)
));
}
@@ -26707,41 +26921,41 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes
const active = tabState.active;
const page = useBrowserPages((pages) => (active ? pages[active] : null) ?? EMPTY_PAGE);
const hold = useBrowserHolds?.((map) => bot ? map[bot.id] ?? null : null) ?? null;
- const root = (0, import_react60.useRef)(null);
- const fly = (0, import_react60.useRef)(null);
- const [landed, setLanded] = (0, import_react60.useState)(false);
- const [settling, setSettling] = (0, import_react60.useState)(false);
- const [width, setWidth] = (0, import_react60.useState)(savedWidth);
- const [dragging, setDragging] = (0, import_react60.useState)(false);
- const [resizing, setResizing] = (0, import_react60.useState)(false);
+ const root = (0, import_react61.useRef)(null);
+ const fly = (0, import_react61.useRef)(null);
+ const [landed, setLanded] = (0, import_react61.useState)(false);
+ const [settling, setSettling] = (0, import_react61.useState)(false);
+ const [width, setWidth] = (0, import_react61.useState)(savedWidth);
+ const [dragging, setDragging] = (0, import_react61.useState)(false);
+ const [resizing, setResizing] = (0, import_react61.useState)(false);
const instant = dragging || resizing;
- const [reading, setReading] = (0, import_react60.useState)(false);
+ const [reading, setReading] = (0, import_react61.useState)(false);
const panelWidth = fitWidth(width ?? (view === "browser" ? DEFAULT_WIDTH : DETAILS_WIDTH), widthRange(view, room2));
- (0, import_react60.useLayoutEffect)(() => {
+ (0, import_react61.useLayoutEffect)(() => {
if (view === "browser" && width === null) setWidth(DEFAULT_WIDTH);
}, [view, width]);
- (0, import_react60.useLayoutEffect)(() => {
+ (0, import_react61.useLayoutEffect)(() => {
chatRoom.hold(instant);
}, [instant]);
- const [last, setLast] = (0, import_react60.useState)({ view, width: panelWidth });
+ const [last, setLast] = (0, import_react61.useState)({ view, width: panelWidth });
if (last.view !== view || last.width !== panelWidth) {
setLast({ view, width: panelWidth });
if (last.view !== view) setSettling(last.width !== panelWidth && !instant);
}
- const shownView = (0, import_react60.useRef)(view);
- (0, import_react60.useLayoutEffect)(() => {
+ const shownView = (0, import_react61.useRef)(view);
+ (0, import_react61.useLayoutEffect)(() => {
const switched = settling && shownView.current !== view;
shownView.current = view;
if (switched) chatRoom.hold(true);
chatRoom.setRight(leaving || overlay ? null : panelWidth);
if (switched) chatRoom.hold(false);
}, [view, panelWidth, leaving, overlay]);
- (0, import_react60.useEffect)(() => () => {
+ (0, import_react61.useEffect)(() => () => {
chatRoom.setRight(null);
chatRoom.hold(false);
}, []);
- const mounted = (0, import_react60.useRef)(false);
- (0, import_react60.useEffect)(() => {
+ const mounted = (0, import_react61.useRef)(false);
+ (0, import_react61.useEffect)(() => {
if (!mounted.current) {
mounted.current = true;
return void 0;
@@ -26750,31 +26964,31 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes
const timer = setTimeout(() => setResizing(false), 160);
return () => clearTimeout(timer);
}, [room2]);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
if (!settling) return void 0;
const timer = setTimeout(() => setSettling(false), SPRING_SHAPE.duration + 40);
return () => clearTimeout(timer);
}, [settling, view]);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
const timer = setTimeout(() => setLanded(true), 360);
return () => clearTimeout(timer);
}, []);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
if (canBrowse) actions.browserEnsure(bot.id);
}, [bot?.id, canBrowse]);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
if (view === "browser" && (active === null || !tabState.ids.includes(active))) actions.setPanelView("details");
}, [view, active, tabState.ids.length]);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
if (pane.view === "side" && sideChat === void 0) actions.setPanelView("details");
}, [pane.view, sideChat]);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
if (view !== "browser" || leaving) void actions.browserShow?.(null);
}, [view, leaving]);
- (0, import_react60.useEffect)(() => () => {
+ (0, import_react61.useEffect)(() => () => {
void actions.browserShow?.(null);
}, []);
- (0, import_react60.useEffect)(() => {
+ (0, import_react61.useEffect)(() => {
if (!page.readAt || Date.now() - page.readAt > READ_FLASH_MS) return void 0;
setReading(true);
const timer = setTimeout(() => setReading(false), READ_FLASH_MS);
@@ -26818,7 +27032,7 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes
return actions[name](...args);
};
}
- (0, import_react60.useLayoutEffect)(() => {
+ (0, import_react61.useLayoutEffect)(() => {
const move = fly.current;
if (!move) return;
fly.current = null;
@@ -26901,7 +27115,7 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes
for (const name of ends) grip.addEventListener(name, onEnd);
};
const hasStrip = panelHasStrip(canBrowse, tabState.ids.length, sideChats.length);
- return (0, import_react60.createElement)(
+ return (0, import_react61.createElement)(
"aside",
{
ref: root,
@@ -26919,15 +27133,15 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes
if (event.target === event.currentTarget) setLanded(true);
}
},
- leaving || overlay ? null : (0, import_react60.createElement)("div", { className: "bt-panel-grip", role: "separator", "aria-orientation": "vertical", "aria-label": t("Resize panel"), onPointerDown: startResize }),
+ leaving || overlay ? null : (0, import_react61.createElement)("div", { className: "bt-panel-grip", role: "separator", "aria-orientation": "vertical", "aria-label": t("Resize panel"), onPointerDown: startResize }),
// Over the whole window while dragging: the cursor stays a resize cursor and the
// pages underneath (the chat, the guest) see no pointer.
- dragging ? (0, import_react_dom10.createPortal)((0, import_react60.createElement)("div", { className: "bt-drag-shield", "aria-hidden": true }), document.body) : null,
- hasStrip ? (0, import_react60.createElement)(PanelStrip, { bot, subject: pane.id, view, ids: tabState.ids, active, sides: sideChats, side: pane.side, canBrowse, reading, onView: switchView, actions: panelActions, useBrowserPages }) : null,
- view === "browser" && bot ? (0, import_react60.createElement)(BrowserView, { key: `browser:${active}`, bot, tabId: active, leaving, landed: landed && !settling, actions, useBrowserPages, hold }) : view === "side" && sideChat ? (0, import_react60.createElement)("div", { key: `side:${sideChat.id}`, className: "bt-panel-view" }, (0, import_react60.createElement)(SideChatView, { subject: pane.id, chat: sideChat, roster, actions: panelActions })) : (0, import_react60.createElement)(
+ dragging ? (0, import_react_dom10.createPortal)((0, import_react61.createElement)("div", { className: "bt-drag-shield", "aria-hidden": true }), document.body) : null,
+ hasStrip ? (0, import_react61.createElement)(PanelStrip, { bot, subject: pane.id, view, ids: tabState.ids, active, sides: sideChats, side: pane.side, canBrowse, reading, onView: switchView, actions: panelActions, useBrowserPages }) : null,
+ view === "browser" && bot ? (0, import_react61.createElement)(BrowserView, { key: `browser:${active}`, bot, tabId: active, leaving, landed: landed && !settling, actions, useBrowserPages, hold }) : view === "side" && sideChat ? (0, import_react61.createElement)("div", { key: `side:${sideChat.id}`, className: "bt-panel-view" }, (0, import_react61.createElement)(SideChatView, { subject: pane.id, chat: sideChat, roster, actions: panelActions })) : (0, import_react61.createElement)(
"div",
{ key: `details:${pane.id}:${pane.renaming ? "rename" : ""}:${pane.tab ?? ""}`, className: "bt-panel-view" },
- (0, import_react60.createElement)(DetailsDrawer, {
+ (0, import_react61.createElement)(DetailsDrawer, {
sessionId: pane.id,
startRenaming: pane.renaming,
startTab: pane.tab,
@@ -27070,7 +27284,7 @@ var BROWSER_CSS = `
`;
// src/client/overlays.js
-var import_react61 = require("react");
+var import_react62 = require("react");
var import_react_dom11 = require("react-dom");
var DIALOG_EXIT_MS2 = 160;
var MENU_EXIT_MS3 = 120;
@@ -27081,8 +27295,8 @@ function Overlays({ useRoster, useUi, useSessions, useSessionStatus, useActivity
const frameSnap = useFrame ? useFrame((value) => value) : { viewport: window.innerWidth, sidebarWidth: FALLBACK_SIDEBAR_WIDTH, collapsedWidth: 0 };
const pref = useSidebarPref ? useSidebarPref((value) => value) : "open";
const current = useSessions((list) => Object.values(list.byId).find((session) => (session?.retainedBy?.mainView ?? 0) > 0)?.id ?? null);
- const previous = (0, import_react61.useRef)(current);
- (0, import_react61.useEffect)(() => {
+ const previous = (0, import_react62.useRef)(current);
+ (0, import_react62.useEffect)(() => {
if (previous.current === current) return;
previous.current = current;
if (current) actions.followPanel?.(current);
@@ -27096,8 +27310,8 @@ function Overlays({ useRoster, useUi, useSessions, useSessionStatus, useActivity
panel: open ? { view: open.view, yielded: ui2.panelYield === true } : null
});
const shown = open !== null && layout.panel !== "folded" ? open : null;
- const [kept, setKept] = (0, import_react61.useState)(shown);
- (0, import_react61.useEffect)(() => {
+ const [kept, setKept] = (0, import_react62.useState)(shown);
+ (0, import_react62.useEffect)(() => {
if (shown) {
setKept(shown);
return void 0;
@@ -27117,17 +27331,17 @@ function Overlays({ useRoster, useUi, useSessions, useSessionStatus, useActivity
const [memory, memoryLeaving] = useLinger(ui2.memory && memoryOwner(ui2.memory) ? ui2.memory : null, DIALOG_EXIT_MS2);
const owner = memory ? memoryOwner(memory) : null;
const [menu, menuLeaving] = useLinger(ui2.menu, MENU_EXIT_MS3);
- return (0, import_react61.createElement)(
- import_react61.Fragment,
+ return (0, import_react62.createElement)(
+ import_react62.Fragment,
null,
- pane ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(BotPanel, { pane, leaving: shown === null, room: layout.room, overlay: layout.panel === "overlay", roster, actions, useSessions, useSessionStatus, useActivity, useWork, useBrowserTabs, useBrowserPages, useBrowserHolds }), document.body) : null,
- ui2.newChat ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(NewChat, { key: `${ui2.newChat}:${ui2.newChatSection ?? ""}`, mode: ui2.newChat, sectionId: ui2.newChatSection ?? null, paneLeft: layout.column, roster, actions }), document.body) : null,
- ui2.palette ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(CommandPalette, { key: ui2.palette.token, start: ui2.palette.query, token: ui2.palette.token, roster, actions, useSessions }), document.body) : null,
- ui2.exchange ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(ExchangeDialog, { pair: ui2.exchange, paneLeft: layout.column, roster, actions }), document.body) : null,
- ui2.voice ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(VoiceMode, { key: ui2.voice, sessionId: ui2.voice, paneLeft: layout.column, roster, actions, useSessions, useSessionStatus }), document.body) : null,
- menu ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(ContextMenu, { key: `${menu.kind ?? ""}:${menu.id}:${menu.x}:${menu.y}`, menu, roster, actions, useWork, leaving: menuLeaving }), document.body) : null,
- settings ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(SettingsDialog, { page: settings.page, id: settings.id, roster, actions, useUpdate, leaving: settingsLeaving }), document.body) : null,
- owner ? (0, import_react_dom11.createPortal)((0, import_react61.createElement)(MemoryDialog, { key: owner.id, owner, actions, leaving: memoryLeaving }), document.body) : null
+ pane ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(BotPanel, { pane, leaving: shown === null, room: layout.room, overlay: layout.panel === "overlay", roster, actions, useSessions, useSessionStatus, useActivity, useWork, useBrowserTabs, useBrowserPages, useBrowserHolds }), document.body) : null,
+ ui2.newChat ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(NewChat, { key: `${ui2.newChat}:${ui2.newChatSection ?? ""}`, mode: ui2.newChat, sectionId: ui2.newChatSection ?? null, paneLeft: layout.column, roster, actions }), document.body) : null,
+ ui2.palette ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(CommandPalette, { key: ui2.palette.token, start: ui2.palette.query, token: ui2.palette.token, roster, actions, useSessions }), document.body) : null,
+ ui2.exchange ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(ExchangeDialog, { pair: ui2.exchange, paneLeft: layout.column, roster, actions }), document.body) : null,
+ ui2.voice ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(VoiceMode, { key: ui2.voice, sessionId: ui2.voice, paneLeft: layout.column, roster, actions, useSessions, useSessionStatus }), document.body) : null,
+ menu ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(ContextMenu, { key: `${menu.kind ?? ""}:${menu.id}:${menu.x}:${menu.y}`, menu, roster, actions, useWork, leaving: menuLeaving }), document.body) : null,
+ settings ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(SettingsDialog, { page: settings.page, id: settings.id, roster, actions, useUpdate, leaving: settingsLeaving }), document.body) : null,
+ owner ? (0, import_react_dom11.createPortal)((0, import_react62.createElement)(MemoryDialog, { key: owner.id, owner, actions, leaving: memoryLeaving }), document.body) : null
);
}
@@ -27210,7 +27424,7 @@ function readPage(limits) {
items.push(item);
return { item, number: items.length, secret };
};
- const nameOf2 = (el, text2, secret) => collapse(
+ const nameOf3 = (el, text2, secret) => collapse(
el.getAttribute("aria-label") || text2 || (el.localName === "input" && !secret && NO_VALUE_TYPES.has(el.type) ? el.value : "") || el.getAttribute("placeholder") || el.title || el.getAttribute("alt") || el.querySelector?.("img[alt]")?.alt || el.getAttribute("name") || ""
).slice(0, 80);
const fenced = (code, lang) => {
@@ -27386,7 +27600,7 @@ ${body2 || "(no text)"}
const found = itemFor(el, style);
const mark2 = found ? `[#${found.number}]` : "";
if (tag === "input" || tag === "textarea" || tag === "select") {
- if (found) found.item.name = nameOf2(el, tag === "select" ? "" : el.labels?.[0] ? collapse(el.labels[0].textContent) : "", found.secret);
+ if (found) found.item.name = nameOf3(el, tag === "select" ? "" : el.labels?.[0] ? collapse(el.labels[0].textContent) : "", found.secret);
return mark2 ? ` ${mark2} ` : "";
}
let body2;
@@ -27404,7 +27618,7 @@ ${body2 || "(no text)"}
} else {
body2 = children(el, { ...next, pre: keepsSpace });
}
- if (found) found.item.name = nameOf2(el, oneLine(body2), found.secret);
+ if (found) found.item.name = nameOf3(el, oneLine(body2), found.secret);
const level = /^h([1-6])$/.exec(tag)?.[1] || (el.getAttribute("role") === "heading" ? el.getAttribute("aria-level") || "2" : "");
if (level) {
const title = oneLine(body2);
@@ -27532,7 +27746,7 @@ var PREVIEW_SCRIPT = `(() => {
const text = meta('description') || meta('og:description') || paragraph || document.body?.innerText || ''
return text.replace(/\\s+/g, ' ').trim().slice(0, 200)
})()`;
-var EMPTY = { url: "", title: "", favicon: null, loading: false, canGoBack: false, canGoForward: false, error: null, live: false, excerpt: "" };
+var EMPTY2 = { url: "", title: "", favicon: null, loading: false, canGoBack: false, canGoForward: false, error: null, live: false, excerpt: "" };
function createAppViewProxy(bridge, botId, tabId) {
const listeners2 = /* @__PURE__ */ new Map();
const state = { url: "", title: "", loading: false, canGoBack: false, canGoForward: false };
@@ -27684,7 +27898,7 @@ function createBotBrowsers({ bridge, createSource: createSource2, storage = glob
const savedTab = (botId, tabId) => saved[botId]?.tabs?.find((entry) => entry.id === tabId);
const publish2 = (tabId, patch) => pages.set((state) => {
const botId = owner.get(tabId);
- return { ...state, [tabId]: { ...EMPTY, ...savedTab(botId, tabId), ...state[tabId], ...patch } };
+ return { ...state, [tabId]: { ...EMPTY2, ...savedTab(botId, tabId), ...state[tabId], ...patch } };
});
const save = (botId, entry) => {
saved = store.update((stored) => setEntry(stored, botId, entry), saved);
@@ -28187,15 +28401,15 @@ function lineDiff(before, after) {
}
// src/client/learning-card.js
-var import_react62 = require("react");
+var import_react63 = require("react");
var failedAnswers = /* @__PURE__ */ new Map();
function ProposalCard({ proposal, initialError = "", onFailure, onResolved, actions }) {
const outcome = proposal.outcome;
- const [busy, setBusy] = (0, import_react62.useState)(false);
- const [error, setError] = (0, import_react62.useState)(initialError);
- const [open, setOpen] = (0, import_react62.useState)(false);
- const busyRef = (0, import_react62.useRef)(false);
- const titleId = (0, import_react62.useId)();
+ const [busy, setBusy] = (0, import_react63.useState)(false);
+ const [error, setError] = (0, import_react63.useState)(initialError);
+ const [open, setOpen] = (0, import_react63.useState)(false);
+ const busyRef = (0, import_react63.useRef)(false);
+ const titleId = (0, import_react63.useId)();
const answer = (approve) => {
if (busyRef.current) return;
busyRef.current = true;
@@ -28212,68 +28426,68 @@ function ProposalCard({ proposal, initialError = "", onFailure, onResolved, acti
};
const update = proposal.action === "update";
const agents = proposal.kind === "agents";
- const rows2 = (0, import_react62.useMemo)(() => lineDiff(update ? proposal.previous?.content : "", proposal.content), [update, proposal.previous?.content, proposal.content]);
+ const rows2 = (0, import_react63.useMemo)(() => lineDiff(update ? proposal.previous?.content : "", proposal.content), [update, proposal.previous?.content, proposal.content]);
const change = agents ? [
- (0, import_react62.createElement)(FileBox, { key: "file", name: "AGENTS.md", path: proposal.folder, state: proposal.exists === false ? "Added" : "Modified", blocks: proposal.edits.map((edit) => [
+ (0, import_react63.createElement)(FileBox, { key: "file", name: "AGENTS.md", path: proposal.folder, state: proposal.exists === false ? "Added" : "Modified", blocks: proposal.edits.map((edit) => [
...(edit.op === "add" ? [] : editLines(edit.old)).map((line) => ({ kind: "removed", line })),
...(edit.op === "remove" ? [] : editLines(edit.text)).map((line) => ({ kind: "added", line }))
]) }),
- ...proposal.edits.map((edit, index) => edit.why ? (0, import_react62.createElement)("p", { className: "bt-learning-why", key: `why-${index}` }, edit.why) : null)
+ ...proposal.edits.map((edit, index) => edit.why ? (0, import_react63.createElement)("p", { className: "bt-learning-why", key: `why-${index}` }, edit.why) : null)
] : [
- (0, import_react62.createElement)(FileBox, { key: "file", name: "SKILL.md", path: `skills/${proposal.name}`, state: update ? "Updated" : "Added", blocks: [rows2] }),
- proposal.why ? (0, import_react62.createElement)("p", { className: "bt-learning-why", key: "why" }, proposal.why) : null
+ (0, import_react63.createElement)(FileBox, { key: "file", name: "SKILL.md", path: `skills/${proposal.name}`, state: update ? "Updated" : "Added", blocks: [rows2] }),
+ proposal.why ? (0, import_react63.createElement)("p", { className: "bt-learning-why", key: "why" }, proposal.why) : null
];
const kind = t(agents ? "AGENTS.md update" : update ? "Skill update" : "New skill");
if (outcome) {
const what = agents ? proposal.folder : proposal.name;
- return (0, import_react62.createElement)(
+ return (0, import_react63.createElement)(
"section",
{ className: "bt-q bt-q-settled bt-learning-card bt-learning-settled", role: "group", "aria-label": `${kind} · ${what}`, "data-outcome": outcome },
- (0, import_react62.createElement)(
+ (0, import_react63.createElement)(
"button",
{ type: "button", className: "bt-learning-fold", "aria-expanded": open, onClick: () => setOpen(!open) },
- (0, import_react62.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react62.createElement)(agents ? PencilIcon : MemoryIcon)),
- (0, import_react62.createElement)("span", { className: "bt-learning-kind" }, kind),
- (0, import_react62.createElement)("span", { className: "bt-learning-sum" }, `${t(outcome === "approved" ? "Approved" : "Declined")} · ${what}`)
+ (0, import_react63.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react63.createElement)(agents ? PencilIcon : MemoryIcon)),
+ (0, import_react63.createElement)("span", { className: "bt-learning-kind" }, kind),
+ (0, import_react63.createElement)("span", { className: "bt-learning-sum" }, `${t(outcome === "approved" ? "Approved" : "Declined")} · ${what}`)
),
open ? change : null
);
}
const oldDetail = update && typeof proposal.previous?.description === "string" && proposal.previous.description !== proposal.description ? proposal.previous.description : void 0;
- return (0, import_react62.createElement)(
+ return (0, import_react63.createElement)(
"section",
{ className: "bt-q bt-learning-card", role: "group", "aria-labelledby": titleId, "aria-busy": busy },
- agents ? (0, import_react62.createElement)(ProposalHead, { titleId, icon: PencilIcon, title: kind }) : (0, import_react62.createElement)(ProposalHead, { titleId, title: proposal.name, kind, detail: proposal.description, oldDetail }),
+ agents ? (0, import_react63.createElement)(ProposalHead, { titleId, icon: PencilIcon, title: kind }) : (0, import_react63.createElement)(ProposalHead, { titleId, title: proposal.name, kind, detail: proposal.description, oldDetail }),
change,
- error ? (0, import_react62.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null,
- (0, import_react62.createElement)(ProposalFoot, { busy, answer })
+ error ? (0, import_react63.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null,
+ (0, import_react63.createElement)(ProposalFoot, { busy, answer })
);
}
function ProposalHead({ titleId, icon: icon2 = MemoryIcon, title, kind, detail, oldDetail }) {
- return (0, import_react62.createElement)(
+ return (0, import_react63.createElement)(
"div",
{ className: "bt-q-head" },
- (0, import_react62.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react62.createElement)(icon2)),
- (0, import_react62.createElement)(
+ (0, import_react63.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react63.createElement)(icon2)),
+ (0, import_react63.createElement)(
"div",
{ className: "bt-q-text" },
- (0, import_react62.createElement)("p", { className: "bt-q-title", id: titleId }, title),
- kind ? (0, import_react62.createElement)("div", { className: "bt-q-detail" }, kind) : null,
- oldDetail ? (0, import_react62.createElement)("p", { className: "bt-learning-description bt-learning-old" }, (0, import_react62.createElement)("del", null, oldDetail)) : null,
- detail ? (0, import_react62.createElement)("p", { className: "bt-learning-description" }, detail) : null
+ (0, import_react63.createElement)("p", { className: "bt-q-title", id: titleId }, title),
+ kind ? (0, import_react63.createElement)("div", { className: "bt-q-detail" }, kind) : null,
+ oldDetail ? (0, import_react63.createElement)("p", { className: "bt-learning-description bt-learning-old" }, (0, import_react63.createElement)("del", null, oldDetail)) : null,
+ detail ? (0, import_react63.createElement)("p", { className: "bt-learning-description" }, detail) : null
),
- (0, import_react62.createElement)("span", { className: "bt-q-badge bt-learning-status" }, (0, import_react62.createElement)("span", { className: "bt-learning-dot", "aria-hidden": true }), t("Awaiting approval"))
+ (0, import_react63.createElement)("span", { className: "bt-q-badge bt-learning-status" }, (0, import_react63.createElement)("span", { className: "bt-learning-dot", "aria-hidden": true }), t("Awaiting approval"))
);
}
function ProposalFoot({ busy, answer }) {
- return (0, import_react62.createElement)(
+ return (0, import_react63.createElement)(
"div",
{ className: "bt-q-foot bt-learning-foot" },
- (0, import_react62.createElement)("button", { type: "button", className: "bt-learning-btn bt-learning-decline", disabled: busy, onClick: () => answer(false) }, t("Decline")),
- (0, import_react62.createElement)(
+ (0, import_react63.createElement)("button", { type: "button", className: "bt-learning-btn bt-learning-decline", disabled: busy, onClick: () => answer(false) }, t("Decline")),
+ (0, import_react63.createElement)(
"button",
{ type: "button", className: "bt-learning-btn bt-learning-approve", disabled: busy, onClick: () => answer(true) },
- (0, import_react62.createElement)(CheckIcon),
+ (0, import_react63.createElement)(CheckIcon),
t("Approve")
)
);
@@ -28281,43 +28495,43 @@ function ProposalFoot({ busy, answer }) {
var COLLAPSE_ROWS = 8;
var SIGNS = { added: "+", removed: "−", same: "" };
function FileBox({ name, path: path2, state, blocks }) {
- const [open, setOpen] = (0, import_react62.useState)(false);
+ const [open, setOpen] = (0, import_react63.useState)(false);
const all = blocks.flat();
const added = all.filter((row) => row.kind === "added").length;
const removed = all.filter((row) => row.kind === "removed").length;
const folds = all.length > COLLAPSE_ROWS;
const shut = folds && !open;
- return (0, import_react62.createElement)(
+ return (0, import_react63.createElement)(
"div",
{ className: "bt-learning-file" },
- (0, import_react62.createElement)(
+ (0, import_react63.createElement)(
"div",
{ className: "bt-learning-filehead" },
- (0, import_react62.createElement)("span", { className: "bt-learning-name" }, name),
- path2 ? (0, import_react62.createElement)("span", { className: "bt-learning-path" }, path2) : null,
- (0, import_react62.createElement)("span", { className: "bt-learning-spacer" }),
- added > 0 ? (0, import_react62.createElement)("span", { className: "bt-learning-plus" }, `+${added}`) : null,
- removed > 0 ? (0, import_react62.createElement)("span", { className: "bt-learning-minus" }, `−${removed}`) : null,
- (0, import_react62.createElement)("span", { className: `bt-learning-state bt-learning-state-${state.toLowerCase()}` }, t(state))
+ (0, import_react63.createElement)("span", { className: "bt-learning-name" }, name),
+ path2 ? (0, import_react63.createElement)("span", { className: "bt-learning-path" }, path2) : null,
+ (0, import_react63.createElement)("span", { className: "bt-learning-spacer" }),
+ added > 0 ? (0, import_react63.createElement)("span", { className: "bt-learning-plus" }, `+${added}`) : null,
+ removed > 0 ? (0, import_react63.createElement)("span", { className: "bt-learning-minus" }, `−${removed}`) : null,
+ (0, import_react63.createElement)("span", { className: `bt-learning-state bt-learning-state-${state.toLowerCase()}` }, t(state))
),
- (0, import_react62.createElement)(
+ (0, import_react63.createElement)(
"div",
{ className: shut ? "bt-learning-code bt-learning-shut" : "bt-learning-code" },
blocks.map((rows2, blockIndex) => [
- blockIndex > 0 ? (0, import_react62.createElement)("div", { className: "bt-learning-gap", key: `gap-${blockIndex}` }) : null,
- ...rows2.map((row, rowIndex) => (0, import_react62.createElement)(
+ blockIndex > 0 ? (0, import_react63.createElement)("div", { className: "bt-learning-gap", key: `gap-${blockIndex}` }) : null,
+ ...rows2.map((row, rowIndex) => (0, import_react63.createElement)(
"div",
{ className: `bt-learning-row bt-learning-${row.kind}`, key: `${blockIndex}-${rowIndex}` },
- (0, import_react62.createElement)("span", { className: "bt-learning-num", "aria-hidden": true }, row.number ?? ""),
- (0, import_react62.createElement)("span", { className: "bt-learning-sign", "aria-hidden": true }, SIGNS[row.kind]),
- (0, import_react62.createElement)("span", { className: "bt-learning-text" }, row.line || " ")
+ (0, import_react63.createElement)("span", { className: "bt-learning-num", "aria-hidden": true }, row.number ?? ""),
+ (0, import_react63.createElement)("span", { className: "bt-learning-sign", "aria-hidden": true }, SIGNS[row.kind]),
+ (0, import_react63.createElement)("span", { className: "bt-learning-text" }, row.line || " ")
))
])
),
- folds ? (0, import_react62.createElement)(
+ folds ? (0, import_react63.createElement)(
"div",
{ className: shut ? "bt-learning-morebar bt-learning-morebar-shut" : "bt-learning-morebar" },
- (0, import_react62.createElement)(
+ (0, import_react63.createElement)(
"button",
{ type: "button", className: "bt-learning-more", "aria-expanded": open, onClick: () => setOpen(!open) },
t(open ? "Show less" : "Show all {count} lines", { count: all.length })
@@ -28328,7 +28542,7 @@ function FileBox({ name, path: path2, state, blocks }) {
function LearningProposals({ turn, dock, sessionId, useRoster, actions }) {
const roster = useRoster((value) => value);
const facts = useTurnFacts(sessionId, actions);
- const [failed, setFailed] = (0, import_react62.useState)({});
+ const [failed, setFailed] = (0, import_react63.useState)({});
const bot = roster.byId?.[sessionId];
if (!bot || currentPart(bot) !== sessionId) return null;
const proposals = roster.learning?.[bot.id] ?? [];
@@ -28357,10 +28571,10 @@ function LearningProposals({ turn, dock, sessionId, useRoster, actions }) {
delete next[id];
return next;
});
- return (0, import_react62.createElement)("div", { className: dock ? "bt-learning-stack bt-learning-dock" : "bt-learning-stack" }, cards.map((proposal) => (0, import_react62.createElement)(
+ return (0, import_react63.createElement)("div", { className: dock ? "bt-learning-stack bt-learning-dock" : "bt-learning-stack" }, cards.map((proposal) => (0, import_react63.createElement)(
"div",
{ className: "bt-q-inline", key: proposal.id },
- (0, import_react62.createElement)(ProposalCard, {
+ (0, import_react63.createElement)(ProposalCard, {
proposal,
initialError: failed[proposal.id]?.error ?? failedAnswers.get(proposal.id)?.error,
onFailure,
@@ -28370,10 +28584,10 @@ function LearningProposals({ turn, dock, sessionId, useRoster, actions }) {
)));
}
function LearningTurnTail(props) {
- return (0, import_react62.createElement)(LearningProposals, { ...props, dock: false });
+ return (0, import_react63.createElement)(LearningProposals, { ...props, dock: false });
}
function LearningDock(props) {
- return (0, import_react62.createElement)(LearningProposals, { ...props, dock: true });
+ return (0, import_react63.createElement)(LearningProposals, { ...props, dock: true });
}
var LEARNING_CSS = `
.bt-learning-stack{display:flex;flex-direction:column;gap:4px}
@@ -28463,7 +28677,7 @@ function createSwitchWindow(settle) {
}
// src/client/queue-dock.js
-var import_react63 = require("react");
+var import_react64 = require("react");
var OWN_QUEUE_KINDS = /* @__PURE__ */ new Set(["user", "schedule", "user-question-reply"]);
var EMPTY_QUEUE = [];
var QUEUE_TEXT_FACTS = { collapseWhitespace: true, trimWhitespace: true };
@@ -28480,17 +28694,17 @@ function queueAttachments(content) {
var fileSizeText2 = (bytes) => typeof bytes !== "number" || !Number.isFinite(bytes) ? "" : bytes < 1024 ? `${bytes} B` : bytes < 1048576 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1048576).toFixed(1)} MB`;
function QueueFile({ attachment, label }) {
const size = fileSizeText2(attachment.bytes);
- return (0, import_react63.createElement)(
+ return (0, import_react64.createElement)(
"span",
{ className: "bt-queue-file", "aria-label": label, title: attachment.name },
- (0, import_react63.createElement)("span", { className: "bt-queue-fileicon", "aria-hidden": true }, (0, import_react63.createElement)(PaperclipIcon)),
- (0, import_react63.createElement)("span", { className: "bt-queue-filename" }, attachment.name),
- size !== "" ? (0, import_react63.createElement)("span", { className: "bt-queue-filesize" }, size) : null
+ (0, import_react64.createElement)("span", { className: "bt-queue-fileicon", "aria-hidden": true }, (0, import_react64.createElement)(PaperclipIcon)),
+ (0, import_react64.createElement)("span", { className: "bt-queue-filename" }, attachment.name),
+ size !== "" ? (0, import_react64.createElement)("span", { className: "bt-queue-filesize" }, size) : null
);
}
function QueueThumb({ attachment, loadImage, label }) {
- const [url, setUrl] = (0, import_react63.useState)(null);
- (0, import_react63.useEffect)(() => {
+ const [url, setUrl] = (0, import_react64.useState)(null);
+ (0, import_react64.useEffect)(() => {
let alive = true;
loadImage(attachment).then((resolved) => {
if (alive) setUrl(resolved);
@@ -28500,22 +28714,22 @@ function QueueThumb({ attachment, loadImage, label }) {
alive = false;
};
}, [attachment, loadImage]);
- return url === null ? (0, import_react63.createElement)("span", { className: "bt-queue-thumb", "aria-hidden": true }) : (0, import_react63.createElement)("img", { className: "bt-queue-thumb", src: url, alt: label });
+ return url === null ? (0, import_react64.createElement)("span", { className: "bt-queue-thumb", "aria-hidden": true }) : (0, import_react64.createElement)("img", { className: "bt-queue-thumb", src: url, alt: label });
}
function Preview({ text, renderFactorySlot }) {
const rendered = renderFactorySlot?.("conversation.user.text", { text, facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true });
- return (0, import_react63.createElement)("span", { className: "bt-queue-preview" }, rendered ?? text);
+ return (0, import_react64.createElement)("span", { className: "bt-queue-preview" }, rendered ?? text);
}
function EditField({ text, onChange, onSave, onCancel }) {
- const field = (0, import_react63.useRef)(null);
- (0, import_react63.useEffect)(() => {
+ const field = (0, import_react64.useRef)(null);
+ (0, import_react64.useEffect)(() => {
const node = field.current;
if (node === null) return;
node.focus();
node.style.height = "auto";
node.style.height = `${node.scrollHeight}px`;
}, [text]);
- return (0, import_react63.createElement)("textarea", {
+ return (0, import_react64.createElement)("textarea", {
ref: field,
className: "bt-queue-edit",
value: text,
@@ -28534,28 +28748,28 @@ function EditField({ text, onChange, onSave, onCancel }) {
});
}
function RowButton({ label, title, disabled, onClick, children }) {
- return (0, import_react63.createElement)("button", { type: "button", className: "bt-queue-action", "aria-label": label, title: title ?? label, disabled, onClick }, children);
+ return (0, import_react64.createElement)("button", { type: "button", className: "bt-queue-action", "aria-label": label, title: title ?? label, disabled, onClick }, children);
}
function QueueDock({ useSession, useProjection, updateQueue, loadImage, renderFactorySlot, actions }) {
const inbox = useProjection?.("inbox");
const pendingSubmissions = useSession?.((s) => s.pendingSubmissions) ?? EMPTY_QUEUE;
- const queue = (0, import_react63.useMemo)(() => {
+ const queue = (0, import_react64.useMemo)(() => {
const rows2 = (inbox?.["next-turn"] ?? EMPTY_QUEUE).filter((row) => OWN_QUEUE_KINDS.has(row.source?.kind));
const inChat = new Set(pendingSubmissions.filter((item) => item.placement === "transcript").map((item) => item.requestId));
return inChat.size === 0 ? rows2 : rows2.filter(({ source }) => source === null || typeof source !== "object" || !("rpcId" in source) || !inChat.has(source.rpcId));
}, [inbox, pendingSubmissions]);
- const pendingQueue = (0, import_react63.useMemo)(() => {
+ const pendingQueue = (0, import_react64.useMemo)(() => {
const admitted = new Set(queue.flatMap(({ source }) => source !== null && typeof source === "object" && "rpcId" in source ? [source.rpcId] : []));
return pendingSubmissions.filter((submission) => submission.placement === "queued" && !admitted.has(submission.requestId));
}, [pendingSubmissions, queue]);
const rowCount = queue.length + pendingQueue.length;
const running = useSession?.((s) => s.running) === true;
const queueMutable = useSession?.((s) => s.subagent === null || s.subagent === void 0 || s.subagent.address?.mode === "continuable") ?? true;
- const [editing, setEditing] = (0, import_react63.useState)(null);
- const [busy, setBusy] = (0, import_react63.useState)(null);
- const [collapsed, setCollapsed] = (0, import_react63.useState)(true);
- const listId = (0, import_react63.useId)();
- (0, import_react63.useEffect)(() => {
+ const [editing, setEditing] = (0, import_react64.useState)(null);
+ const [busy, setBusy] = (0, import_react64.useState)(null);
+ const [collapsed, setCollapsed] = (0, import_react64.useState)(true);
+ const listId = (0, import_react64.useId)();
+ (0, import_react64.useEffect)(() => {
if (rowCount === 0 && !collapsed) setCollapsed(true);
if (editing !== null && (!queueMutable || !queue.some((row) => row.id === editing.id))) setEditing(null);
}, [collapsed, editing, queue, queueMutable, rowCount]);
@@ -28583,77 +28797,77 @@ function QueueDock({ useSession, useProjection, updateQueue, loadImage, renderFa
if (editing === null || editing.text.trim() === "") return;
if (await applyAction(editing.id, { kind: "edit", content: [{ type: "text", text: editing.text }] }, t("Couldn’t edit the queued message — it may have started already."))) setEditing(null);
};
- return (0, import_react63.createElement)(
+ return (0, import_react64.createElement)(
"div",
{ className: "bt-queue-dock", "data-queue-dock": "" },
- (0, import_react63.createElement)(
+ (0, import_react64.createElement)(
"div",
{ className: "bt-queue-panel" },
- rowCount > 1 && (0, import_react63.createElement)(
+ rowCount > 1 && (0, import_react64.createElement)(
"button",
{ type: "button", className: "bt-queue-head", "aria-controls": listId, "aria-expanded": expanded, disabled: interactionActive, onClick: () => setCollapsed((value) => !value) },
- (0, import_react63.createElement)("span", { className: "bt-queue-lead", "aria-hidden": true }, (0, import_react63.createElement)(QueueIcon)),
- (0, import_react63.createElement)("span", { className: "bt-queue-count" }, t("{n} queued messages", { n: rowCount })),
- !listVisible && pendingQueue.length > 0 && (0, import_react63.createElement)("span", { className: "bt-queue-status", role: "status" }, t("Sending…")),
- (0, import_react63.createElement)("span", { className: "bt-queue-chev", "aria-hidden": true }, expanded ? (0, import_react63.createElement)(ChevronDownIcon) : (0, import_react63.createElement)(ChevronUpIcon))
+ (0, import_react64.createElement)("span", { className: "bt-queue-lead", "aria-hidden": true }, (0, import_react64.createElement)(QueueIcon)),
+ (0, import_react64.createElement)("span", { className: "bt-queue-count" }, t("{n} queued messages", { n: rowCount })),
+ !listVisible && pendingQueue.length > 0 && (0, import_react64.createElement)("span", { className: "bt-queue-status", role: "status" }, t("Sending…")),
+ (0, import_react64.createElement)("span", { className: "bt-queue-chev", "aria-hidden": true }, expanded ? (0, import_react64.createElement)(ChevronDownIcon) : (0, import_react64.createElement)(ChevronUpIcon))
),
- (0, import_react63.createElement)(
+ (0, import_react64.createElement)(
"ul",
{ id: listId, className: "bt-queue-list", hidden: !listVisible },
listVisible && queue.map((row) => {
const attachments = queueAttachments(row.content);
const text = textOf(row.content);
- return (0, import_react63.createElement)(
+ return (0, import_react64.createElement)(
"li",
{ key: row.id, className: "bt-queue-row" },
- rowCount === 1 && (0, import_react63.createElement)("span", { className: "bt-queue-lead", "aria-hidden": true }, (0, import_react63.createElement)(QueueIcon)),
- editing?.id === row.id ? (0, import_react63.createElement)(EditField, { text: editing.text, onChange: (text2) => setEditing({ id: row.id, text: text2 }), onSave: saveEdit, onCancel: () => setEditing(null) }) : (0, import_react63.createElement)(
- import_react63.Fragment,
+ rowCount === 1 && (0, import_react64.createElement)("span", { className: "bt-queue-lead", "aria-hidden": true }, (0, import_react64.createElement)(QueueIcon)),
+ editing?.id === row.id ? (0, import_react64.createElement)(EditField, { text: editing.text, onChange: (text2) => setEditing({ id: row.id, text: text2 }), onSave: saveEdit, onCancel: () => setEditing(null) }) : (0, import_react64.createElement)(
+ import_react64.Fragment,
null,
- attachments.length > 0 && (0, import_react63.createElement)(
+ attachments.length > 0 && (0, import_react64.createElement)(
"span",
{ className: "bt-queue-attachments" },
- attachments.map((item, index) => item.type === "image" ? (0, import_react63.createElement)(QueueThumb, { key: `${item.attachment.attachmentId}:${index}`, attachment: item.attachment, loadImage, label: t("Queued image") }) : (0, import_react63.createElement)(QueueFile, { key: `${item.attachment.attachmentId}:${item.attachment.name}:${index}`, attachment: item.attachment, label: t("Queued file {name}", { name: item.attachment.name }) }))
+ attachments.map((item, index) => item.type === "image" ? (0, import_react64.createElement)(QueueThumb, { key: `${item.attachment.attachmentId}:${index}`, attachment: item.attachment, loadImage, label: t("Queued image") }) : (0, import_react64.createElement)(QueueFile, { key: `${item.attachment.attachmentId}:${item.attachment.name}:${index}`, attachment: item.attachment, label: t("Queued file {name}", { name: item.attachment.name }) }))
),
- (0, import_react63.createElement)(Preview, { text: row.content.filter((block) => block.type === "text").map((block) => block.text).join(""), renderFactorySlot })
+ (0, import_react64.createElement)(Preview, { text: row.content.filter((block) => block.type === "text").map((block) => block.text).join(""), renderFactorySlot })
),
- queueMutable && (0, import_react63.createElement)(
+ queueMutable && (0, import_react64.createElement)(
"div",
{ className: "bt-queue-actions" },
- editing?.id === row.id ? (0, import_react63.createElement)(
- import_react63.Fragment,
+ editing?.id === row.id ? (0, import_react64.createElement)(
+ import_react64.Fragment,
null,
- (0, import_react63.createElement)(RowButton, { label: t("Save queued message"), disabled: busy !== null || editing.text.trim() === "", onClick: saveEdit }, (0, import_react63.createElement)(CheckIcon)),
- (0, import_react63.createElement)(RowButton, { label: t("Cancel editing"), disabled: busy !== null, onClick: () => setEditing(null) }, (0, import_react63.createElement)(CloseIcon))
- ) : (0, import_react63.createElement)(
- import_react63.Fragment,
+ (0, import_react64.createElement)(RowButton, { label: t("Save queued message"), disabled: busy !== null || editing.text.trim() === "", onClick: saveEdit }, (0, import_react64.createElement)(CheckIcon)),
+ (0, import_react64.createElement)(RowButton, { label: t("Cancel editing"), disabled: busy !== null, onClick: () => setEditing(null) }, (0, import_react64.createElement)(CloseIcon))
+ ) : (0, import_react64.createElement)(
+ import_react64.Fragment,
null,
- (0, import_react63.createElement)(RowButton, { label: t("Edit queued message"), title: text === null ? t("Contains non-text content, so editing is not supported yet") : void 0, disabled: busy !== null || text === null, onClick: () => {
+ (0, import_react64.createElement)(RowButton, { label: t("Edit queued message"), title: text === null ? t("Contains non-text content, so editing is not supported yet") : void 0, disabled: busy !== null || text === null, onClick: () => {
if (text !== null) setEditing({ id: row.id, text });
- } }, (0, import_react63.createElement)(PencilIcon)),
- (0, import_react63.createElement)(RowButton, { label: t("Delete queued message"), disabled: busy !== null, onClick: () => applyAction(row.id, { kind: "remove" }, t("Couldn’t delete the queued message — it may have started already.")) }, (0, import_react63.createElement)(TrashIcon)),
- (0, import_react63.createElement)(RowButton, { label: t("Steer queued message"), title: running ? void 0 : t("Only while a turn is running"), disabled: busy !== null || !running, onClick: () => applyAction(row.id, { kind: "steer" }, t("Couldn’t steer the queued message. Try again.")) }, (0, import_react63.createElement)(ArrowUpIcon))
+ } }, (0, import_react64.createElement)(PencilIcon)),
+ (0, import_react64.createElement)(RowButton, { label: t("Delete queued message"), disabled: busy !== null, onClick: () => applyAction(row.id, { kind: "remove" }, t("Couldn’t delete the queued message — it may have started already.")) }, (0, import_react64.createElement)(TrashIcon)),
+ (0, import_react64.createElement)(RowButton, { label: t("Steer queued message"), title: running ? void 0 : t("Only while a turn is running"), disabled: busy !== null || !running, onClick: () => applyAction(row.id, { kind: "steer" }, t("Couldn’t steer the queued message. Try again.")) }, (0, import_react64.createElement)(ArrowUpIcon))
)
)
);
}),
- listVisible && pendingQueue.map((submission) => (0, import_react63.createElement)(
+ listVisible && pendingQueue.map((submission) => (0, import_react64.createElement)(
"li",
{ key: submission.requestId, className: "bt-queue-row bt-queue-pending" },
- rowCount === 1 && (0, import_react63.createElement)("span", { className: "bt-queue-lead", "aria-hidden": true }, (0, import_react63.createElement)(QueueIcon)),
- submission.attachments.length > 0 && (0, import_react63.createElement)(
+ rowCount === 1 && (0, import_react64.createElement)("span", { className: "bt-queue-lead", "aria-hidden": true }, (0, import_react64.createElement)(QueueIcon)),
+ submission.attachments.length > 0 && (0, import_react64.createElement)(
"span",
{ className: "bt-queue-attachments" },
- submission.attachments.map((attachment, index) => attachment.type === "image" ? (0, import_react63.createElement)("img", { key: `${attachment.value.previewUrl}:${index}`, className: "bt-queue-thumb", src: attachment.value.previewUrl, alt: t("Queued image") }) : (0, import_react63.createElement)(QueueFile, { key: `${attachment.value.attachmentId}:${attachment.value.name}:${index}`, attachment: attachment.value, label: t("Queued file {name}", { name: attachment.value.name }) }))
+ submission.attachments.map((attachment, index) => attachment.type === "image" ? (0, import_react64.createElement)("img", { key: `${attachment.value.previewUrl}:${index}`, className: "bt-queue-thumb", src: attachment.value.previewUrl, alt: t("Queued image") }) : (0, import_react64.createElement)(QueueFile, { key: `${attachment.value.attachmentId}:${attachment.value.name}:${index}`, attachment: attachment.value, label: t("Queued file {name}", { name: attachment.value.name }) }))
),
- (0, import_react63.createElement)(Preview, { text: submission.text, renderFactorySlot }),
- (0, import_react63.createElement)("span", { className: "bt-queue-status", role: "status" }, t("Sending…")),
- queueMutable && (0, import_react63.createElement)(
+ (0, import_react64.createElement)(Preview, { text: submission.text, renderFactorySlot }),
+ (0, import_react64.createElement)("span", { className: "bt-queue-status", role: "status" }, t("Sending…")),
+ queueMutable && (0, import_react64.createElement)(
"div",
{ className: "bt-queue-actions" },
- (0, import_react63.createElement)(RowButton, { label: t("Edit queued message"), title: t("Sending…"), disabled: true }, (0, import_react63.createElement)(PencilIcon)),
- (0, import_react63.createElement)(RowButton, { label: t("Delete queued message"), title: t("Sending…"), disabled: true }, (0, import_react63.createElement)(TrashIcon)),
- (0, import_react63.createElement)(RowButton, { label: t("Steer queued message"), title: t("Sending…"), disabled: true }, (0, import_react63.createElement)(ArrowUpIcon))
+ (0, import_react64.createElement)(RowButton, { label: t("Edit queued message"), title: t("Sending…"), disabled: true }, (0, import_react64.createElement)(PencilIcon)),
+ (0, import_react64.createElement)(RowButton, { label: t("Delete queued message"), title: t("Sending…"), disabled: true }, (0, import_react64.createElement)(TrashIcon)),
+ (0, import_react64.createElement)(RowButton, { label: t("Steer queued message"), title: t("Sending…"), disabled: true }, (0, import_react64.createElement)(ArrowUpIcon))
)
))
)
@@ -28768,6 +28982,15 @@ function apply(ctx) {
savedPrefs = {};
}
const roster = createSource({ ...EMPTY_ROSTER, prefs: savedPrefs });
+ ctx.effect(() => {
+ const publish2 = () => publishOwnedSessions(window, ownedSessionIds(roster.getSnapshot()));
+ const off = roster.subscribe(publish2);
+ publish2();
+ return () => {
+ off();
+ publishOwnedSessions(window, []);
+ };
+ }, "ds-bot: publish owned sessions");
const unreadStore = sharedMap(STORAGE.unread);
const reactionStore = sharedMap(STORAGE.reactions);
const seenStore = sharedMap(STORAGE.seen);
@@ -28878,6 +29101,7 @@ function apply(ctx) {
const live2 = {};
if (value.connectors !== void 0 && JSON.stringify(value.connectors) !== JSON.stringify(current.connectors ?? [])) live2.connectors = value.connectors;
if (value.capabilityStatuses !== void 0 && JSON.stringify(value.capabilityStatuses) !== JSON.stringify(current.capabilityStatuses ?? {})) live2.capabilityStatuses = value.capabilityStatuses;
+ if (value.operatorTasks !== void 0 && JSON.stringify(value.operatorTasks) !== JSON.stringify(current.operatorTasks ?? {})) live2.operatorTasks = value.operatorTasks;
if (value.learning !== void 0 && JSON.stringify(value.learning) !== JSON.stringify(current.learning ?? {})) live2.learning = value.learning;
if (value.learningSettled !== void 0 && JSON.stringify(value.learningSettled) !== JSON.stringify(current.learningSettled ?? {})) live2.learningSettled = value.learningSettled;
if (value.btwCards !== void 0 && JSON.stringify(value.btwCards) !== JSON.stringify(current.btwCards ?? {})) live2.btwCards = value.btwCards;
@@ -29426,10 +29650,10 @@ function apply(ctx) {
const appComputer = globalThis.dsBotApp;
if (typeof appComputer?.computer === "function") {
ctx.effect(() => {
- const nameOf2 = (id) => roster.getSnapshot().byId[id]?.name ?? "a Bot";
+ const nameOf3 = (id) => roster.getSnapshot().byId[id]?.name ?? "a Bot";
const sync = () => {
const live2 = computer.getSnapshot();
- const name = (id) => nameOf2(id);
+ const name = (id) => nameOf3(id);
const look = (id) => lookOf(roster.getSnapshot().byId[id]);
const rows2 = (live2.leases ?? []).map((entry) => ({
botId: entry.botId,
@@ -29695,6 +29919,7 @@ function apply(ctx) {
[MODEL_CSS + FOLDER_CSS + BOT_SETTINGS_CSS + AGENT_CARDS_CSS + GROUP_SETTINGS_CSS + AVATAR_LIBRARY_CSS, "models"],
[USAGE_CSS, "usage"],
[SCHEDULE_CSS, "schedules"],
+ [OPERATOR_TASKS_CSS, "operator-tasks"],
[FEEDBACK_CSS, "feedback"],
[ABOUT_CSS, "about"],
[MEMBER_CSS, "members"],
@@ -29812,7 +30037,9 @@ function apply(ctx) {
const sync = () => {
const list = ctx.sessions.list.getSnapshot();
const main = Object.values(list.byId ?? {}).find((session) => (session?.retainedBy?.mainView ?? 0) > 0)?.id;
- const plain = isAgentSessionId(main);
+ const snap = roster.getSnapshot();
+ const unowned = main !== void 0 && !ownedSessionIds(snap).includes(main);
+ const plain = isAgentSessionId(main) || snap.ready && unowned;
setPlain(plain);
if (plain) dropPanels();
if (main === previous) return;
diff --git a/ds-bot/index.js b/ds-bot/index.js
index 8b35617981..461d20a228 100644
--- a/ds-bot/index.js
+++ b/ds-bot/index.js
@@ -41,12 +41,14 @@ import * as usage from './src/host/usage.js'
import * as update from './src/host/update.js'
import * as dshUpdate from './src/host/dsh-update.js'
import * as thinking from './src/host/thinking.js'
+import * as operatorTasks from './src/host/operator-tasks.js'
import * as channel from './src/host/channel.js'
import * as feed from './src/host/feed.js'
import * as im from './src/host/im/index.js'
import * as officeSkills from './src/host/office-skills.js'
import * as goalSkills from './src/host/goal-skills.js'
import * as localAgents from './src/host/local-agents/index.js'
+import * as creditGuard from './src/host/credit-guard.js'
export { COLORS } from './src/host/constants.js'
@@ -58,7 +60,7 @@ export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'ses
// install. Listeners run and tools are listed in registration order, so this order holds:
// usage meters model requests after every listener that rewrites them. privacy checks a
// call before the hooks of tools do, so a closed call never reaches a card they show.
-const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, groupLog, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, computer, usage, update, dshUpdate, thinking, feed, im, channel, officeSkills, goalSkills, localAgents]
+const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, groupLog, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, computer, usage, update, dshUpdate, thinking, feed, im, operatorTasks, channel, officeSkills, goalSkills, localAgents, creditGuard]
export function apply(ctx, config = {}) {
createRuntime(ctx, config)
diff --git a/ds-bot/src/client/brainstorm.js b/ds-bot/src/client/brainstorm.js
new file mode 100644
index 0000000000..2bb8051611
--- /dev/null
+++ b/ds-bot/src/client/brainstorm.js
@@ -0,0 +1,12 @@
+// The composer's Brainstorm row. It only types the word at the caret: the word itself
+// is what switches a Bot into its show-me-options-first stance (the operator's
+// AGENTS.md), so no mode flips and nothing else is sent.
+export const BRAINSTORM_TEXT = 'brainstorm '
+
+export const canBrainstorm = inputActions => typeof inputActions?.insertText === 'function'
+
+export function insertBrainstorm(inputActions) {
+ if (!canBrainstorm(inputActions)) return false
+ inputActions.insertText(BRAINSTORM_TEXT, inputActions.captureInsertion?.())
+ return true
+}
diff --git a/ds-bot/src/client/composer.js b/ds-bot/src/client/composer.js
index ee6ce285fd..1be35479ab 100644
--- a/ds-bot/src/client/composer.js
+++ b/ds-bot/src/client/composer.js
@@ -1,12 +1,13 @@
import { createElement as h, Fragment, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
-import { ChatsIcon, ClockIcon, GoalIcon, MicIcon, PaperclipIcon, PeopleIcon, PlusIcon, WaveIcon } from './icons.js'
+import { BulbIcon, ChatsIcon, ClockIcon, GoalIcon, MicIcon, PaperclipIcon, PeopleIcon, PlusIcon, WaveIcon } from './icons.js'
import { canSetGoal } from './goal.js'
import { BotMark } from './mark.js'
import { stepMenuFocus, useLinger, useViewport, viewBottom } from './motion.js'
import { t } from './i18n.js'
import { insertComposerNewline, sendsOnEnter } from './enter-key.js'
import { enterSteers, steerable } from './enter-steer.js'
+import { canBrainstorm, insertBrainstorm } from './brainstorm.js'
// -------------------------------------------------------------------------
// Composer: dictation mic and the voice-chat button. The shell's send
@@ -200,6 +201,10 @@ export function ComposerPlus({ sessionId, inputActions, useInput, useRoster, act
actions.referenceChat(sessionId, inputActions?.captureInsertion?.())
}
const canReference = typeof inputActions?.captureInsertion === 'function' && actions.canReferenceChat()
+ const brainstorm = () => {
+ setOpen(null)
+ insertBrainstorm(inputActions)
+ }
const room = roster.roomsById?.[sessionId]
const goal = () => {
setOpen(null)
@@ -216,6 +221,7 @@ export function ComposerPlus({ sessionId, inputActions, useInput, useRoster, act
},
shown.files ? h('button', { type: 'button', role: 'menuitem', onClick: attach }, h(PaperclipIcon), h('span', { className: 'bt-menu-label' }, t('Add files'))) : null,
canReference ? h('button', { type: 'button', role: 'menuitem', onMouseDown: keepComposerFocus, onClick: reference }, h(ChatsIcon), h('span', { className: 'bt-menu-label' }, t('Reference a chat'))) : null,
+ canBrainstorm(inputActions) ? h('button', { type: 'button', role: 'menuitem', onMouseDown: keepComposerFocus, onClick: brainstorm }, h(BulbIcon), h('span', { className: 'bt-menu-label' }, t('Brainstorm'))) : null,
canSetGoal(room, roster) ? h('button', { type: 'button', role: 'menuitem', onClick: goal }, h(GoalIcon), h('span', { className: 'bt-menu-label' }, t('Set a goal'))) : null,
h('button', { type: 'button', role: 'menuitem', onClick: schedule }, h(ClockIcon), h('span', { className: 'bt-menu-label' }, t('Scheduled task')))), document.body) : null)
}
diff --git a/ds-bot/src/client/details-drawer.js b/ds-bot/src/client/details-drawer.js
index fcbd7fa748..d82bf738d9 100644
--- a/ds-bot/src/client/details-drawer.js
+++ b/ds-bot/src/client/details-drawer.js
@@ -13,6 +13,7 @@ import { ModelMenu, modelOf } from './model-menu.js'
import { FolderMenu } from './folder-menu.js'
import { MemoryRow } from './memory-panel.js'
import { ScheduleSummary } from './schedules.js'
+import { OperatorTasks } from './operator-tasks.js'
import { useGlide, useMorph } from './motion.js'
import { MemberApprovals, MemberState, StopMemberWork, StopRoomWork, useMemberWork, workState } from './member-status.js'
import { canSetGoal, goalView, hasGoalAdmin } from './goal.js'
@@ -339,6 +340,7 @@ export function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, ro
usage ? h('div', { key: 'usage' }, h('div', { className: 'bt-section-title' }, t('Usage')),
h('div', { className: 'bt-kv' }, h('span', null, bot.name), h('span', null, usage))) : null,
h(ScheduleSummary, { key: 'routines', bot, actions }),
+ h(OperatorTasks, { key: 'operator-tasks', bot, roster }),
] : null,
bot && tab === 'browser' ? h(BrowserCards, { bot, sessionId, roster, actions, useBrowserTabs, useBrowserPages }) : null)]
}
diff --git a/ds-bot/src/client/header.js b/ds-bot/src/client/header.js
index 1cb0390666..d24a7769aa 100644
--- a/ds-bot/src/client/header.js
+++ b/ds-bot/src/client/header.js
@@ -7,6 +7,7 @@ import { AgentBadge } from './agent-badge.js'
import { ActivityIndicator } from './activity-row.js'
import { clockLabel, openingTurn, unseenSince } from './cells.js'
import { GoalIsland, goalView } from './goal.js'
+import { OperatorBadge, operatorCount, unresolvedCount } from './operator-tasks.js'
import { viewBottom } from './motion.js'
import { t } from './i18n.js'
@@ -131,6 +132,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')), !away && bot?.engine ? h(AgentBadge, { engine: bot.engine }) : 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 cc4b3d202f..67da0eaa20 100644
--- a/ds-bot/src/client/i18n.js
+++ b/ds-bot/src/client/i18n.js
@@ -10,6 +10,7 @@ const ZH = {
Working: '进行中',
'Waiting for your answer': '等你回答',
'Waiting for {names}': '等 {names} 交回',
+ 'Waiting for a teammate': '等队友交回工作',
'Unread activity': '有未读',
'Not read yet': '未读',
Search: '搜索',
@@ -1260,6 +1261,7 @@ const ZH = {
'Add files': '添加文件',
'Reference a chat': '引用对话',
'Chat with {name}': '与 {name} 的对话',
+ Brainstorm: '头脑风暴',
'Scheduled task': '定时任务',
'Send to': '发给',
'Scheduled task: {text}': '定时任务:{text}',
@@ -1313,6 +1315,39 @@ 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': '你的要求',
+ 'The ask is not recorded': '没有记录你的要求',
+ '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}」里',
+ 'Question card': '问题卡片',
+ 'Answer card': '待回答的卡片',
+ 'A card waiting for your answer': '一张等你回答的卡片',
+ 'Key request': '密钥请求',
+ 'Tool approval': '工具审批',
+ 'Decision {id}': '决定 {id}',
+ 'due {date}': '截止 {date}',
+ 'not shown on a card yet': '还没有以卡片形式出现',
+ 'Working now': '正在工作',
+ 'Moving on to a fresh part': '正在换到新的对话段',
+ 'Running {tool} on {target}': '正在对 {target} 运行 {tool}',
+ 'Running {tool}': '正在运行 {tool}',
+ Order: '委托',
+ 'From {name}': '来自 {name}',
+ 'Waiting on': '在等',
'Automation tasks are off in DSH': 'DSH 的「自动化任务」没有打开',
'No such Bot': '没有这个 Bot',
'No such Bot or group chat': '没有这个 Bot 或群聊',
diff --git a/ds-bot/src/client/icons.js b/ds-bot/src/client/icons.js
index c0b86e8a4e..078715a90c 100644
--- a/ds-bot/src/client/icons.js
+++ b/ds-bot/src/client/icons.js
@@ -71,6 +71,8 @@ export const ConnectorIcon = lineIcon(['M7 10a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5
export const SignOutIcon = lineIcon(['M8.5 17H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h2.5', 'M10 10h6.5', 'M13.5 7l3 3-3 3'])
export const SignInIcon = lineIcon(['M11.5 3H14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-2.5', 'M3.5 10H10', 'M7 7l3 3-3 3'])
export const PaperclipIcon = lineIcon(['M15.5 9.5l-5.6 5.6a3.4 3.4 0 0 1-4.8-4.8l6.1-6.1a2.25 2.25 0 0 1 3.2 3.2l-6 6a1.1 1.1 0 0 1-1.6-1.6l5.5-5.5'])
+// A bulb on a short base: an idea, for the composer's brainstorm row.
+export const BulbIcon = lineIcon(['M7.5 14.5h5', 'M8.25 17h3.5', 'M7.5 12.5a5 5 0 1 1 5 0v2h-5z'])
export const ClockIcon = lineIcon(['M10 3.5a6.5 6.5 0 1 1 0 13 6.5 6.5 0 0 1 0-13z', 'M10 6.5V10l2.5 1.5'])
// Six broad, shallow teeth around a wide hub: it reads as a gear even at 15px.
export const GearIcon = lineIcon(['M10 7.4a2.6 2.6 0 1 1 0 5.2 2.6 2.6 0 0 1 0-5.2z', 'M7.85 4.4l.29-1.87a7.7 7.7 0 0 1 3.72 0l.29 1.87a6 6 0 0 1 1.63.94l1.76-.69a7.7 7.7 0 0 1 1.86 3.23l-1.47 1.18a6 6 0 0 1 0 1.88l1.47 1.18a7.7 7.7 0 0 1-1.86 3.23l-1.76-.69a6 6 0 0 1-1.63.94l-.29 1.87a7.7 7.7 0 0 1-3.72 0l-.29-1.87a6 6 0 0 1-1.63-.94l-1.76.69a7.7 7.7 0 0 1-1.86-3.23l1.47-1.18a6 6 0 0 1 0-1.88L2.6 7.88a7.7 7.7 0 0 1 1.86-3.23l1.76.69a6 6 0 0 1 1.63-.94z'])
diff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.js
index e666fb3c9f..1e648a9602 100644
--- a/ds-bot/src/client/index.js
+++ b/ds-bot/src/client/index.js
@@ -1,7 +1,7 @@
import { call } from './api.js'
import { isHex, inkText, paintCss } from './inks.js'
import { DEFAULT_MASK, SHAPES, markupCache, maskOf } from './characters.js'
-import { createSource, EMPTY_ROSTER, indexRoster, isAgentSession } from './sources.js'
+import { createSource, EMPTY_ROSTER, indexRoster, isAgentSession, ownedSessionIds, publishOwnedSessions } from './sources.js'
import { teamActions } from './team-actions.js'
import { themeCss, shellTokens, registry, registerShape, registerTheme, allThemes, layoutOf, widthOf, flatWidthOf } from './themes.js'
import { MENTION_ORIGIN, currentPart } from './text.js'
@@ -40,6 +40,7 @@ import { GROUP_SETTINGS_CSS } from './group-settings.js'
import { FOLDER_CSS } from './folder-menu.js'
import { USAGE_CSS } from './usage-page.js'
import { SCHEDULE_CSS } from './schedules.js'
+import { OPERATOR_TASKS_CSS } from './operator-tasks.js'
import { STORAGE, migrateStorage } from './storage.js'
import { noteLeft, setUnread, sharedMap, toggleReaction } from './shared-map.js'
import { freePriority, groupsFor, readMode, surfaceGroups, writeMode } from './surface.js'
@@ -68,6 +69,18 @@ export function apply(ctx) {
let savedPrefs = {}
try { savedPrefs = JSON.parse(localStorage.getItem(PREFS_KEY) ?? '{}') ?? {} } catch { savedPrefs = {} }
const roster = createSource({ ...EMPTY_ROSTER, prefs: savedPrefs })
+ // local: sidebar-coexistence. The shell files every Session it lists; the ones this
+ // plugin owns (Bot chats and parts, group Sessions, Agent Sessions) are published
+ // here so the shell can keep them out of its own sections.
+ ctx.effect(() => {
+ const publish = () => publishOwnedSessions(window, ownedSessionIds(roster.getSnapshot()))
+ const off = roster.subscribe(publish)
+ publish()
+ return () => {
+ off()
+ publishOwnedSessions(window, [])
+ }
+ }, 'ds-bot: publish owned sessions')
const unreadStore = sharedMap(STORAGE.unread)
const reactionStore = sharedMap(STORAGE.reactions)
// When each conversation was last left; a visit compares new turns against it.
@@ -198,6 +211,7 @@ export function apply(ctx) {
const live = {}
if (value.connectors !== undefined && JSON.stringify(value.connectors) !== JSON.stringify(current.connectors ?? [])) live.connectors = value.connectors
if (value.capabilityStatuses !== undefined && JSON.stringify(value.capabilityStatuses) !== JSON.stringify(current.capabilityStatuses ?? {})) live.capabilityStatuses = value.capabilityStatuses
+ if (value.operatorTasks !== undefined && JSON.stringify(value.operatorTasks) !== JSON.stringify(current.operatorTasks ?? {})) live.operatorTasks = value.operatorTasks
if (value.learning !== undefined && JSON.stringify(value.learning) !== JSON.stringify(current.learning ?? {})) live.learning = value.learning
if (value.learningSettled !== undefined && JSON.stringify(value.learningSettled) !== JSON.stringify(current.learningSettled ?? {})) live.learningSettled = value.learningSettled
if (value.btwCards !== undefined && JSON.stringify(value.btwCards) !== JSON.stringify(current.btwCards ?? {})) live.btwCards = value.btwCards
@@ -1033,6 +1047,7 @@ export function apply(ctx) {
[MODEL_CSS + FOLDER_CSS + BOT_SETTINGS_CSS + AGENT_CARDS_CSS + GROUP_SETTINGS_CSS + AVATAR_LIBRARY_CSS, 'models'],
[USAGE_CSS, 'usage'],
[SCHEDULE_CSS, 'schedules'],
+ [OPERATOR_TASKS_CSS, 'operator-tasks'],
[FEEDBACK_CSS, 'feedback'],
[ABOUT_CSS, 'about'],
[MEMBER_CSS, 'members'],
@@ -1150,7 +1165,11 @@ export function apply(ctx) {
const sync = () => {
const list = ctx.sessions.list.getSnapshot()
const main = Object.values(list.byId ?? {}).find(session => (session?.retainedBy?.mainView ?? 0) > 0)?.id
- const plain = isAgentSessionId(main)
+ // local: sidebar-coexistence. A Session the roster does not own was opened from the
+ // shell's own sections, so it shows as the native dsh page.
+ const snap = roster.getSnapshot()
+ const unowned = main !== undefined && !ownedSessionIds(snap).includes(main)
+ const plain = isAgentSessionId(main) || (snap.ready && unowned)
setPlain(plain)
if (plain) dropPanels()
if (main === previous) return
diff --git a/ds-bot/src/client/mark.js b/ds-bot/src/client/mark.js
index be620c91b2..9c4eecec9e 100644
--- a/ds-bot/src/client/mark.js
+++ b/ds-bot/src/client/mark.js
@@ -98,6 +98,13 @@ function MainStar() {
h('path', { d: 'M10 2.4l2.29 5.04 5.51.63-4.09 3.74 1.11 5.42L10 14.5l-4.82 2.73 1.11-5.42L2.2 8.07l5.51-.63z' }))
}
+// local: waiting-mark. A small clock for a Bot whose handed-on work has not come back.
+function WaitIcon({ size = 9 }) {
+ return h('svg', { viewBox: '0 0 10 10', width: size, height: size, 'aria-hidden': true },
+ h('circle', { cx: 5, cy: 5, r: 3.45 }),
+ h('path', { d: 'M5 2.75v2.4l1.75 .95' }))
+}
+
// Marks settle with a short squash when a run finishes.
function useSettled(state) {
const prev = useRef(state)
@@ -123,7 +130,8 @@ export function BotAvatar({ bot, size, state = 'idle', main, admin, badge = true
badgeKind === 'working' ? h('span', { className: 'bt-badge bt-badge-working', 'aria-label': t('Working'), role: 'img' }) : null,
badgeKind === 'alert' ? h('span', { className: 'bt-badge bt-badge-alert', 'aria-label': t('Waiting for your answer'), role: 'img' }, '?') : null,
badgeKind === 'admin' ? h('span', { className: 'bt-badge bt-badge-admin', 'aria-label': t('Admin'), role: 'img' }, h(StarIcon)) : null,
- badgeKind === 'main' ? h('span', { className: 'bt-badge bt-badge-main', 'aria-label': t('Main Bot'), role: 'img' }, h(MainStar)) : null)
+ badgeKind === 'main' ? h('span', { className: 'bt-badge bt-badge-main', 'aria-label': t('Main Bot'), role: 'img' }, h(MainStar)) : null,
+ badge && state === 'waiting' ? h('span', { className: 'bt-badge bt-badge-waiting', role: 'img', 'aria-label': t('Waiting for a teammate') }, h(WaitIcon)) : null)
}
// A group avatar seats its members' characters in the frame: two on a
diff --git a/ds-bot/src/client/operator-tasks.js b/ds-bot/src/client/operator-tasks.js
new file mode 100644
index 0000000000..381980dc90
--- /dev/null
+++ b/ds-bot/src/client/operator-tasks.js
@@ -0,0 +1,125 @@
+// 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 = { 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')
+const where = (roster, item) => (item.roomId ? t('in group "{name}"', { name: roster.roomsById?.[item.roomId]?.name ?? t('a group') }) : '')
+
+function unresolvedLine(item) {
+ switch (item.kind) {
+ case 'question': return { label: t('Question card'), text: item.text || t('A card waiting for your answer') }
+ case 'view': return { label: t('Answer card'), text: item.text || t('A card waiting for your answer') }
+ case 'key': return { label: t('Key request'), text: item.detail ? `${item.text}: ${item.detail}` : item.text }
+ case 'approval': return { label: t('Tool approval'), text: item.detail ? `${item.text}: ${item.detail}` : item.text }
+ case 'decision': return {
+ label: t('Decision {id}', { id: item.id }),
+ text: item.text,
+ note: [item.due ? t('due {date}', { date: item.due }) : '', item.carded ? '' : t('not shown on a card yet')].filter(Boolean).join(', '),
+ }
+ default: return { label: '', text: item.text ?? '' }
+ }
+}
+
+// The running tool step, when there is one. It is a step on the job, never the job.
+const stepOf = (item) => {
+ if (item.switching) return t('Moving on to a fresh part')
+ if (item.tool === undefined) return undefined
+ return item.target ? t('Running {tool} on {target}', { tool: item.tool, target: item.target }) : t('Running {tool}', { tool: item.tool })
+}
+
+// What a running item is doing, in its own words.
+const doingOf = (item) => stepOf(item) ?? item.text ?? t('Working')
+
+// The operator's own words for the job: the first line of the message they sent, as it
+// was written. The step below it may move on, but the ask stays what it was.
+const askOf = (item) => {
+ const line = String(item.text ?? '').split(/\r?\n/).map(part => part.trim()).find(part => part !== '')
+ return line ?? t('The ask is not recorded')
+}
+
+function activeLine(item, roster) {
+ switch (item.kind) {
+ 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: askOf(item), note: stepOf(item) }
+ case 'relay': return { label: t('Relayed by {name}', { name: item.via ?? t('a teammate') }), text: askOf(item), note: stepOf(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 })),
+ items.length === 0
+ ? h('div', { className: 'bt-ops-empty' }, empty)
+ : h('ul', { className: 'bt-ops-list' }, items.map((item) => {
+ const shown = line(item, roster)
+ return h('li', { key: item.key, className: 'bt-ops-item', 'data-kind': item.kind },
+ h('div', { className: 'bt-ops-top' },
+ h('span', { className: 'bt-ops-label' }, shown.label),
+ item.at ? h('span', { className: 'bt-ops-age', title: new Date(item.at).toLocaleString() }, relativeShort(item.at)) : null),
+ shown.text ? h('div', { className: 'bt-ops-text' }, shown.text) : null,
+ shown.note ? h('div', { className: 'bt-ops-note' }, shown.note) : null)
+ })))
+}
+
+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: "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 = `
+.bt-ops-empty{font-size:12px;line-height:16px;color:var(--bt-ink-3);padding:2px 0}
+.bt-ops-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
+.bt-ops-item{padding:6px 8px;border-radius:8px;background:var(--bt-hover);min-width:0}
+.bt-ops-top{display:flex;align-items:baseline;gap:8px}
+.bt-ops-label{flex:1;min-width:0;font-size:12px;line-height:16px;font-weight:600;color:var(--bt-ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.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;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/client/sidebar.js b/ds-bot/src/client/sidebar.js
index 80c0f6b58c..cd48f48454 100644
--- a/ds-bot/src/client/sidebar.js
+++ b/ds-bot/src/client/sidebar.js
@@ -69,7 +69,8 @@ function BotRow({ bot, roster, actions, useSessions, useSessionStatus, useSessio
const unread = useSessionStatus(map => map.get(part)?.completionUnread === true || map.get(part)?.pendingInteraction !== undefined) || (marked && !active)
useMarkedUnread(id, active, marked, actions)
const main = isMainOf(roster, id)
- const tile = roster.mainBotId === id
+ // local: sidebar-coexistence. Every Main Bot tiles, not only the seated one.
+ const tile = main || roster.mainBotId === id
const approval = useApproval(useWork, entry => entry.botId === id)
const alert = roster.questions?.[part] !== undefined || approval
const doing = useActivity(map => map[id])
@@ -448,14 +449,14 @@ function useListGlide(listRef, layout, key) {
}, [layout, key])
}
-// In the Bot view the left column is ours, drawn on
over the shell's
-// collapsed sidebar: the open column or the avatar rail push the conversation
-// over, the drawer floats above it. Its right edge drags the open width, and
-// down to the rail.
-function LeftColumn({ mode, width, onGrip, leaving, children }) {
- return createPortal(h('div', { className: 'bt-leftcol', 'data-left': mode, 'data-leaving': leaving || undefined, 'aria-hidden': leaving || undefined, style: { width: `${width}px` } },
+// local: sidebar-coexistence. The Bot list sits inside the shell's own sidebar
+// column (the sidebar.workspaces slot), beside the shell's own sections, rather
+// than in a column drawn on over a collapsed shell sidebar. The shell's
+// column owns the width and the resize, so the grip stays hidden (styles.js).
+function LeftColumn({ mode, onGrip, leaving, children }) {
+ return h('div', { className: 'bt-leftcol', 'data-left': mode, 'data-leaving': leaving || undefined, 'aria-hidden': leaving || undefined },
children,
- h('div', { className: 'bt-leftcol-grip', role: 'separator', 'aria-orientation': 'vertical', 'aria-label': t('Resize sidebar'), title: t('Resize sidebar'), onPointerDown: onGrip })), document.body)
+ h('div', { className: 'bt-leftcol-grip', role: 'separator', 'aria-orientation': 'vertical', 'aria-label': t('Resize sidebar'), title: t('Resize sidebar'), onPointerDown: onGrip }))
}
// The top-left switch hides the whole column and brings it back. Under a
@@ -494,6 +495,7 @@ export function TeamSidebar(props) {
const panelYield = useUi(value => value.panelYield === true)
const bootFailed = useUi(value => value.bootFailed === true)
const renameSection = useUi(value => value.renameSection)
+ const accountSeated = useUi(value => value.accountSeated === true)
props.useRegistry(value => value)
const frameSnap = props.useFrame ? props.useFrame(value => value) : { viewport: typeof window === 'undefined' ? 0 : window.innerWidth, sidebarWidth: FALLBACK_SIDEBAR_WIDTH, collapsedWidth: 0 }
const pref = props.useSidebarPref ? props.useSidebarPref(value => value) : 'open'
@@ -517,7 +519,7 @@ export function TeamSidebar(props) {
const order = useMemo(() => {
const stamps = JSON.parse(updated)
const entries = [
- ...roster.bots.filter(bot => bot.id !== roster.mainBotId).map(bot => ({ kind: 'bot', item: bot, at: stamps[currentPart(bot)] ?? bot.createdAt })),
+ ...roster.bots.filter(bot => !isMainOf(roster, bot.id) && bot.id !== roster.mainBotId).map(bot => ({ kind: 'bot', item: bot, at: stamps[currentPart(bot)] ?? bot.createdAt })),
...roster.rooms.map(room => ({ kind: 'room', item: room, at: stamps[room.id] ?? room.createdAt })),
// The Agent sorts by its most recent Session, falling back to when it was added.
...(roster.agents ?? []).map(agent => ({ kind: 'agent', item: agent, at: Math.max(0, ...agent.sessions.map(id => stamps[id] ?? 0)) || agent.createdAt })),
@@ -531,6 +533,9 @@ export function TeamSidebar(props) {
[order, sectionSet],
)
const main = roster.byId[roster.mainBotId]
+ // local: sidebar-coexistence. The seated Main Bot first, then every other Main Bot.
+ const tileBots = [main, ...(roster.mainBotIds ?? []).map(id => roster.byId[id])]
+ .filter((bot, index, all) => bot !== undefined && all.findIndex(other => other?.id === bot.id) === index)
const glideKey = useMemo(
() => `${sections.map(s => `${s.id}:${s.collapsed ? 1 : 0}`).join(',')}|${order.map(entry => `${entry.item.id}:${entry.item.sectionId ?? ''}`).join(',')}`,
[sections, order],
@@ -571,11 +576,11 @@ export function TeamSidebar(props) {
// collapsed track; a drawer floats over the rail's place, so it pushes as much
// as the rail and the chat stays put when it opens or closes.
const openWidth = drag?.width ?? frameSnap.sidebarWidth
- const ourWidth = shown === 'rail' ? RAIL_WIDTH : openWidth
const pushed = mode === 'open' ? openWidth : mode === 'hidden' ? 0 : RAIL_WIDTH
useLayoutEffect(() => {
if (typeof document === 'undefined') return
- chatRoom.setLeft(Math.max(0, pushed - (frameSnap.collapsedWidth ?? 0)))
+ // local: sidebar-coexistence. The shell's column already makes room for the list.
+ chatRoom.setLeft(null)
}, [pushed, frameSnap.collapsedWidth])
useEffect(() => () => { if (typeof document !== 'undefined') chatRoom.setLeft(null) }, [])
@@ -722,7 +727,7 @@ export function TeamSidebar(props) {
if (requested.current) return undefined
requested.current = true
quiet(true)
- actions.toggleSidebar()
+ // local: sidebar-coexistence. The shell's sidebar holds the Bot list, so it is never collapsed under it.
clearTimeout(requestLapse.current)
requestLapse.current = setTimeout(() => { requested.current = false; quiet(false); setLapsed(value => value + 1) }, 300)
return undefined
@@ -767,7 +772,8 @@ export function TeamSidebar(props) {
}
// The switch (top-left button, the shortcut) hides the whole column or brings
// back the one it hid.
- const onToggle = () => actions.toggleLeftHidden?.()
+ // local: sidebar-coexistence. The shell's own sidebar switch hides the column that holds the list.
+ const onToggle = () => (actions.toggleSidebar ?? actions.toggleLeftHidden)?.()
// The shell's sidebar shortcut is caught on its way down, before the shell's
// own listener on window sees it: left to the shell, it would expand the shell's
// sidebar first and our sync would pull it back, a visible flash.
@@ -800,11 +806,14 @@ export function TeamSidebar(props) {
h('span', { className: 'bt-rail-sep', 'aria-hidden': true }))
// The foot stands in for the shell's hidden footer: the account avatar, and on
// the rail the new-chat button above it.
+ // local: sidebar-coexistence. The shell's footer seats the account once; a seated
+ // account is not drawn a second time here.
+ const seated = accountSeated
const foot = wideContent
- ? h('div', { className: 'bt-leftcol-foot' }, h(AccountLauncher, { seat: false, actions }))
+ ? (seated ? null : h('div', { className: 'bt-leftcol-foot' }, h(AccountLauncher, { seat: false, actions })))
: h('div', { className: 'bt-leftcol-foot bt-leftcol-foot-rail' },
h('button', { type: 'button', className: 'bt-round', 'aria-label': t('New…'), title: t('New…'), onClick: () => actions.openNewChat('new') }, h(PlusIcon)),
- h(AccountLauncher, { seat: false, actions }))
+ seated ? null : h(AccountLauncher, { seat: false, actions }))
const content = h('div', { className: wideContent ? 'bt-side' : 'bt-side bt-rail', onKeyDown: typeToSearch },
top,
wideContent && roster.readOnly ? h('div', { className: 'bt-hint bt-read-only', role: 'status' }, hostText(roster.readOnly)) : null,
@@ -813,7 +822,8 @@ export function TeamSidebar(props) {
onDragEnd: () => { setDragId(null); setDropTarget(null) },
onDragLeave: (event) => { if (!event.currentTarget.contains(event.relatedTarget)) setDropTarget(null) },
},
- wideContent ? (main ? h(BotRow, { ...rowProps, bot: main, marked: markedUnread[main.id] === true }) : roster.ready ? null : h('div', { className: 'bt-hint' }, bootFailed ? bootHint() : t('Setting up your Main Bot…'))) : null,
+ // local: sidebar-coexistence. Every Main Bot tiles in one grid above the sections.
+ wideContent ? (tileBots.length > 0 ? h('div', { className: 'bt-tile-grid' }, tileBots.map(bot => h(BotRow, { key: bot.id, ...rowProps, bot, marked: markedUnread[bot.id] === true }))) : roster.ready ? null : h('div', { className: 'bt-hint' }, bootFailed ? bootHint() : t('Setting up your Main Bot…'))) : null,
sections.length > 0 && wideContent
? h('div', {
className: 'bt-sec-ungrouped',
@@ -838,7 +848,7 @@ export function TeamSidebar(props) {
foot)
return h(Fragment, null,
h(TitleToggle, { hidden: mode === 'hidden', onToggle }),
- shown === 'hidden' ? null : h(LeftColumn, { mode: shown, width: ourWidth, onGrip: startDrag, leaving }, content))
+ shown === 'hidden' ? null : h(LeftColumn, { mode: shown, onGrip: startDrag, leaving }, content))
}
// The update button at the sidebar's top right: a cloud while a newer DS Bot —
@@ -1181,7 +1191,7 @@ function useLandOnMainBot(roster, useSessions, actions) {
const lastBot = useRef(null)
useEffect(() => {
if (!roster.ready || !roster.mainBotId) return undefined
- const [id, blank] = mainView.split('|')
+ const [id] = mainView.split('|')
const bot = id === '' ? undefined : roster.byId[id]
if (bot !== undefined) {
lastBot.current = { botId: bot.id, sessionId: id }
@@ -1196,8 +1206,9 @@ function useLandOnMainBot(roster, useSessions, actions) {
if ((room.sessionId ?? room.id) !== id) actions.openSession(room.id)
return undefined
}
- // A DSH Agent Session, blank or not, is a real destination: it stays.
- if (id !== '' && ((actions.isAgentSession?.(id) ?? roster.agentOf[id] !== undefined) || blank !== '1')) {
+ // local: sidebar-coexistence. Any other Session, blank or not, was opened from the
+ // shell's own sections next to the Bot list, so it is a real destination: it stays.
+ if (id !== '') {
lastBot.current = null
return undefined
}
diff --git a/ds-bot/src/client/sources.js b/ds-bot/src/client/sources.js
index e16533ed88..061e2adbea 100644
--- a/ds-bot/src/client/sources.js
+++ b/ds-bot/src/client/sources.js
@@ -16,10 +16,21 @@ export function createSource(initial) {
}
}
-export const EMPTY_ROSTER = { revision: -1, mainBotId: null, mainBotIds: [], bots: [], rooms: [], agents: [], sections: [], exchangeTurns: {}, questions: {}, btwCards: {}, sideChats: {}, learning: {}, secrets: [], capabilities: [], capabilityStatuses: {}, secretRequests: {}, models: [], defaultModel: null, modelsKey: null, prefs: {}, byId: {}, roomsById: {}, agentsById: {}, agentOf: {}, ready: false }
+export const EMPTY_ROSTER = { revision: -1, mainBotId: null, mainBotIds: [], bots: [], rooms: [], agents: [], sections: [], exchangeTurns: {}, questions: {}, btwCards: {}, sideChats: {}, learning: {}, secrets: [], capabilities: [], capabilityStatuses: {}, operatorTasks: {}, secretRequests: {}, models: [], defaultModel: null, modelsKey: null, prefs: {}, byId: {}, roomsById: {}, agentsById: {}, agentOf: {}, ready: false }
// Any Main Bot holds the Main Bot powers; `mainBotId`, the first one, is the sidebar tile.
export const isMainOf = (roster, id) => id !== undefined && (roster.mainBotIds ?? []).includes(id)
+// local: sidebar-coexistence. Every Session the team owns: Bot chats and their parts,
+// group Sessions with their parts and each member's Session there, and the Sessions of
+// DSH Agents. The shell keeps these out of its own sections.
+export function ownedSessionIds(roster) {
+ return [...new Set([
+ ...roster.bots.flatMap(bot => [bot.id, bot.sessionId ?? bot.id, ...(bot.parts ?? [])]),
+ ...roster.rooms.flatMap(room => [room.id, room.sessionId ?? room.id, ...(room.ownParts ?? []), ...(room.parts ?? []), ...Object.values(room.sessions ?? {})]),
+ ...Object.keys(roster.agentOf ?? {}),
+ ].filter(id => typeof id === 'string' && id !== ''))]
+}
+
// A Bot's chat is a chain of Sessions ("parts"): the Bot id is its first part's id
// and `sessionId` its current one. Every part id finds the Bot; Session state
// (running, unread, turns) is read from the current part, team state from the Bot id.
@@ -44,6 +55,17 @@ export function indexRoster(value) {
return { ...value, agents: value.agents ?? [], sections: value.sections ?? [], byId, roomsById, agentsById, agentOf, ready: true }
}
+// local: sidebar-coexistence. The event the shell listens on for the Sessions this
+// plugin owns. The installed shell still listens on the old name, so both go out
+// until one release after the shell takes the new one (loose end LE-20261103-033).
+export const SESSIONS_EVENT = 'ds-bot:sessions'
+export const legacySessionsEvent = 'dsh-bot:sessions'
+export function publishOwnedSessions(win, ids) {
+ win.__dshBotSessions = ids
+ win.dispatchEvent(new CustomEvent(SESSIONS_EVENT, { detail: ids }))
+ win.dispatchEvent(new CustomEvent(legacySessionsEvent, { detail: ids }))
+}
+
// Whether a main-view Session id belongs to the team's DSH Agent: the conversation
// group then stays withdrawn while the shell keeps the sidebar. Before the roster
// arrives, the ids cached from the last pull answer.
diff --git a/ds-bot/src/client/styles.js b/ds-bot/src/client/styles.js
index 2693dc0919..0e71bd5242 100644
--- a/ds-bot/src/client/styles.js
+++ b/ds-bot/src/client/styles.js
@@ -2,7 +2,6 @@ import { INKS } from './inks.js'
import { DEFAULT_MASK } from './characters.js'
import { MENTION_ORIGIN } from './text.js'
import { SPRING_SHAPE, SPRING_TAP, SPRING_STRETCH, SPRING_POP, spring } from './motion.js'
-import { DSH_NARROW } from './frame-layout.js'
// The pill stretches for "Memory updated" on SPRING_STRETCH, and its icon pops on
// SPRING_POP; it closes on SPRING_SHAPE.
@@ -14,11 +13,11 @@ import { DSH_NARROW } from './frame-layout.js'
// CONVERSATION_CSS re-skins the shell's own conversation DOM and styles what only
// the conversation renders.
export const SHELL_CSS = `
-body{--bt-im-telegram:#229ed9;--bt-im-weixin:#07c160;--bt-im-feishu:#3370ff;--bt-im-dingtalk:#1e88e5;--bt-im-wecom:#0082ef;--bt-im-qq:#e03e3e;--bt-im-discord:#5865f2;--bt-im-slack:#4a154b;--bt-im-mark-ink:#ffffff;--bt-qr-paper:#ffffff;--bt-qr-ink:#141414;--bt-ink:#141414;--bt-danger:#e02135;--bt-ink-2:rgba(20,20,20,.6);--bt-ink-3:rgba(20,20,20,.36);--bt-bubble:#eeeeee;--bt-sidebar:#f7f7f7;--bt-main:#fcfcfc;--bt-line:rgba(20,20,20,.08);--bt-line-2:rgba(20,20,20,.15);--bt-line-weak:rgba(20,20,20,.1);--bt-hover:rgba(119,119,119,.09);--bt-active:rgba(119,119,119,.17);--bt-card:#ffffff;--bt-accent:#4d6bfe;--bt-green:#00c972;--bt-star:#ff9800;--bt-user:#070707;--bt-user-ink:#fcfcfc;--bt-tag-bg:rgba(20,20,20,.06);--bt-tag-ink:rgba(20,20,20,.56);--bt-knob:#ffffff;--bt-glass-bg:color-mix(in srgb,var(--bt-main) 78%,transparent);--bt-glass-border:rgba(255,255,255,.72);--bt-glass-rim:rgba(20,20,20,.09);--bt-glass-shadow:0 8px 28px -6px rgba(0,0,0,.08),0 2px 6px -1px rgba(0,0,0,.04),inset 0 1px 0 rgba(255,255,255,.82);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 14%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 14%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 24%,transparent);-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:100%;--bt-font:var(--dsw-font-family,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}
+body{--bt-im-telegram:#229ed9;--bt-im-weixin:#07c160;--bt-im-feishu:#3370ff;--bt-im-dingtalk:#1e88e5;--bt-im-wecom:#0082ef;--bt-im-qq:#e03e3e;--bt-im-discord:#5865f2;--bt-im-slack:#4a154b;--bt-im-mark-ink:#ffffff;--bt-qr-paper:#ffffff;--bt-qr-ink:#141414;--bt-ink:#141414;--bt-danger:#e02135;--bt-ink-2:rgba(20,20,20,.6);--bt-ink-3:rgba(20,20,20,.36);--bt-bubble:#eeeeee;--bt-sidebar:#f7f7f7;--bt-main:#fcfcfc;--bt-line:rgba(20,20,20,.08);--bt-line-2:rgba(20,20,20,.15);--bt-line-weak:rgba(20,20,20,.1);--bt-hover:rgba(119,119,119,.09);--bt-active:rgba(119,119,119,.17);--bt-card:#ffffff;--bt-accent:#4d6bfe;--bt-green:#00c972;--bt-star:#ff9800;--bt-waiting:#5b6472;--bt-user:#070707;--bt-user-ink:#fcfcfc;--bt-tag-bg:rgba(20,20,20,.06);--bt-tag-ink:rgba(20,20,20,.56);--bt-knob:#ffffff;--bt-glass-bg:color-mix(in srgb,var(--bt-main) 78%,transparent);--bt-glass-border:rgba(255,255,255,.72);--bt-glass-rim:rgba(20,20,20,.09);--bt-glass-shadow:0 8px 28px -6px rgba(0,0,0,.08),0 2px 6px -1px rgba(0,0,0,.04),inset 0 1px 0 rgba(255,255,255,.82);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 14%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 14%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 24%,transparent);-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:100%;--bt-font:var(--dsw-font-family,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}
/* iOS waits out a double-tap zoom on buttons; the plugin's own controls never zoom. */
:is(.bt-tool,.bt-uaction,.bt-menu button,.bt-menu-item,.bt-icon-btn,.bt-round,.bt-pill,.bt-account,.bt-set-row,.bt-settings-item,.bt-react-strip button,.bt-palette-row,.bt-palette-clear,.bt-tab,.bt-ptab,.bt-ptab-x,.bt-bcard-x,.bt-plus,.bt-q-btn,.bt-q-x,.bt-x,.bt-nc-send,.bt-send,.bt-soft,.bt-mini,.bt-side-send,.bt-shape,.bt-swatch,.bt-color,.bt-newchat,.bt-task-day,.bt-task-remove,.bt-fb-btn){touch-action:manipulation}
:is(.bt-round,.bt-you,.bt-account,.bt-color,.bt-color span,.bt-swatch,.bt-icon-btn,.bt-avatar-trigger,.bt-avatar-pencil,.bt-plus,.bt-mic,.bt-voice){corner-shape:round}
-body[data-ds-dark-theme]{--bt-im-telegram:#2ea8de;--bt-im-weixin:#17c96a;--bt-im-feishu:#4d84ff;--bt-im-dingtalk:#3d99ed;--bt-im-wecom:#2898f2;--bt-im-qq:#e85555;--bt-im-discord:#6e7bf2;--bt-im-slack:#7c4380;--bt-im-mark-ink:#ffffff;--bt-ink:#f2f2f2;--bt-ink-2:rgba(242,242,242,.6);--bt-ink-3:rgba(242,242,242,.36);--bt-bubble:#262626;--bt-sidebar:#1b1b1b;--bt-main:#141414;--bt-line:rgba(255,255,255,.08);--bt-line-2:rgba(255,255,255,.15);--bt-line-weak:rgba(255,255,255,.1);--bt-hover:rgba(160,160,160,.12);--bt-active:rgba(160,160,160,.2);--bt-card:#1f1f1f;--bt-user:#f2f2f2;--bt-user-ink:#141414;--bt-tag-bg:rgba(255,255,255,.09);--bt-tag-ink:rgba(242,242,242,.62);--bt-glass-bg:color-mix(in srgb,var(--bt-main) 74%,transparent);--bt-glass-border:rgba(255,255,255,.13);--bt-glass-rim:rgba(255,255,255,.11);--bt-glass-shadow:0 12px 32px -6px rgba(0,0,0,.42),0 2px 8px -1px rgba(0,0,0,.28),inset 0 1px 0 rgba(255,255,255,.12);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 18%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 18%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 28%,transparent)}
+body[data-ds-dark-theme]{--bt-im-telegram:#2ea8de;--bt-im-weixin:#17c96a;--bt-im-feishu:#4d84ff;--bt-im-dingtalk:#3d99ed;--bt-im-wecom:#2898f2;--bt-im-qq:#e85555;--bt-im-discord:#6e7bf2;--bt-im-slack:#7c4380;--bt-im-mark-ink:#ffffff;--bt-ink:#f2f2f2;--bt-ink-2:rgba(242,242,242,.6);--bt-ink-3:rgba(242,242,242,.36);--bt-bubble:#262626;--bt-sidebar:#1b1b1b;--bt-main:#141414;--bt-line:rgba(255,255,255,.08);--bt-line-2:rgba(255,255,255,.15);--bt-line-weak:rgba(255,255,255,.1);--bt-hover:rgba(160,160,160,.12);--bt-active:rgba(160,160,160,.2);--bt-card:#1f1f1f;--bt-user:#f2f2f2;--bt-user-ink:#141414;--bt-tag-bg:rgba(255,255,255,.09);--bt-tag-ink:rgba(242,242,242,.62);--bt-waiting:#9aa3b2;--bt-glass-bg:color-mix(in srgb,var(--bt-main) 74%,transparent);--bt-glass-border:rgba(255,255,255,.13);--bt-glass-rim:rgba(255,255,255,.11);--bt-glass-shadow:0 12px 32px -6px rgba(0,0,0,.42),0 2px 8px -1px rgba(0,0,0,.28),inset 0 1px 0 rgba(255,255,255,.12);--bt-accent-soft:color-mix(in srgb,var(--bt-accent) 18%,transparent);--bt-danger-soft:color-mix(in srgb,var(--bt-danger) 18%,transparent);--bt-danger-glow:color-mix(in srgb,var(--bt-danger) 28%,transparent)}
${Object.entries(INKS).map(([name, [light]]) => `body{--bt-ink-${name}:${light}}`).join('')}
${Object.entries(INKS).map(([name, [, dark]]) => `body[data-ds-dark-theme]{--bt-ink-${name}:${dark}}`).join('')}
.bt-mark{display:inline-block;flex:none;position:relative;line-height:0}
@@ -109,6 +108,14 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default}
.bt-badge-main path{fill:var(--bt-star);stroke:var(--bt-sidebar);stroke-width:2.6;stroke-linejoin:round;paint-order:stroke}
.bt-badge-alert{background:color-mix(in srgb,var(--bt-accent) 78%,var(--bt-sidebar));color:var(--bt-accent-ink,#fff);font-size:8.5px;line-height:12px;font-weight:600;font-family:var(--bt-font)}
.bt-badge-working{background:color-mix(in srgb,var(--bt-green) 82%,var(--bt-sidebar));width:8px;height:8px;right:1px;bottom:1px}
+/* local: waiting-mark. A Bot whose own turn is over but whose handed-on work has not
+ come back cannot wear the working badge, and a Main Bot's star takes the one badge
+ slot, so the wait gets a slot of its own opposite the star. */
+.bt-badge-waiting{right:auto;left:0;background:color-mix(in srgb,var(--bt-waiting) 90%,var(--bt-sidebar))}
+.bt-badge-waiting svg{width:9px;height:9px}
+.bt-badge-waiting :is(circle,path){fill:none;stroke:var(--bt-sidebar);stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
+body:not([data-bt-motion=quiet]) .bt-badge-waiting{animation:bt-wait-tick 2.4s ease-in-out infinite}
+@keyframes bt-wait-tick{0%,100%{opacity:1}50%{opacity:.4}}
.bt-cluster{position:relative;display:inline-block;flex:none;line-height:0}
.bt-cluster>*{position:absolute}
.bt-cluster-more,.bt-cluster-you{display:inline-flex;align-items:center;justify-content:center;border-radius:50%;background:var(--bt-active);color:var(--bt-ink-3);font-family:var(--bt-font);font-weight:500;line-height:1;font-variant-numeric:tabular-nums}
@@ -131,6 +138,10 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default}
.bt-side:not(.bt-rail)>.bt-list::-webkit-scrollbar-track{background:transparent}
.bt-side:not(.bt-rail)>.bt-list::-webkit-scrollbar-thumb{border:4px solid transparent;border-radius:6px;background:color-mix(in srgb,var(--bt-ink) 16%,transparent) padding-box}
.bt-side:not(.bt-rail)>.bt-list:hover::-webkit-scrollbar-thumb{background-color:color-mix(in srgb,var(--bt-ink) 30%,transparent)}
+/* local: sidebar-coexistence. Every Main Bot tiles, two to a row. */
+.bt-tile-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));justify-items:center;align-self:stretch;padding:8px 0 2px}
+.bt-tile-grid>.bt-tile-wrap{padding:6px 0}
+.bt-tile-grid .bt-tile{width:100%;max-width:112px}
.bt-tile-wrap{display:flex;justify-content:center;padding:20px 0 15px}
.bt-tile{display:flex;flex-direction:column;align-items:center;gap:4px;width:95px;padding:6px 8px 4px;border-radius:16px;border:0;background:transparent;color:var(--bt-ink);cursor:pointer;font-family:inherit;transition:background-color .12s ease}
.bt-tile:hover{background:var(--bt-hover)}
@@ -158,6 +169,10 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default}
.bt-leftcol{position:fixed;left:0;top:0;bottom:0;z-index:25;display:flex;--bt-lc-clear:var(--dsh-frame-top-clearance,var(--dsh-windows-titlebar-height,0px));background:var(--bt-leftcol-fill,var(--bt-sidebar));border-right:.5px solid var(--bt-line);box-sizing:border-box;padding:calc(var(--bt-lc-clear) + 6px) 12px 6px;color:var(--bt-ink);font-family:var(--bt-font)}
html[data-windows-titlebar] .bt-leftcol,html[data-platform=darwin] .bt-leftcol{border-right:none}
.bt-leftcol{animation:bt-leftcol-in ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing}}
+/* local: sidebar-coexistence. The column sits in the shell's own sidebar, which owns
+ the place, the fill, the width, the resize and the slide. */
+.bt-leftcol{position:relative;left:auto;top:auto;bottom:auto;z-index:auto;flex-direction:column;min-height:0;--bt-lc-clear:0px;background:none;border-right:none;padding:0;animation:none}
+.bt-leftcol>.bt-leftcol-grip{display:none}
.bt-leftcol[data-leaving]{transform:translateX(-100%);transition:transform ${SPRING_SHAPE.duration}ms ${SPRING_SHAPE.easing};pointer-events:none}
@keyframes bt-leftcol-in{from{transform:translateX(-100%)}}
@media (prefers-reduced-motion:reduce){.bt-leftcol{animation:none}.bt-leftcol[data-leaving],[class*="_centerCol"]{transition:none}}
@@ -165,11 +180,8 @@ html[data-windows-titlebar] .bt-leftcol,html[data-platform=darwin] .bt-leftcol{b
.bt-leftcol-grip:hover,.bt-leftcol-grip:active{background:linear-gradient(to right,transparent 3px,var(--bt-line-2) 3px,var(--bt-line-2) 5px,transparent 5px)}
/* The shell's collapsed sidebar keeps no track in the Bot view, so a hidden
column leaves nothing behind (the shell's right column, when open, keeps its
- own geometry). Narrow hosts may put the conversation in the first track,
- so only the desktop layout can force that track to zero. */
-@media (min-width:${DSH_NARROW}px){
-[class*="_frame"][data-sidebar-collapsed][data-rightbar-collapsed]:has(>[class*="_sidebarCol"]){grid-template-columns:0px minmax(0,1fr) 0px!important}
-}
+ own geometry). Our own collapse of it lands without the shell's slide. */
+/* local: sidebar-coexistence. The shell keeps its own tracks while the Bot list sits inside them. */
html[data-bt-collapsing] [class*="_frame"]:has(>[class*="_sidebarCol"]){transition:none!important}
.bt-leftcol[data-left=drawer]{background:var(--bt-sidebar);box-shadow:8px 0 24px rgba(0,0,0,.14)}
.bt-leftcol>.bt-side{width:100%}
@@ -1136,7 +1148,9 @@ body[data-bt-goal] [class*="_scroll"]:has(> [class*="_column"]){padding-top:calc
}
@keyframes bt-fade-in{from{opacity:0}to{opacity:1}}
@keyframes bt-fade-out{from{opacity:1}to{opacity:0}}
-[data-composer-card]{display:flex!important;flex-direction:row!important;flex-wrap:wrap!important;align-items:center!important;gap:0!important;min-height:44px!important;border-radius:22px!important;padding:7.5px!important;box-sizing:border-box;background:var(--bt-glass-bg)!important;-webkit-backdrop-filter:blur(20px) saturate(180%)!important;backdrop-filter:blur(20px) saturate(180%)!important;border:.5px solid var(--bt-glass-rim)!important;box-shadow:var(--bt-glass-shadow),0 0 0 1px rgba(228,228,228,.04)!important;transition:border-color .15s ease,background-color .15s ease,${spring(SPRING_SHAPE, 'border-radius')}!important}
+[data-composer-card]{display:flex!important;flex-direction:row!important;flex-wrap:wrap!important;align-items:center!important;gap:0!important;min-height:44px!important;border-radius:22px!important;padding:7.5px!important;box-sizing:border-box;position:relative!important;isolation:isolate!important;background:transparent!important;-webkit-backdrop-filter:none!important;backdrop-filter:none!important;border:.5px solid var(--bt-glass-rim)!important;box-shadow:var(--bt-glass-shadow),0 0 0 1px rgba(228,228,228,.04)!important;transition:border-color .15s ease,${spring(SPRING_SHAPE, 'border-radius')}!important}
+/* The glass sits on a layer behind the contents: a backdrop-filter on the card itself would make it a backdrop root, and the Harness menus that open inside it (the slash and skills picker, model, permission) would lose their own blur and show the chat sharp through a 58% fill. */
+[data-composer-card]::before{content:"";position:absolute;inset:0;z-index:-1;border-radius:inherit;pointer-events:none;background:var(--bt-glass-bg);-webkit-backdrop-filter:blur(20px) saturate(180%);backdrop-filter:blur(20px) saturate(180%)}
[data-composer-card]:hover,[data-composer-card]:focus-within{border-color:color-mix(in srgb,var(--bt-ink) 30%,transparent)!important}
[data-composer-card]:has(> [data-slot="conversation.input.attachments"] *),[data-composer-card]:has([data-composer-input] br + *),[data-composer-card]:has([data-composer-input] > :nth-child(2)){border-radius:18px!important}
[class*="_root"]:has(> [data-composer-card]){padding:0 11px 13px 16px!important}
diff --git a/ds-bot/src/client/themes.js b/ds-bot/src/client/themes.js
index 82c3b3b930..193973398f 100644
--- a/ds-bot/src/client/themes.js
+++ b/ds-bot/src/client/themes.js
@@ -65,6 +65,9 @@ export const shellTokens = ({ light, dark }) => ({
'--dsw-alias-label-primary': { light: light.text, dark: dark.text },
'--dsw-alias-label-secondary': { light: rgba(light.text, 0.74), dark: rgba(dark.text, 0.74) },
'--dsw-alias-label-tertiary': { light: rgba(light.text, 0.6), dark: rgba(dark.text, 0.6) },
+ // The shell's idle dot (pending to-dos, idle sessions) is neutral-300, 1.4:1 on the
+ // light page; graphics need 3:1. Same step as label-tertiary keeps it in each theme.
+ '--dsw-alias-state-idle-primary': { light: rgba(light.text, 0.6), dark: rgba(dark.text, 0.6) },
})
// Other plugins add character shapes and themes through `window.dshBot`, or queue
diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js
new file mode 100644
index 0000000000..2b5b902c05
--- /dev/null
+++ b/ds-bot/src/host/card-gate.js
@@ -0,0 +1,293 @@
+// The card gate: decisions follow the job back to the Bot that sent it.
+//
+// A job a Bot sends another Bot runs in a hidden turn: the user does not watch it.
+// A question card or a plan review raised there lands in the sub-agent's own chat,
+// away from the conversation the user started the job in, so the gate refuses it
+// and sends the decision back to the sender (the manager) instead. The manager
+// cards the user and relays the answer; a plan approval relayed by a Main Bot with
+// PLAN-APPROVED turns the sub-agent's plan mode off with no card.
+//
+// What stays open: a Main Bot's own cards, every turn the user typed, a request
+// whose audience is the user, and a job whose text carries CARD-IT-YOURSELF. A
+// card whose option is the production approval is never opened by that token:
+// deploy approval always goes back to the manager, who cards Steve and mints the
+// approval for the Bot that runs the merge. Interactive show_view cards follow
+// the same rules as ask_user. Every card decided in a Bot's Session is logged
+// with the reason that decided it.
+//
+// A plan release (PLAN-APPROVED, an ORDER line) is honoured from a Main Bot, or
+// from the admin of a group the receiving Bot is a member of.
+//
+// DSH_CARD_GATE=off turns all of it off.
+
+import { appendFileSync, mkdirSync, readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+
+export const CARD_IT_YOURSELF = 'CARD-IT-YOURSELF'
+export const PLAN_APPROVED = 'PLAN-APPROVED'
+export const EXIT_PLAN_MODE = 'exit_plan_mode'
+const PRODUCTION_LABEL = /^deploy to production( \(Recommended\))?$/i
+const TITLE_MAX = 200
+
+export const gateOn = (env = process.env) => String(env.DSH_CARD_GATE ?? '').trim().toLowerCase() !== 'off'
+
+export const isProductionLabel = label => PRODUCTION_LABEL.test(String(label ?? '').trim())
+
+const clip = text => {
+ const value = String(text ?? '').replace(/\s+/g, ' ').trim()
+ return value.length > TITLE_MAX ? `${value.slice(0, TITLE_MAX - 3)}...` : value
+}
+
+/** The plan's first markdown heading, or its first line. */
+export const planTitle = (plan) => {
+ for (const line of String(plan ?? '').split('\n')) {
+ const match = /^#{1,6}\s+(.+?)\s*$/.exec(line)
+ if (match) return clip(match[1])
+ }
+ return clip(String(plan ?? '').split('\n').find(line => line.trim() !== '') ?? '')
+}
+
+// Who sent the job a trigger carries: its Bot's name, else the name on the message.
+const senderOf = (rt, info) => rt.botOf?.(info?.senderSessionId)?.name ?? info?.senderName ?? 'the Bot that sent this job'
+
+/**
+ * Why the turn running in a Session is or is not gated: `reason` is gate-off,
+ * not-bot-turn, main-bot, audience-user or gated; a gated turn also carries who
+ * runs it, who sent it, and whether it may card.
+ */
+export function turnGate(rt, sessionId) {
+ if (!gateOn()) return { reason: 'gate-off' }
+ const { state } = rt
+ const entry = rt.live?.get(sessionId)
+ const turn = entry?.turn
+ if (turn === undefined || !(state.exchangeTurns?.[sessionId] ?? []).includes(turn)) return { reason: 'not-bot-turn' }
+ const botId = rt.chatOwners?.get(sessionId)
+ if (botId === undefined) return { reason: 'not-bot-turn' }
+ if (rt.isMain?.(botId)) return { reason: 'main-bot' }
+ const info = entry.info
+ // A request the user sees answered here is the user's turn as much as the Bot's.
+ if (info?.audience === 'user') return { reason: 'audience-user' }
+ const triggers = [{ info, text: entry.infoText }, ...(entry.joined ?? [])]
+ const texts = triggers.flatMap(({ info: item, text }) => {
+ const record = (state.exchanges ?? []).find(other => other.id === item?.exchangeId)
+ return [text, record?.text].filter(value => typeof value === 'string')
+ })
+ return {
+ reason: 'gated',
+ bot: rt.botOf?.(botId)?.name ?? botId,
+ manager: senderOf(rt, info),
+ cardItYourself: texts.some(text => text.includes(CARD_IT_YOURSELF)),
+ }
+}
+
+/** The gated turn (see turnGate), or undefined when the gate does not apply. */
+export function gatedTurn(rt, sessionId) {
+ const gate = turnGate(rt, sessionId)
+ if (gate.reason !== 'gated') return undefined
+ const { reason: _reason, ...gated } = gate
+ return gated
+}
+
+export const cardRefusal = manager => `This job came from ${manager}. Do not card Steve: end your turn with a DECISION block for ${manager} (question, 2 to 4 options, the recommended one marked with its reason, Hold). ${manager} cards Steve and relays his answer.`
+
+export const planRefusal = manager => `This job came from ${manager}. Do not open a plan review for Steve here: send the full plan to ${manager} as a DECISION (Approve plan (Recommended) / Change it / Hold). When ${manager} relays approval with ${PLAN_APPROVED}, plan mode turns off for you.`
+
+export const productionRefusal = manager => `This job came from ${manager}. A deploy approval never goes to Steve from here: send the deploy DECISION to ${manager}, naming the repo and the PR as #N. ${manager} cards Steve and mints the approval; then run gh pr merge --repo alone.`
+
+/**
+ * How the gate decides a card in this Session: `allowed`, `because` (the reason
+ * that decided it), the production label when one is offered, who runs the turn
+ * and who sent it, and the refusal text when it is refused.
+ */
+export function judgeCard(rt, sessionId, options) {
+ const label = (options ?? []).map(option => option?.label).find(isProductionLabel)
+ const gate = turnGate(rt, sessionId)
+ const botId = rt.chatOwners?.get(sessionId)
+ const named = { bot: gate.bot ?? rt.botOf?.(botId)?.name ?? botId ?? sessionId, ...(gate.manager !== undefined ? { manager: gate.manager } : {}), ...(label !== undefined ? { label } : {}) }
+ if (gate.reason !== 'gated') return { allowed: true, because: gate.reason, ...named }
+ if (label !== undefined) return { allowed: false, because: 'production-label', ...named, text: productionRefusal(gate.manager) }
+ if (gate.cardItYourself) return { allowed: true, because: 'card-it-yourself', ...named }
+ return { allowed: false, because: 'gated', ...named, text: cardRefusal(gate.manager) }
+}
+
+/** Whether ask_user in this Session is refused; the refusal text, or undefined. */
+export function refuseCard(rt, sessionId, options) {
+ const judged = judgeCard(rt, sessionId, options)
+ return judged.allowed ? undefined : judged
+}
+
+/** The labels a view offers the user, read from its options, confirm and submit parts. */
+export function viewLabels(view) {
+ const labels = []
+ const walk = (node, depth = 0) => {
+ if (depth > 8 || node === null || typeof node !== 'object') return
+ if (Array.isArray(node)) { for (const item of node) walk(item, depth + 1); return }
+ if (node.type === 'options') for (const option of node.options ?? []) labels.push({ label: String(option?.label ?? '') })
+ if (node.type === 'confirm') labels.push({ label: String(node.confirmLabel ?? '') })
+ if (node.type === 'submit') labels.push({ label: String(node.label ?? '') })
+ if (node.type === 'form') labels.push({ label: String(node.submitLabel ?? '') })
+ for (const child of node.children ?? []) walk(child, depth + 1)
+ }
+ walk(view)
+ return labels
+}
+
+/** Logs a card decision, so an allowed card can be traced as well as a refused one. */
+export function logCard(rt, tool, judged, title) {
+ if (!gateOn()) return
+ const { text: _text, ...entry } = judged
+ void logGate(rt, { ...entry, tool, title: String(title ?? '') })
+}
+
+/** Whether exit_plan_mode in this Session is refused; the refusal text, or undefined. */
+export function refusePlan(rt, sessionId) {
+ const gated = gatedTurn(rt, sessionId)
+ if (gated === undefined || gated.cardItYourself) return undefined
+ return { ...gated, text: planRefusal(gated.manager) }
+}
+
+/**
+ * One JSON line in /logs/card-gate.log. Only names, the tool and a title.
+ * Written synchronously: a fire-and-forget async write could land after the host
+ * stopped and its folder was removed (seen as ENOTEMPTY in test teardown on Node 22).
+ */
+export function logGate(rt, entry) {
+ if (typeof rt.home !== 'string') return Promise.resolve()
+ const path = join(rt.home, 'logs', 'card-gate.log')
+ const line = JSON.stringify({ time: new Date().toISOString(), ...entry, ...(entry.title !== undefined ? { title: clip(rt.redactSecrets?.(entry.title) ?? entry.title) } : {}) })
+ try {
+ mkdirSync(dirname(path), { recursive: true })
+ appendFileSync(path, `${line}\n`, 'utf8')
+ } catch (error) {
+ rt.warn?.('ds-bot: card gate log not written: %s', error?.code ?? error)
+ }
+ return Promise.resolve()
+}
+
+// A job a Main Bot hands out opens with this line; it carries the manager's
+// approval to start, so the Bot it reaches is not left waiting in plan mode.
+export const ORDER_PREFIX = /^ORDER from .+? · job /
+export const orderReleaseOn = (env = process.env) => String(env.DSH_ORDER_RELEASE ?? '').trim().toLowerCase() !== 'off'
+
+/** Which release a message carries: 'plan-approved', 'order', or undefined. */
+export function releaseKind(text, env = process.env) {
+ const value = String(text ?? '')
+ if (value.includes(PLAN_APPROVED)) return 'plan-approved'
+ if (orderReleaseOn(env) && ORDER_PREFIX.test(value.trimStart())) return 'order'
+ return undefined
+}
+
+/**
+ * A Main Bot's message that relays a plan approval (PLAN-APPROVED), or hands out a
+ * job (an ORDER line), turns plan mode off in the Session it reaches, whether that
+ * Bot is a Main Bot or not: at once between turns, from the next step inside one.
+ * Every attempt is logged with its outcome, so a release that did nothing says why.
+ * Returns what planMode.set said, or undefined when nothing was done.
+ */
+export function relayPlanApproval(rt, { fromId, toId, agent, text }) {
+ if (!gateOn()) return undefined
+ const kind = releaseKind(text)
+ if (kind === undefined) return undefined
+ const log = (outcome) => {
+ void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId ?? 'unknown', tool: kind, outcome, ...(authority !== undefined ? { authority } : {}) })
+ }
+ let authority
+ if (fromId !== undefined && fromId === toId) { log('self'); return undefined }
+ authority = releaseAuthority(rt, fromId, toId)
+ if (authority === undefined) { log('sender-not-manager'); return undefined }
+ const planMode = planModeFor(rt, agent)
+ if (planMode === undefined || agent === undefined) { log('no-plan-service'); return undefined }
+ let outcome
+ try {
+ const now = planMode.get(agent)
+ if (!(now.pending ?? now.active)) { log('not-in-plan-mode'); return undefined }
+ outcome = planMode.set(agent, false)
+ } catch (error) {
+ rt.warn?.('ds-bot: relayed plan approval not applied: %s', error)
+ log('error')
+ return undefined
+ }
+ log(outcome)
+ return outcome
+}
+
+/**
+ * Who may release a Bot's plan mode: 'main' for a Main Bot, 'group-admin' for the
+ * admin of a group the receiving Bot is a member of (a group admin is the manager
+ * Steve's routing names for that group's work), else undefined.
+ */
+export function releaseAuthority(rt, fromId, toId) {
+ if (fromId === undefined) return undefined
+ if (rt.isMain?.(fromId)) return 'main'
+ const rooms = Object.values(rt.state?.rooms ?? {})
+ if (rooms.some(room => room?.admin === fromId && (room.members ?? []).includes(toId))) return 'group-admin'
+ return undefined
+}
+
+/**
+ * The plan-mode service that serves this agent. Under an agent preset, plan mode
+ * lives in the preset's isolated group (`isolate: planMode: true`), so a Host-realm
+ * `ctx.get('planMode')` finds nothing: the preset composition is read first.
+ */
+export function planModeFor(rt, agent) {
+ if (agent === undefined) return undefined
+ return rt.ctx?.get?.('agentPresets')?.serviceFor?.(agent, 'planMode') ?? rt.ctx?.get?.('planMode')
+}
+
+/**
+ * Bots that keep plan mode on, by name: /plan-mode-keep.json, a JSON array of
+ * names. Read on each call (it is tiny), so an edit needs no restart.
+ */
+export function keepsPlanMode(rt, name) {
+ if (typeof rt.home !== 'string' || typeof name !== 'string') return false
+ try {
+ const list = JSON.parse(readFileSync(join(rt.home, 'plan-mode-keep.json'), 'utf8'))
+ return Array.isArray(list) && list.some(item => String(item).trim().toLowerCase() === name.trim().toLowerCase())
+ } catch {
+ return false
+ }
+}
+
+export const planDefaultOffOn = (env = process.env) => String(env.DSH_PLAN_DEFAULT_OFF ?? '').trim().toLowerCase() !== 'off'
+
+/**
+ * A Bot Session does not start in plan mode: DSH's shipped presets pin it on for
+ * every new Session (`defaultActive: true`), and Steve's rule is off by default.
+ * Each Session is switched off once, recorded in `state.planDefaultOff`, so a later
+ * /plan in that chat is the user's choice and stays on. A Bot with
+ * `planMode: 'on'` is left alone. Returns the outcome, or undefined.
+ */
+export function ensurePlanOff(rt, agent, why, { fresh = false } = {}) {
+ if (!planDefaultOffOn()) return undefined
+ const sessionId = agent?.session?.id ?? agent?.id
+ if (sessionId === undefined) return undefined
+ // A Session DS Bot has just made for a Bot is not yet in the owner tables.
+ const botId = rt.selfOf?.(sessionId)
+ if (botId === undefined && !fresh) return undefined
+ const done = rt.state?.planDefaultOff ?? (rt.state === undefined ? undefined : (rt.state.planDefaultOff = {}))
+ if (done === undefined || done[sessionId] !== undefined) return undefined
+ const bot = rt.botOf?.(botId)
+ const log = (outcome) => { void logGate(rt, { bot: bot?.name ?? botId ?? sessionId, tool: 'plan-default-off', why, outcome }) }
+ if (bot?.planMode === 'on' || keepsPlanMode(rt, bot?.name)) { done[sessionId] = 'kept'; log('kept-bot-opt-in'); void rt.save?.().catch?.(() => {}); return 'kept' }
+ const planMode = planModeFor(rt, agent)
+ if (planMode === undefined) { log('no-plan-service'); return undefined }
+ let outcome
+ try {
+ const now = planMode.get(agent)
+ outcome = (now.pending ?? now.active) ? planMode.set(agent, false) : 'already-off'
+ } catch (error) {
+ rt.warn?.('ds-bot: plan default-off not applied: %s', error)
+ log('error')
+ return undefined
+ }
+ done[sessionId] = outcome
+ void rt.save?.().catch?.(() => {})
+ log(outcome)
+ return outcome
+}
+
+/** One line at start-up, so the log proves this code is the code that is running. */
+export function announceGate(rt) {
+ if (!gateOn()) return Promise.resolve()
+ return logGate(rt, { tool: 'gate-loaded', release: 'plan-approved+order', releaseFrom: 'main+group-admin', cards: 'judged+logged', orderRelease: orderReleaseOn(), planDefaultOff: planDefaultOffOn(), lookup: 'agentPresets.serviceFor' })
+}
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js
index 3bf0fd63c7..339f57f6f2 100644
--- a/ds-bot/src/host/channel.js
+++ b/ds-bot/src/host/channel.js
@@ -122,6 +122,7 @@ export function install(rt) {
// Named apart from the state view's `computer`: the live answer merges into the
// same object and would wipe its `enabled` and `provider` fields.
computerLive: rt.computerLive?.() ?? {},
+ operatorTasks: rt.operatorTasksView?.() ?? {},
})
// The live fields' sources are spread across the host with no single change
// counter, so the serialized answer itself is the detector: a poll whose `live`
diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js
index 5ef6d04736..6b07209f38 100644
--- a/ds-bot/src/host/constants.js
+++ b/ds-bot/src/host/constants.js
@@ -69,7 +69,7 @@ export const AGENT_SESSION_TITLE_MAX = 80
// profile, so the list served to one session can be shorter.
export const TEAM_TOOLS = [
'list_bots', 'message_bot', 'stop_bot', 'create_bot', 'update_bot', 'list_bot_models',
- 'create_group', 'update_group', 'delete_group', 'post_to_group', 'ask_user', 'show_view',
+ 'create_group', 'update_group', 'delete_group', 'post_to_group', 'ask_user', 'void_question', 'show_view',
'request_secret', 'list_secrets', 'group_relay', 'read_own_chat',
'read_group_chat', 'remember', 'forget', 'recall', 'read_browser',
'list_capabilities', 'save_capability', 'delete_capability',
diff --git a/ds-bot/src/host/credit-guard.js b/ds-bot/src/host/credit-guard.js
new file mode 100644
index 0000000000..74d99a8a33
--- /dev/null
+++ b/ds-bot/src/host/credit-guard.js
@@ -0,0 +1,312 @@
+// Credit guard: keeps Bots that run on a prepaid API credit route inside the monthly
+// grant. It reads the organization's spend from the Anthropic Admin API, warns once
+// near the limit, and at the cutoff moves each guarded Bot back to its fallback model
+// and tells it in its own chat. A meter that cannot read for too long counts as over
+// the cutoff: a blind meter must never let a Bot keep spending.
+//
+// Config, under the plugin's `creditGuard` key (no key: the guard is off):
+// route the model route that bills the credit, e.g. 'anthropic-credit'
+// fallback the model a guarded Bot moves to, e.g. 'kimi-coding/k3'
+// bots names or ids of the Bots it guards
+// budget, warnAt, cutAt, hardAt dollars (200, 150, 190, 195)
+// resetDay day of the month the grant renews, UTC (20)
+// pollMinutes (15), blindHours (2), waitMinutes (10)
+// adminKey the team secret (or environment variable) holding the Admin key
+// baseUrl the Admin API ('https://api.anthropic.com')
+// prices per million tokens, by model, for hours the cost report has not caught up on
+// The Admin key is only sent to baseUrl; it is never logged or shown.
+
+import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+export const DEFAULTS = {
+ budget: 200,
+ warnAt: 150,
+ cutAt: 190,
+ hardAt: 195,
+ resetDay: 20,
+ pollMinutes: 15,
+ blindHours: 2,
+ waitMinutes: 10,
+ adminKey: 'ANTHROPIC_ADMIN_KEY',
+ baseUrl: 'https://api.anthropic.com',
+ // Unknown models are priced at the dearest entry, so an estimate errs high.
+ prices: { 'claude-opus-5-5': { input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75 } },
+}
+const ADMIN_PREFIX = 'sk-ant-admin'
+const CREDIT_ERROR = /credit balance is too low|insufficient.{0,20}credit/i
+const MINUTE = 60_000
+
+export function settingsOf(config) {
+ const raw = config?.creditGuard
+ if (raw === undefined || raw === null || raw.enabled === false) return undefined
+ const merged = { ...DEFAULTS, ...raw, prices: { ...DEFAULTS.prices, ...raw.prices } }
+ if (typeof merged.route !== 'string' || merged.route === '' || typeof merged.fallback !== 'string' || merged.fallback === '') return undefined
+ merged.bots = Array.isArray(merged.bots) ? merged.bots.filter(name => typeof name === 'string' && name !== '') : []
+ const day = Math.trunc(Number(merged.resetDay))
+ merged.resetDay = day >= 1 && day <= 28 ? day : DEFAULTS.resetDay
+ return merged
+}
+
+// The start of the grant period that holds `now`: the reset day at 00:00 UTC, this
+// month if it has passed, else last month.
+export function periodStart(now, resetDay) {
+ const date = new Date(now)
+ let year = date.getUTCFullYear()
+ let month = date.getUTCMonth()
+ if (date.getUTCDate() < resetDay) {
+ month -= 1
+ if (month < 0) { month = 11; year -= 1 }
+ }
+ return Date.UTC(year, month, resetDay)
+}
+
+const startOfDay = at => {
+ const date = new Date(at)
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())
+}
+
+// Dollars per bucket start. The cost report gives each amount in cents, as a decimal string.
+export function costBuckets(pages) {
+ const byDay = new Map()
+ for (const page of pages) {
+ for (const bucket of page?.data ?? []) {
+ const at = Date.parse(bucket.starting_at)
+ if (!Number.isFinite(at)) continue
+ let cents = 0
+ for (const result of bucket.results ?? []) {
+ const amount = Number(result.amount)
+ if (Number.isFinite(amount)) cents += amount
+ }
+ byDay.set(at, (byDay.get(at) ?? 0) + cents / 100)
+ }
+ }
+ return byDay
+}
+
+const priceOf = (prices, model) => {
+ if (prices[model]) return prices[model]
+ const entry = Object.entries(prices).find(([name]) => typeof model === 'string' && model.startsWith(name))
+ if (entry) return entry[1]
+ return Object.values(prices).reduce((dearest, price) => (price.output > (dearest?.output ?? -1) ? price : dearest), undefined)
+}
+
+// Dollars for token usage at list prices, from usage report pages.
+export function usageCost(pages, prices) {
+ let dollars = 0
+ for (const page of pages) {
+ for (const bucket of page?.data ?? []) {
+ for (const result of bucket.results ?? []) {
+ const price = priceOf(prices, result.model)
+ if (price === undefined) continue
+ const creation = result.cache_creation ?? {}
+ const written = (creation.ephemeral_5m_input_tokens ?? 0) + (creation.ephemeral_1h_input_tokens ?? 0)
+ dollars += ((result.uncached_input_tokens ?? 0) * price.input
+ + (result.cache_read_input_tokens ?? 0) * (price.cacheRead ?? price.input)
+ + written * (price.cacheWrite ?? price.input)
+ + (result.output_tokens ?? 0) * price.output) / 1_000_000
+ }
+ }
+ }
+ return dollars
+}
+
+// Month-to-date dollars: the cost report for every day before today, and for today
+// whichever is higher of its partial cost bucket and the usage priced at list rates.
+export function spendOf({ costPages, usagePages, prices, now }) {
+ const today = startOfDay(now)
+ let total = 0
+ let todayCost = 0
+ for (const [at, dollars] of costBuckets(costPages)) {
+ if (at >= today) todayCost += dollars
+ else total += dollars
+ }
+ return total + Math.max(todayCost, usageCost(usagePages, prices))
+}
+
+// What the guard does with one reading. `blindFor` is how long no reading has worked.
+export function decide({ spent, blindFor, settings, running, waitedFor }) {
+ const blind = spent === undefined
+ if (blind && blindFor < settings.blindHours * 60 * MINUTE) return { act: 'none' }
+ if (blind || spent >= settings.hardAt) return { act: 'switch', reason: blind ? 'blind' : 'hard' }
+ if (spent >= settings.cutAt) {
+ if (running && waitedFor < settings.waitMinutes * MINUTE) return { act: 'wait' }
+ return { act: 'switch', reason: 'cut' }
+ }
+ if (spent >= settings.warnAt) return { act: 'warn' }
+ return { act: 'none' }
+}
+
+export function adminKeyProblem(key) {
+ if (typeof key !== 'string' || key === '') return 'no-key'
+ if (!key.startsWith(ADMIN_PREFIX)) return 'bad-key'
+ return undefined
+}
+
+const money = value => `$${value.toFixed(2)}`
+
+export function install(rt) {
+ const settings = settingsOf(rt.config)
+ if (settings === undefined) {
+ rt.creditGuardView = () => ({ enabled: false })
+ return
+ }
+ const { ctx } = rt
+ const fetchFn = rt.config.creditGuard.fetch ?? globalThis.fetch
+ const now = rt.config.creditGuard.now ?? (() => Date.now())
+ const statePath = join(rt.home, 'credit-guard.json')
+ const logPath = join(rt.home, 'logs', 'credit-guard.log')
+ const startedAt = now()
+ let record = { period: 0, warned: [], switched: [] }
+ let lastGood
+ let lastReading
+ let waitingSince
+ let timer = null
+ let stopped = false
+ let busy = Promise.resolve()
+
+ const log = async (entry) => {
+ const line = JSON.stringify({ at: new Date(now()).toISOString(), ...entry })
+ try {
+ await mkdir(join(rt.home, 'logs'), { recursive: true })
+ await appendFile(logPath, `${line}\n`, 'utf8')
+ } catch (error) { rt.warn?.('ds-bot: credit guard log not written: %s', error?.message ?? error) }
+ }
+ const loadRecord = async () => {
+ try { record = { ...record, ...JSON.parse(await readFile(statePath, 'utf8')) } } catch { /* first run */ }
+ }
+ const saveRecord = () => writeFile(statePath, JSON.stringify(record, null, 1), 'utf8')
+ .catch(error => rt.warn?.('ds-bot: credit guard state not saved: %s', error?.message ?? error))
+
+ const adminKey = () => rt.secretValue?.(settings.adminKey) ?? process.env[settings.adminKey]
+
+ async function pages(path, query, key) {
+ const out = []
+ let page
+ for (let count = 0; count < 20; count++) {
+ const url = new URL(path, settings.baseUrl)
+ for (const [name, value] of Object.entries(query)) url.searchParams.append(name, value)
+ if (page) url.searchParams.set('page', page)
+ const response = await fetchFn(url, { headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' } })
+ if (response.status === 401 || response.status === 403) throw Object.assign(new Error(`Admin API ${response.status}`), { kind: 'bad-key', status: response.status })
+ if (!response.ok) throw Object.assign(new Error(`Admin API ${response.status}`), { kind: 'error', status: response.status })
+ const body = await response.json()
+ out.push(body)
+ if (!body?.has_more || !body.next_page) break
+ page = body.next_page
+ }
+ return out
+ }
+
+ // One reading: dollars spent this period, or `undefined` with the reason it failed.
+ async function read() {
+ const key = adminKey()
+ const problem = adminKeyProblem(key)
+ if (problem) return { problem }
+ const at = now()
+ const start = new Date(periodStart(at, settings.resetDay)).toISOString()
+ const today = new Date(startOfDay(at)).toISOString()
+ try {
+ const costPages = await pages('/v1/organizations/cost_report', { starting_at: start, bucket_width: '1d' }, key)
+ const usagePages = await pages('/v1/organizations/usage_report/messages', { starting_at: today, bucket_width: '1h', 'group_by[]': 'model' }, key)
+ return { spent: spendOf({ costPages, usagePages, prices: settings.prices, now: at }) }
+ } catch (error) {
+ return { problem: error?.kind ?? 'error', status: error?.status }
+ }
+ }
+
+ const guarded = () => settings.bots.map(ref => rt.findBot?.(ref)).filter(bot => bot !== undefined
+ && typeof bot.model === 'string' && bot.model.startsWith(`${settings.route}/`) && bot.model !== settings.fallback)
+ const sessionsOf = bot => [rt.chatOf?.(bot.id), ...(rt.groupSessionsOf?.(bot.id) ?? [])].filter(Boolean)
+ const running = bot => sessionsOf(bot).some(id => rt.live?.get(id)?.turn !== undefined)
+
+ async function notify(bot, text) {
+ await rt.deliver({ toId: bot.id, role: 'update', text })
+ .catch(error => rt.warn?.('ds-bot: credit guard notice for %s not delivered: %s', bot.name, error?.message ?? error))
+ }
+
+ async function switchBot(bot, why, spent) {
+ const from = bot.model
+ await rt.updateBot(bot.id, { model: settings.fallback })
+ const after = rt.botOf?.(bot.id)?.model
+ const ok = after === settings.fallback || (typeof after === 'string' && !after.startsWith(`${settings.route}/`))
+ await log({ event: 'switch', bot: bot.name, from, to: after, why, spent, ok })
+ if (!ok) return
+ record.switched = [...new Set([...record.switched, bot.id])]
+ await saveRecord()
+ const reading = spent === undefined ? 'the spend meter has had no reading for over ' + settings.blindHours + ' hours'
+ : `${money(spent)} of the ${money(settings.budget)} credit is used this month`
+ const reason = why === 'credit-error' ? 'the API refused a request for low credit' : reading
+ await notify(bot, `[Credit guard] I moved you from ${from} to ${after} because ${reason}. Your next turns run on ${after}. Tell the user in your next reply.`)
+ }
+
+ async function check() {
+ const at = now()
+ const period = periodStart(at, settings.resetDay)
+ if (record.period !== period) record = { period, warned: [], switched: [] }
+ const reading = await read()
+ lastReading = { at, ...reading }
+ if (reading.spent !== undefined) lastGood = at
+ await log(reading.spent !== undefined
+ ? { event: 'reading', spent: Number(reading.spent.toFixed(2)) }
+ : { event: 'blind', problem: reading.problem, ...(reading.status ? { status: reading.status } : {}) })
+ const bots = guarded()
+ const blindFor = at - (lastGood ?? startedAt)
+ let waiting = false
+ for (const bot of bots) {
+ const busyNow = running(bot)
+ const decision = decide({ spent: reading.spent, blindFor, settings, running: busyNow, waitedFor: waitingSince === undefined ? 0 : at - waitingSince })
+ if (decision.act === 'warn' && !record.warned.includes(bot.id)) {
+ record.warned.push(bot.id)
+ await saveRecord()
+ await log({ event: 'warn', bot: bot.name, spent: reading.spent })
+ await notify(bot, `[Credit guard] ${money(reading.spent)} of the ${money(settings.budget)} credit is used this month. At ${money(settings.cutAt)} I move you to ${settings.fallback}. Tell the user in your next reply.`)
+ } else if (decision.act === 'wait') {
+ waiting = true
+ await log({ event: 'wait', bot: bot.name, spent: reading.spent })
+ } else if (decision.act === 'switch') {
+ await switchBot(bot, decision.reason, reading.spent)
+ }
+ }
+ if (waiting) waitingSince ??= at
+ else waitingSince = undefined
+ return waiting
+ }
+
+ const schedule = (ms) => {
+ if (stopped) return
+ timer = setTimeout(() => { busy = busy.then(run, run) }, ms)
+ }
+ async function run() {
+ let waiting = false
+ try { waiting = await check() } catch (error) { await log({ event: 'error', message: String(error?.message ?? error).slice(0, 200) }) }
+ schedule(waiting ? MINUTE : settings.pollMinutes * MINUTE)
+ }
+
+ // A refusal for low credit is an immediate cutoff, whatever the meter says.
+ ctx.on?.('session/event', (session, event) => {
+ if (event?.type !== 'turn/end') return
+ const reason = event.data?.reason
+ if (reason?.kind !== 'error') return
+ const message = String(reason.error?.message ?? '')
+ if (!CREDIT_ERROR.test(message)) return
+ const ownerId = rt.chatOwners?.get?.(session?.id) ?? rt.groupOwners?.get?.(session?.id)?.botId
+ const bot = guarded().find(entry => entry.id === ownerId || sessionsOf(entry).includes(session?.id))
+ if (bot === undefined) return
+ busy = busy.then(() => switchBot(bot, 'credit-error', undefined)).catch(error => rt.warn?.('ds-bot: credit guard switch failed: %s', error?.message ?? error))
+ })
+
+ ctx.effect?.(() => {
+ void loadRecord().then(() => log({ event: 'start', route: settings.route, fallback: settings.fallback, bots: settings.bots, resetDay: settings.resetDay })).then(() => schedule(0))
+ return () => { stopped = true; if (timer !== null) clearTimeout(timer) }
+ }, 'ds-bot: credit guard')
+
+ rt.creditGuardView = () => ({
+ enabled: true,
+ route: settings.route,
+ budget: settings.budget,
+ reading: lastReading === undefined ? undefined
+ : { at: lastReading.at, ...(lastReading.spent === undefined ? { problem: lastReading.problem } : { spent: lastReading.spent }) },
+ })
+ rt.creditGuardCheck = () => (busy = busy.then(check, check))
+}
diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js
index ff60a6a8c4..84a3e27eba 100644
--- a/ds-bot/src/host/delivery.js
+++ b/ds-bot/src/host/delivery.js
@@ -1,11 +1,14 @@
// Delivery: how one Bot, the user, or DS Bot itself puts a message into a Bot Session.
import { randomUUID } from 'node:crypto'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
+import { announceGate, ensurePlanOff, relayPlanApproval } from './card-gate.js'
import { HISTORY_TIMEOUT_MS, LONG_HEAD, MESSAGE_INLINE_MAX, READ_LINE_MAX, SOURCE_KIND, TEXT_KEPT, TEXT_SHOW_MAX } from './constants.js'
import { headOf, textOf } from './text.js'
export function install(rt) {
const { ctx, state } = rt
+ // The card gate says once that it is loaded, so its log proves which code runs.
+ void announceGate(rt)
const resolveAgent = async (sessionId) => {
const resolved = await ctx.sessionController.resolveAgent(sessionId)
@@ -29,6 +32,7 @@ export function install(rt) {
if (resent && role !== 'room') return `[Message from ${fromName} · DeepSeek Harness restarted before it could reach you]`
if (role === 'reply') return `[Reply from ${fromName}${goesOn}]`
if (role === 'stopped') return `[Stopped by ${fromName}]`
+ if (role === 'voided') return `[Question voided by ${fromName}]`
if (role === 'room') return `[Group chat "${roomName}" · ${note}]`
if (role === 'report') return `[Group chat "${roomName}" · replies to your post${goesOn}]`
if (role === 'kickoff') return '[Bot team setup]'
@@ -57,13 +61,22 @@ export function install(rt) {
// length when it went as a file (attachLong). `work`: the work (handoffs.js) a
// result that came back goes on with. `merged`: a request that takes in an earlier
// one its recipient had not read, under that one's exchange.
- async function deliver({ fromId, fromName: senderName, toId, sessionId, text, role, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, merged = false, abandoned = false, recordExchange = true, askedBy, fromRoomId, images = [], files = [], length, work }) {
+ // `handedBack`: this delivery is a pointer to a message the recipient already read in
+ // this Session, not the message itself (turns.js), so the dialogs read the body from
+ // the delivery that carried it.
+ async function deliver({ fromId, fromName: senderName, toId, sessionId, text, role, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, merged = false, abandoned = false, handedBack = false, recordExchange = true, askedBy, fromRoomId, images = [], files = [], length, work }) {
const from = rt.botOf(fromId)
const to = rt.botOf(toId)
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
const fromName = senderName ?? 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,
@@ -71,12 +84,14 @@ export function install(rt) {
role,
exchangeId,
senderName: fromName,
+ ...(origin === 'operator' ? { origin } : {}),
...(work ? { work } : {}),
...(fromId ? { senderSessionId: fromId } : {}),
...(replyTo ? { replyTo } : {}),
...(roomId ? { roomId } : {}),
...(audience === 'user' ? { audience } : {}),
...(deferred ? { deferred: true } : {}),
+ ...(handedBack ? { handedBack: true } : {}),
...(resumed ? { resumed: true } : {}),
...(retried ? { retried: true } : {}),
...(askedBy ? { askedBy } : {}),
@@ -96,6 +111,10 @@ export function install(rt) {
],
source,
})
+ // A Main Bot relaying a plan approval takes the Bot out of plan mode, before the
+ // message that carries it is read (card-gate.js).
+ ensurePlanOff(rt, agent, 'delivery')
+ relayPlanApproval(rt, { fromId, toId, agent, text })
if (steer) agent.steer(message)
else agent.followup(message)
await ctx.sessions.flush(agent.session)
@@ -124,6 +143,9 @@ export function install(rt) {
try {
for await (const event of rt.eventsBackwards(entry.sessionId ?? rt.chatOf(entry.to), AbortSignal.timeout(HISTORY_TIMEOUT_MS))) {
if (event.type !== 'user/message' || event.data?.source?.exchangeId !== entry.id) continue
+ // A hand-back carries a pointer, not the message; the delivery that brought it is
+ // further back and is what the dialog shows.
+ if (event.data.source.handedBack === true) continue
const delivered = textOf(event.data.content)
const text = delivered.slice(delivered.indexOf('\n') + 1)
return { text: headOf(text, TEXT_SHOW_MAX), whole: text.length <= TEXT_SHOW_MAX }
diff --git a/ds-bot/src/host/handoffs.js b/ds-bot/src/host/handoffs.js
index d0725e71be..ef145c27dd 100644
--- a/ds-bot/src/host/handoffs.js
+++ b/ds-bot/src/host/handoffs.js
@@ -16,6 +16,10 @@ const minutes = since => {
return count < 1 ? 'for less than a minute' : `for ${count} min`
}
+// How long a work with no result at all may still count as waiting. Past this the
+// reply is taken as lost, so its Bot stops showing as loaded on work that ended.
+const WAIT_CEILING_MS = 24 * 60 * 60 * 1000
+
export function install(rt) {
const { ctx, state } = rt
const works = () => (state.works ??= {})
@@ -94,13 +98,22 @@ 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 turn = rt.operatorTurnOf?.(from)
+ const origin = above?.origin ?? (turn !== undefined ? 'operator' : undefined)
+ // The operator's ask rides on the work, so a Bot that takes the job on still shows
+ // it after the turn that took it has ended.
+ const ask = above?.ask ?? turn?.askText
+ works()[id] = { ...(from ? { from } : {}), ...(to ? { to } : {}), ...(room ? { room } : {}), ...(above ? { parent } : {}), ...(fromRoom ? { fromRoom } : {}), ...(name ? { name } : {}), ...(child ? { child } : {}), ...(origin ? { origin } : {}), ...(ask ? { ask: headOf(ask, 240) } : {}), open: [], results: [], at: Date.now() }
if (above !== undefined) above.open.push(id)
save()
}
@@ -115,6 +128,9 @@ export function install(rt) {
for (const child of Object.values(works())) if (child.parent === id) delete child.parent
const above = works()[work.parent]
if (above !== undefined) {
+ // The work reads closed the moment the reply is recorded, not when the Bot that
+ // asked gets round to reading it. The result below is what carries the answer up.
+ above.open = (above.open ?? []).filter(other => other !== id)
// The whole result goes into a file of its own before the team file names it.
const file = keepResult(id, text)
above.results.push({ id, name, text: headOf(text, TEXT_KEPT), ...(work.child ? { child: work.child } : {}), ...(text.length > TEXT_KEPT ? { length: text.length } : {}), ...(file ? { file } : {}), at: Date.now(), ...extra })
@@ -135,8 +151,11 @@ export function install(rt) {
let settled
let live
for (const [workId, work] of Object.entries(works())) {
- for (const openId of work.open) {
- const result = work.results?.find(result => result.id === openId)
+ const results = work.results ?? []
+ // A settled run is no longer open, so the results name it too.
+ const ids = new Set([...(work.open ?? []), ...results.map(result => result.id)])
+ for (const openId of ids) {
+ const result = results.find(item => item.id === openId)
if ((result?.child ?? works()[openId]?.child ?? openId) !== id) continue
if (result === undefined) live ??= { id: openId, parent: workId }
else if (settled === undefined || (result.at ?? 0) < settled.at) settled = { id: openId, parent: workId, at: result.at ?? 0 }
@@ -216,9 +235,19 @@ export function install(rt) {
// that goes up names it.
function answerMissed(id) {
for (const work of Object.values(works())) {
- if (!work.open.includes(id)) continue
+ // A work reads closed as soon as its reply is recorded, so the result is the
+ // record that the reply belongs to it.
const result = (work.results ?? []).find(item => item.id === id)
- if (result !== undefined) result.failed = true
+ if (result === undefined) {
+ if (!(work.open ?? []).includes(id)) continue
+ save()
+ return
+ }
+ result.failed = true
+ // The reply never reached the asker, so the work waits again until the notice
+ // that carries the answer is read.
+ work.open ??= []
+ if (!work.open.includes(id)) work.open.push(id)
save()
return
}
@@ -269,26 +298,76 @@ export function install(rt) {
// Two requests from one sender belong to the same work when they were sent for it.
const sameWork = (id, parent) => (works()[id]?.parent ?? undefined) === (works()[parent] === undefined ? undefined : parent)
+ // A work stops waiting when its reply has arrived, or when it has sat past the
+ // ceiling with no result at all. An open id left behind by a reply that came back
+ // another way must not make its Bot look loaded for days. A subagent run has no Bot
+ // to hand back, so neither rule applies to it.
+ const arrived = (work, childId) => (work.results ?? []).some(result => result.id === childId)
+ const pastCeiling = work => Date.now() - (work.at ?? 0) > WAIT_CEILING_MS
+ const forgotten = work => (work.results ?? []).length === 0 && pastCeiling(work)
+ const stillOwed = (work, childId, child) => child.to === undefined || (!arrived(work, childId) && !forgotten(work))
+
// The works their Bots wait on, outside a turn that does them (`busy`): each with what
// it handed on that has not come back yet. One that came back waits only to be read.
const held = busy => Object.entries(works())
.filter(([id, work]) => work.to !== undefined && work.open.length > 0 && !busy.has(id))
- .map(([id, work]) => ({ id, work, out: work.open.map(childId => ({ id: childId, work: works()[childId] })).filter(child => child.work !== undefined) }))
+ .map(([id, work]) => ({
+ id,
+ work,
+ out: work.open
+ .map(childId => ({ id: childId, work: works()[childId] }))
+ .filter(child => child.work !== undefined)
+ .filter(child => stillOwed(work, child.id, child.work)),
+ }))
const busyWith = sessionIds => new Set(sessionIds.map(sessionId => rt.live.get(sessionId)).filter(entry => entry?.turn !== undefined).map(entry => workOf(entry.info)).filter(Boolean))
+ // What a Bot sent from outside any work, such as its chat with the user: nothing above
+ // these holds their wait, and the sender waits until the reply closes them.
+ const sentOnOwn = () => Object.values(works())
+ .filter(work => work.to !== undefined && works()[work.parent] === undefined && rt.botOf(work.from) !== undefined && rt.botOf(work.to) !== undefined)
+
+ // Per Bot, the Bots and groups it waits for, and the Bots it does that work for. `for`
+ // stays empty for work a Bot sent on its own, which it does for the user.
+ // local: waiting-live-only. A group wait and a subagent run have no Bot to test and
+ // always count; the wait mark, the status line and the give-up menu's waits all read
+ // this filter. A handed-on work counts only while the Bot it went to is
+ // still on it: running a turn, holding an approval or a part switch, with a message
+ // unread, or itself waiting on work it handed on. A work whose Bot answered some other
+ // way and went idle stays open in the books, but no longer marks the asker waiting.
+ // Whether a Bot is still on work handed to it, for the waits above. The same test
+ // drives the sidebar clock and the status line other Bots read, so the two agree.
+ const onItTest = () => {
+ const pending = held(busyWith([...rt.live.keys()]))
+ const holders = new Set(pending.filter(({ out }) => out.length > 0).map(({ work }) => work.to))
+ const approvals = new Set((rt.approvalsView?.() ?? []).map(entry => entry.botId))
+ const switching = new Set([...(rt.switchJobs?.() ?? [])].map(job => job.botId).filter(Boolean))
+ return (botId) => {
+ if (botId === undefined) return false
+ if (approvals.has(botId) || switching.has(botId) || holders.has(botId)) return true
+ const chat = rt.chatOf?.(botId)
+ const sessions = [chat, ...(rt.groupSessionsOf?.(botId) ?? [])].filter(Boolean)
+ if (sessions.some(sessionId => rt.live.get(sessionId)?.turn !== undefined)) return true
+ return chat !== undefined && (rt.unreadOf?.(chat) ?? []).length > 0
+ }
+ }
- // Per Bot, the Bots and groups it waits for, and the Bots it does that work for.
function waitingView() {
const view = {}
const add = (list, id) => { if (id !== undefined && !list.includes(id)) list.push(id) }
- for (const { work, out } of held(busyWith([...rt.live.keys()]))) {
- if (out.length === 0) continue
+ const pending = held(busyWith([...rt.live.keys()]))
+ const onIt = onItTest()
+ for (const { work, out } of pending) {
+ const live = out.filter(({ work: child }) => child.room !== undefined || child.to === undefined || onIt(child.to))
+ if (live.length === 0) continue
const entry = view[work.to] ??= { bots: [], rooms: [], for: [], waits: [] }
- for (const { id, work: child } of out) {
+ for (const { id, work: child } of live) {
add(child.room ? entry.rooms : entry.bots, child.room ?? child.to)
entry.waits.push({ id, ...(child.room ? { room: child.room, name: rt.roomOf(child.room)?.name } : { to: child.to, name: nameOf(child.to) ?? child.name }) })
}
add(entry.for, work.from)
}
+ // An ask sent on its own marks its sender waiting only while it is recent: one
+ // whose answer never closed it must not label an idle Bot for days.
+ for (const work of sentOnOwn()) if (onIt(work.to) && !pastCeiling(work)) add((view[work.from] ??= { bots: [], rooms: [], for: [] }).bots, work.to)
return view
}
@@ -414,12 +493,18 @@ export function install(rt) {
const entry = rt.live.get(sessionId)
lines.push(`working ${place(sessionId)} ${minutes(entry.since ?? Date.now())}${forWhom(sessionId, entry.info)}${doing(entry)}`)
}
+ // local: waiting-live-only. Only waits on a teammate still on the work are named.
+ const onIt = onItTest()
for (const { work, out } of held(busyWith(running))) {
if (work.to !== botId) continue
+ const live = out.filter(({ work: child }) => child.room !== undefined || child.to === undefined || onIt(child.to))
+ if (out.length > 0 && live.length === 0) continue
const forName = nameOf(work.from) ? `, for ${nameOf(work.from)}` : ''
- const on = [...new Set(out.map(({ work: child }) => (child.room ? `group "${rt.roomOf(child.room)?.name ?? 'a group'}"` : child.name ?? nameOf(child.to) ?? 'a teammate')))]
+ const on = [...new Set(live.map(({ work: child }) => (child.room ? `group "${rt.roomOf(child.room)?.name ?? 'a group'}"` : child.name ?? nameOf(child.to) ?? 'a teammate')))]
lines.push(on.length > 0 ? `waiting for ${on.join(' and ')} to hand back work${forName}` : `about to go on with work${forName}, whose results came back`)
}
+ const sent = [...new Set(sentOnOwn().filter(work => work.from === botId && onIt(work.to)).map(work => nameOf(work.to)))]
+ if (sent.length > 0) lines.push(`waiting for ${sent.join(' and ')} to answer`)
if (lines.length === 0) lines.push('idle')
if (state.questions?.[chat] !== undefined) lines.push('a question card in its own chat waits for the user\'s answer')
if (state.views?.[chat] !== undefined) lines.push('a view card in its own chat waits for the user\'s answer')
@@ -432,5 +517,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, abandonWork, abandonedWork: takeAbandoned })
+ 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, abandonWork, abandonedWork: takeAbandoned })
}
diff --git a/ds-bot/src/host/local-agents/claude.js b/ds-bot/src/host/local-agents/claude.js
index 3bef6730ff..35359b0a8c 100644
--- a/ds-bot/src/host/local-agents/claude.js
+++ b/ds-bot/src/host/local-agents/claude.js
@@ -1,11 +1,77 @@
// The Claude Code engine: one process per session, stream-json both ways.
// stdin takes user/control JSON messages; stdout streams the assistant's
// events until a `result` ends the turn.
+import { randomUUID } from 'node:crypto'
+import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { cleanEnv, spawnAgent } from './discover.js'
// Claude Code tools that only read; the rest may change files or run something.
const READ_TOOLS = new Set(['Read', 'Glob', 'Grep', 'LS', 'WebFetch', 'WebSearch', 'TodoWrite', 'NotebookRead'])
+// Windows allows 32,767 characters for a process's whole command line and Node
+// throws ENAMETOOLONG a little above that, before the process starts. A Bot's
+// assembled system prompt alone can be 40 KB, so it travels in a file and only
+// its path is an argument. The cap here sits below Windows' own so a failure
+// names the offending flag instead of surfacing "spawn ENAMETOOLONG".
+const COMMAND_LINE_LIMIT = 30_000
+const SYSTEM_FILE_DIR = join(tmpdir(), 'dsbot-claude-system')
+const SYSTEM_FILE_MAX_AGE_MS = 24 * 60 * 60 * 1_000
+
+// Files this process still owns, so an ordinary quit leaves none behind. A hard
+// kill runs no handler at all, which is what the age sweep below is for.
+const liveSystemFiles = new Set()
+let swept = false
+
+process.on('exit', () => {
+ for (const file of liveSystemFiles) unlinkQuietly(file)
+})
+
+function unlinkQuietly(file) {
+ liveSystemFiles.delete(file)
+ try { unlinkSync(file) } catch { /* the exit handler and close() can both reach it */ }
+}
+
+// Only a file nobody is reading is ever old enough, because a live session's
+// file is minutes old. So this cannot remove one that a CLI is about to read.
+function sweepStaleSystemFiles(now = Date.now()) {
+ if (swept) return
+ swept = true
+ let names
+ try { names = readdirSync(SYSTEM_FILE_DIR) } catch { return }
+ for (const name of names) {
+ const file = join(SYSTEM_FILE_DIR, name)
+ try {
+ if (now - statSync(file).mtimeMs > SYSTEM_FILE_MAX_AGE_MS) unlinkQuietly(file)
+ } catch { /* another session removed it first */ }
+ }
+}
+
+function writeSystemFile(sessionId, system) {
+ sweepStaleSystemFiles()
+ mkdirSync(SYSTEM_FILE_DIR, { recursive: true, mode: 0o700 })
+ const safe = String(sessionId).replace(/[^A-Za-z0-9_-]/gu, '_').slice(0, 40)
+ const file = join(SYSTEM_FILE_DIR, `${safe}-${randomUUID()}.txt`)
+ writeFileSync(file, system, { encoding: 'utf8', mode: 0o600 })
+ liveSystemFiles.add(file)
+ return file
+}
+
+// The system prompt is the only large argument today, but a custom agent's own
+// arguments could grow the same way. Failing here names which one to look at.
+function guardCommandLine(bin, args) {
+ const total = [bin, ...args].reduce((sum, part) => sum + part.length + 3, 0)
+ if (total <= COMMAND_LINE_LIMIT) return
+ let longest = 0
+ for (let index = 1; index < args.length; index += 1) if (args[index].length > args[longest].length) longest = index
+ const owner = longest > 0 && args[longest - 1].startsWith('--') ? args[longest - 1] : 'the agent arguments'
+ throw Object.assign(
+ new Error(`this agent's command line is ${total} characters and Windows allows ${COMMAND_LINE_LIMIT}; the longest argument belongs to ${owner}, so shorten it or use a file-backed form of that flag`),
+ { code: 'LOCAL_AGENT_EXIT' },
+ )
+}
+
export class ClaudeEngine {
constructor(route, engine, { findExecutable }) {
this.route = route
@@ -82,28 +148,68 @@ class ClaudeSession {
// CLI starts an interactive session and never speaks this protocol.
const args = [...(this.engine.engine.args ?? []), '--print', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose']
if (resumeId !== undefined) args.push('--resume', resumeId)
- if (system !== undefined) args.push('--append-system-prompt', system)
+ // A Bot with a large instruction set puts the whole prompt on the command
+ // line under the inline flag and the process never starts, so the prompt
+ // goes to a file and only its path is an argument.
+ let systemFile
+ if (system !== undefined) {
+ // Local patch 2026-11-09 (codebots): the DSH-built prompt names the
+ // DeepSeek model; on this route the model is Claude Code's.
+ const route = `running in the Claude Code program (model: ${model ?? 'CLI default'})`
+ system = system.replace(/powered by the \S+ model/g, route)
+ try {
+ systemFile = writeSystemFile(this.dshSessionId, system)
+ args.push('--append-system-prompt-file', systemFile)
+ } catch (error) {
+ // A small prompt still starts inline, so a broken temp folder does not
+ // take away a Bot that worked before this file existed.
+ if (system.length >= COMMAND_LINE_LIMIT) throw Object.assign(
+ new Error(`the system prompt could not be written to ${SYSTEM_FILE_DIR} and is too large for the command line: ${error.message}`),
+ { code: 'LOCAL_AGENT_EXIT' },
+ )
+ args.push('--append-system-prompt', system)
+ }
+ }
+ this.systemFile = systemFile
if (mode !== undefined) args.push('--permission-mode', mode)
if (model !== undefined && model !== 'default') args.push('--model', model)
// Print mode has no one to ask: without a prompt tool a call that needs
// permission is refused outright. `stdio` sends it here as a
// control_request, which becomes the Bot's approval card.
args.push('--permission-prompt-tool', 'stdio')
+ // Local patch 2026-11-09 (codebots): coding bots run at high effort unless
+ // the engine sets its own, and load only the bot tools plus the
+ // work-history search, never the user's business MCP servers.
+ args.push('--effort', this.engine.engine.effort ?? 'high')
+ const mcpServers = {
+ 'claude-memory-bridge': {
+ type: 'stdio',
+ command: 'C:\\Users\\SteveDempsey\\AppData\\Local\\Programs\\Python\\Python314\\python.exe',
+ args: ['C:\\Claude\\integrations\\Claude Memory Bridge\\server.py'],
+ },
+ }
+ if (mcp !== undefined) mcpServers.dsbot = { type: 'http', url: mcp.url, headers: { Authorization: `Bearer ${mcp.token}` } }
+ args.push('--strict-mcp-config', '--mcp-config', JSON.stringify({ mcpServers }))
if (mcp !== undefined) {
- args.push('--mcp-config', JSON.stringify({
- mcpServers: { dsbot: { type: 'http', url: mcp.url, headers: { Authorization: `Bearer ${mcp.token}` } } },
- }))
// DS Bot's own team tools need no approval, as for a model-backed Bot:
// toolsFor() already narrowed what this Bot may call.
args.push('--allowedTools', 'mcp__dsbot')
}
this.resumeId = resumeId
- const child = this.child = spawnAgent(bin, args, {
- env: cleanEnv(this.engine.env ?? {}),
- cwd,
- stdio: ['pipe', 'pipe', 'pipe'],
- windowsHide: true,
- })
+ guardCommandLine(bin, args)
+ let child
+ try {
+ child = spawnAgent(bin, args, {
+ env: cleanEnv(this.engine.env ?? {}),
+ cwd,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ })
+ } catch (error) {
+ if (systemFile !== undefined) unlinkQuietly(systemFile)
+ throw error
+ }
+ this.child = child
// stderr is not part of the protocol, but it is where a CLI that cannot
// start says why; its tail goes into the error the turn shows.
let stderr = ''
@@ -136,6 +242,7 @@ class ClaudeSession {
})
child.on('error', (error) => {
this.dead = true
+ if (systemFile !== undefined) unlinkQuietly(systemFile)
const failure = fail(`${this.engine.engine.name} could not start: ${error.message}`)
this.rejectStart?.(failure)
this.rejectStart = undefined
@@ -143,6 +250,7 @@ class ClaudeSession {
})
child.on('exit', (code, signal) => {
this.dead = true
+ if (systemFile !== undefined) unlinkQuietly(systemFile)
// Claude Code deletes old conversations; resuming one that is gone exits
// before init with this line on stderr.
if (this.resumeId !== undefined && this.cliSessionId === undefined && /no conversation found/i.test(stderr)) this.resumeMissing = true
@@ -238,6 +346,10 @@ class ClaudeSession {
kill() {
this.dead = true
+ // The CLI read the prompt at startup and a kill ends the session, so the
+ // file cannot be needed again and is removed now rather than at exit.
+ if (this.systemFile !== undefined) unlinkQuietly(this.systemFile)
+ this.systemFile = undefined
this.child?.kill('SIGTERM')
setTimeout(() => { try { this.child?.kill('SIGKILL') } catch {} }, 5_000).unref?.()
this.child = undefined
diff --git a/ds-bot/src/host/operator-tasks.js b/ds-bot/src/host/operator-tasks.js
new file mode 100644
index 0000000000..3f4b47733b
--- /dev/null
+++ b/ds-bot/src/host/operator-tasks.js
@@ -0,0 +1,190 @@
+// 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'
+
+export const DEFAULT_REGISTER = join(homedir(), '.claude', 'state', 'loose-ends', 'register.jsonl')
+// The register is polled with every state answer; a stat this often is enough.
+const STAT_EVERY_MS = 2000
+const TEXT_MAX = 240
+
+const clip = (text, max = TEXT_MAX) => {
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim()
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat
+}
+// The operator's ask, as the card keeps it: the first line of their message, trimmed.
+// A step the Bot took later is not the ask, so work without one keeps no text at all.
+const askLine = (text) => {
+ const line = String(text ?? '').split(/\r?\n/).map(part => part.trim()).find(part => part !== '')
+ return line === undefined ? undefined : clip(line, 160)
+}
+// A relayed message opens with the relay header line: it frames the message, it is not
+// part of what the operator asked for.
+const relayBody = (work) => {
+ const text = String(work.ask ?? '')
+ return work.originFrom === undefined ? text : text.replace(/^\[(?:[^\r\n]*\]\r?\n|[^\]\r?\n]*\])/, '')
+}
+const timeOf = (value) => {
+ const at = typeof value === 'number' ? value : Date.parse(String(value ?? ''))
+ return Number.isFinite(at) ? at : undefined
+}
+
+// The register is append-only: the newest record of an id is its current state, and
+// its first record says when it was opened. Only open decisions wait on the operator.
+export function openDecisions(text) {
+ const latest = new Map()
+ const opened = new Map()
+ for (const line of String(text ?? '').split(/\r?\n/)) {
+ if (line.trim() === '') continue
+ let record
+ try { record = JSON.parse(line) } catch { continue }
+ if (typeof record?.id !== 'string') continue
+ if (!opened.has(record.id)) opened.set(record.id, timeOf(record.ts))
+ latest.set(record.id, record)
+ }
+ const decisions = []
+ for (const record of latest.values()) {
+ if (record.state !== 'open' || record.kind !== 'decision' || typeof record.owner !== 'string') continue
+ decisions.push({
+ id: record.id,
+ owner: record.owner,
+ text: clip(record.text),
+ ...(record.due ? { due: String(record.due) } : {}),
+ ...(record.risk ? { risk: String(record.risk) } : {}),
+ carded: Boolean(record.carded_at),
+ at: opened.get(record.id) ?? timeOf(record.ts),
+ })
+ }
+ return decisions
+}
+
+export function install(rt) {
+ const { state } = rt
+ const configured = rt.config?.looseEnds
+ const path = configured === false ? undefined : (configured ?? process.env.DS_BOT_LOOSE_ENDS ?? DEFAULT_REGISTER)
+ let cache = { key: '', decisions: [] }
+ let checkedAt = 0
+
+ const decisions = () => {
+ if (path === undefined) return []
+ const now = Date.now()
+ if (now - checkedAt < STAT_EVERY_MS) return cache.decisions
+ checkedAt = now
+ let key
+ try {
+ const stat = statSync(path)
+ key = `${stat.mtimeMs}:${stat.size}`
+ } catch {
+ // No register on this machine: the section is just empty.
+ cache = { key: '', decisions: [] }
+ return cache.decisions
+ }
+ if (key === cache.key) return cache.decisions
+ try {
+ cache = { key, decisions: openDecisions(readFileSync(path, 'utf8')) }
+ } catch {
+ cache = { key: '', decisions: [] }
+ }
+ return cache.decisions
+ }
+
+ const botOfSession = id => rt.groupOwners?.get(id)?.botId ?? rt.chatOwners?.get(id)
+ const roomOfSession = id => rt.groupOwners?.get(id)?.roomId
+
+ function operatorTasksView() {
+ const view = {}
+ const entryOf = (botId) => {
+ if (botId === undefined || state.bots?.[botId] === undefined) return undefined
+ return (view[botId] ??= { operator: [], active: [], unresolved: [] })
+ }
+ const add = (botId, list, item) => { entryOf(botId)?.[list].push(item) }
+
+ for (const [sessionId, question] of Object.entries(state.questions ?? {})) {
+ if (question === undefined || question === null) continue
+ const roomId = roomOfSession(sessionId)
+ add(botOfSession(sessionId), 'unresolved', { kind: 'question', key: `question:${question.id ?? sessionId}`, text: clip(question.question), at: question.askedAt, sessionId, ...(roomId ? { roomId } : {}) })
+ }
+ for (const [sessionId, card] of Object.entries(state.views ?? {})) {
+ if (card === undefined || card === null) continue
+ const roomId = roomOfSession(sessionId)
+ add(botOfSession(sessionId), 'unresolved', { kind: 'view', key: `view:${card.id ?? sessionId}`, text: clip(card.title), at: card.askedAt, sessionId, ...(roomId ? { roomId } : {}) })
+ }
+ for (const [botId, list] of Object.entries(state.secretRequests ?? {})) {
+ for (const request of list ?? []) {
+ if (request?.status !== 'pending') continue
+ add(botId, 'unresolved', { kind: 'key', key: `key:${request.id}`, text: clip(request.name, 80), ...(request.purpose ? { detail: clip(request.purpose) } : {}), at: request.askedAt, ...(request.sessionId ? { sessionId: request.sessionId } : {}) })
+ }
+ }
+ for (const approval of rt.approvalsView?.() ?? []) {
+ add(approval.botId, 'unresolved', { kind: 'approval', key: `approval:${approval.id}`, text: clip(approval.tool, 80), ...(approval.reason ? { detail: clip(approval.reason) } : {}), at: approval.at, sessionId: approval.sessionId, ...(approval.roomId ? { roomId: approval.roomId } : {}) })
+ }
+ const byName = new Map(Object.values(state.bots ?? {}).map(bot => [bot.name, bot.id]))
+ for (const decision of decisions()) {
+ const { owner, id, ...rest } = decision
+ 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?.() ?? {})) {
+ const operator = work.origin === 'operator'
+ if (work.work !== undefined) runningWork.set(botId, work.work)
+ // The ask the work was opened for outlives the turn that took it, so a Bot that
+ // took the job on shows what the operator asked for, not the hand-on message.
+ const openedFor = operator && work.work !== undefined ? state.works?.[work.work]?.ask : undefined
+ const text = operator ? askLine(openedFor ?? relayBody(work)) : 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
+ // 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?.() ?? {})) {
+ 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.operator, entry.active, entry.unresolved]) list.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity))
+ }
+ return view
+ }
+
+ rt.operatorTasksView = operatorTasksView
+}
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js
index 6cdb67497b..859bf20d06 100644
--- a/ds-bot/src/host/parts.js
+++ b/ds-bot/src/host/parts.js
@@ -17,6 +17,7 @@
import { randomUUID } from 'node:crypto'
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
import { openTurnAt } from './btw.js'
+import { ensurePlanOff } from './card-gate.js'
import { HANDOFF_ACK, HISTORY_TIMEOUT_MS, REPLY_KIND, SOURCE_KIND } from './constants.js'
import { parseReplies, stackReplies } from '../shared/group-replies.js'
import { CHECKPOINT_PROMPT, STEWARD_SYSTEM, checkpointCount, checkpointTail, checkpointTailNote, checkpointText, linesFor, parseDecision, stewardRequest } from './steward.js'
@@ -347,7 +348,11 @@ export function install(rt) {
}
adoptedEngines.clear()
}, 'ds-bot: Bot compaction')
- ctx.on('agent/created', ({ agent }) => { adoptCompaction(agent) })
+ ctx.on('agent/created', ({ agent }) => {
+ adoptCompaction(agent)
+ // A Bot Session resumed after a restart leaves the plan mode DSH pinned on it, once.
+ ensurePlanOff(rt, agent, 'resumed')
+ })
// A Bot's own chat, or its Session in one group, or the group's own Session
// (`botId === undefined`), as numbered parts, oldest first; the last one is
@@ -1286,6 +1291,69 @@ export function install(rt) {
return switchBeforeStep(agent, payload, { hard: true })
}, { prepend: true })
+ // [2026-11-05] A step failure used to reach the chat as a bare message: DSH reports
+ // the turn with a message and a code and no frames, so nothing named the line that
+ // threw. This wraps the rest of the chain (registered after the handler above, so
+ // `prepend` puts it first) and records the stack once per failed step. It changes
+ // nothing about the outcome: the error is rethrown exactly as it came.
+ ctx.on('agent/pre-step', async (payload, next) => {
+ try {
+ return await next()
+ } catch (error) {
+ try {
+ const sessionId = payload?.agent?.id
+ rt.noteFailure?.({
+ source: 'turn',
+ text: error?.message ?? String(error),
+ code: typeof error?.code === 'string' ? error.code : undefined,
+ stack: typeof error?.stack === 'string' ? error.stack : undefined,
+ bot: rt.botOf?.(rt.selfOf?.(sessionId))?.name,
+ where: placeOf(sessionId),
+ sessionId,
+ })
+ } catch { /* never let the reporter change the failure */ }
+ throw error
+ }
+ }, { prepend: true })
+
+ // [2026-11-05] DSH resolves the tool set and assembles the system prompt BEFORE it
+ // enters the pre-step chain, so a throw there reaches the chat as a bare message and
+ // no pre-step listener can ever see it. These two seams are the only code that runs
+ // in that window. Wrapping them records the frames once and rethrows unchanged, so
+ // nothing about behaviour moves. A seam that is missing or already wrapped is skipped.
+ const wrappedSeams = new WeakSet()
+ for (const seam of [
+ { label: 'tools.resolve', service: () => ctx.get('tools'), method: 'resolve' },
+ { label: 'systemPrompt.assemble', service: () => ctx.get('systemPrompt'), method: 'assemble' },
+ ]) {
+ try {
+ const service = seam.service()
+ const original = service?.[seam.method]
+ if (service === undefined || service === null || typeof original !== 'function' || wrappedSeams.has(service)) continue
+ wrappedSeams.add(service)
+ service[seam.method] = async function wrappedSeam(...args) {
+ try {
+ return await original.apply(this, args)
+ } catch (error) {
+ try {
+ const agent = args?.[0]?.agent ?? (args?.[0]?.session === undefined ? undefined : { id: args[0].session.id })
+ const sessionId = agent?.id ?? agent?.session?.id
+ rt.noteFailure?.({
+ source: 'turn',
+ text: `${seam.label}: ${error?.message ?? String(error)}`,
+ code: typeof error?.code === 'string' ? error.code : undefined,
+ stack: typeof error?.stack === 'string' ? error.stack : undefined,
+ bot: rt.botOf?.(rt.selfOf?.(sessionId))?.name,
+ where: 'before the pre-step chain',
+ sessionId,
+ })
+ } catch { /* never let the reporter change the failure */ }
+ throw error
+ }
+ }
+ } catch { /* a seam we cannot wrap must not stop the plugin loading */ }
+ }
+
// `messages` left the inbox for this step, so the switch carries them along.
function switchBeforeStep(agent, payload, options) {
// A switch may have started while the checks above awaited.
diff --git a/ds-bot/src/host/privacy.js b/ds-bot/src/host/privacy.js
index dc48b973e1..c11cf2822b 100644
--- a/ds-bot/src/host/privacy.js
+++ b/ds-bot/src/host/privacy.js
@@ -195,6 +195,11 @@ export function install(rt) {
if (bot) throw closed(bot, 'turns')
return
}
+ case 'void_question': {
+ const bot = target(args.bot)
+ if (bot) throw closed(bot, 'questions')
+ return
+ }
case 'attach_capability':
case 'detach_capability': {
const bot = target(args.bot)
diff --git a/ds-bot/src/host/prompt.js b/ds-bot/src/host/prompt.js
index 46e11ba47e..c303038b62 100644
--- a/ds-bot/src/host/prompt.js
+++ b/ds-bot/src/host/prompt.js
@@ -14,7 +14,7 @@ const TEAM_RULES = [
'- Only for a direct user request in your own chat that needs several steps: write one short sentence of normal reply text before your first tool call, and make that tool call in the same response. Never start such a task with tools alone or end it with a promise. On long tasks, give brief factual updates only at meaningful milestones, then keep working.',
'- For "[Message from …]" or "[Reply from …]" messages, do not write plans or progress updates: use tools silently, then reply with the answer. Simple answers do not need progress messages.',
'- In a group chat, the group sees what you write while you work, not only your final reply. For work that takes more than a quick look, start with one short sentence on what you will do, in the same response as your first tool call. After that, write only when you find something the group should know or finish a part of the work, in a sentence or two, not at every step. End with the result. Simple answers need no updates.',
- '- Offer choices with ask_user (a tap-to-answer card) instead of long option lists in text. Calling it ends your turn at once, so write everything you want to say before the call, in the same reply. The answer arrives as the user\'s next message.',
+ '- Offer choices with ask_user (a tap-to-answer card) instead of long option lists in text. Calling it ends your turn at once, so write everything you want to say before the call, in the same reply. The answer arrives as the user\'s next message. The card stays open only until your next finished turn the user can see: a turn in your own chat that asks nothing closes it and a later click on it is refused, so ask again if you still need the answer. A turn that answers another Bot leaves it open.',
'- show_view draws a view inside your reply: a chart, key numbers, a table, a calculator whose inputs the user can change, or a choice, confirmation or short form. Use it when it shows something better than text, not for every answer. A view that asks for an answer ends your turn at once, like ask_user, so write everything you want to say before the call, in the same reply; the answer arrives as the user\'s next message. It only works in your own chat, not in a group. Never collect a key, token, or password with it; call request_secret. The view argument is limited to 8 KB.',
'- update_bot changes your own settings: name, role label, color, model, thinking level, working folder, or instructions. Leave out bot to change yourself. Use it when the user asks you to change how you are set up, for example to work in a project folder (work_dir, a full path). Only a Main Bot can change other Bots; when another Bot needs changing, ask a Main Bot.',
'- You may be in group chats with the user and other Bots. You speak in each group from a separate conversation of yours, apart from your own chat with the user. There your turn arrives as a "[Group chat …]" message that shows the speaking order, and your reply is posted to the group. When someone there asks you to do something, do the work in that turn: the group goes on without waiting and sees what you write as you go. Any member can hand work to another with @Name, and the one that asked answers the result. Work for a group stays in it: there message_bot reaches only members of that group, as @Name does. In a group, read_own_chat shows your own chat (the group sees that you looked; share only what the group needs). In your own chat, read_group_chat shows what was said in a group. A group may have an admin, who steers it: the admin can call members with @Name and change the group with update_group. From outside a group (your own chat or another group), post_to_group posts into a group you are in: the admin\'s post starts a new discussion there; another member\'s post calls only the members it names with @Name.',
@@ -31,6 +31,7 @@ const MAIN_RULES = [
'- After creating a Bot, tell the user in one line that it is ready, using its exact name.',
'- Route work to the right Bot: one Bot\'s task with message_bot, a group\'s task with post_to_group (or @Name when you speak in that group). Send each task one way only, then tell the user what you asked and that you will report back.',
'- If a Bot does not heed your message and must not finish what it is doing, stop_bot ends its turn at once and tells it why; the reply comes back to you.',
+ '- When a question card another Bot left open no longer applies, void_question withdraws it and tells that Bot; a late click on it is refused.',
'- Every Bot runs on one model of its own (list_bots shows it). Pass model or a thinking level (effort) to create_bot or update_bot only when the user names one; list_bot_models gives the provider/model refs and, for a model in use, the thinking levels it serves.',
'- Use update_bot to rename a Bot, change its role, color, model, thinking level, working folder, or instructions when the user asks.',
'- You run the group chats too. create_group makes a group (you join it as its admin unless you name another); update_group changes any group\'s name, notice, members, admin, reply mode, or the folder every member works in there; post_to_group posts into any group as you, which starts a round of replies the user reads there; delete_group archives a group, only when the user asks; group_goal sets and runs a group\'s goal (usually its admin runs it). list_bots shows every group.',
diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.js
index a3c703ea72..033972b2cf 100644
--- a/ds-bot/src/host/roster.js
+++ b/ds-bot/src/host/roster.js
@@ -5,6 +5,7 @@ import { mkdir } from 'node:fs/promises'
import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOTICE_MAX, SECTION_COLORS, SECTION_NAME_MAX } from './constants.js'
import { currentColor, isColor, normalize, unquote } from './text.js'
import { nameProblem } from '../shared/mentions.js'
+import { ensurePlanOff } from './card-gate.js'
const BROWSER_GRANT_KINDS = new Set(['post', 'upload', 'download', 'delete', '*'])
const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/
@@ -95,6 +96,8 @@ export function install(rt) {
const { sessionId } = await ctx.sessionController.create({ ...place, ...await botPreset() })
const agent = await rt.resolveAgent(sessionId)
await ctx.sessionTitle.rename(agent.session, title)
+ // DSH's presets pin plan mode on for every new Session; a Bot's starts off (card-gate.js).
+ ensurePlanOff(rt, agent, 'new-session', { fresh: true })
return sessionId
}
diff --git a/ds-bot/src/host/schedules.js b/ds-bot/src/host/schedules.js
index 9c3aaec630..d916640dc9 100644
--- a/ds-bot/src/host/schedules.js
+++ b/ds-bot/src/host/schedules.js
@@ -36,6 +36,7 @@ function requestOf(record) {
if (record.kind === 'daily') return { ...base, daily: { time: record.time, time_zone: record.timeZone } }
if (record.kind === 'weekly') return { ...base, weekly: { time: record.time, time_zone: record.timeZone, weekdays: record.weekdays } }
if (record.kind === 'cron') return { ...base, cron: { expression: record.expression, time_zone: record.timeZone } }
+ if (record.kind === 'rrule') return { ...base, rrule: record.rrule }
return null
}
@@ -44,7 +45,7 @@ function requestOf(record) {
const hostWide = service => typeof service.edit === 'function'
// The existing Session a task delivers to; a task that opens new Sessions has none.
const sessionOf = entry => entry.target === undefined ? entry.sessionId : entry.target.kind === 'session' ? entry.target.sessionId : undefined
-const TIMING_KINDS = { at: 'at', every_seconds: 'every', daily: 'daily', weekly: 'weekly' }
+const TIMING_KINDS = { at: 'at', every_seconds: 'every', daily: 'daily', weekly: 'weekly', cron: 'cron', rrule: 'rrule' }
const OWN_TASK_TOOLS = ['schedule_edit', 'schedule_view']
// DSH 0.2.2's list page: 100 by default, at most 500.
const LIST_PAGE = 100
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 3846d665a3..d41e5cb6c7 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -3,6 +3,7 @@
import { randomUUID } from 'node:crypto'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { readAvatar } from './avatar.js'
+import { EXIT_PLAN_MODE, judgeCard, logCard, logGate, planTitle, refusePlan, viewLabels } from './card-gate.js'
import { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js'
import { within } from './folders.js'
import { absoluteLinks } from './links.js'
@@ -703,6 +704,10 @@ export function install(rt) {
.filter(option => option.label !== '')
.slice(0, 6)
if (options.length === 0) return 'Give at least one option.'
+ // A job another Bot sent is decided by that Bot, in its own chat (card-gate.js).
+ const judged = judgeCard(rt, id, options)
+ logCard(rt, 'ask_user', judged, args.question)
+ if (!judged.allowed) return judged.text
// A hidden Bot-to-Bot turn shows none of its calls, so its card goes to the
// composer dock, which takes questions without a call.
const turn = rt.live.get(id)?.turn
@@ -723,6 +728,39 @@ export function install(rt) {
},
}))
+ rt.teamTools.push(defineTool({
+ name: 'void_question',
+ description: 'Main Bot only. Withdraw the question card another Bot left open for the user, when it no longer applies. The card leaves the screen, a late click on it is refused, and the Bot is told in a new turn.',
+ parameters: {
+ bot: { type: 'string', required: true, description: 'Exact Bot name from list_bots' },
+ reason: { type: 'string', description: 'Why it was voided; the Bot reads this' },
+ },
+ output,
+ async execute(args, exec) {
+ await rt.load()
+ const sender = callerBot(exec)
+ if (sender === undefined || !rt.isMain(sender.id)) refuse('Only a Main Bot can void a question.')
+ const target = rt.findBot(args.bot)
+ if (target === undefined) refuse(`No Bot named ${args.bot}. Team: ${Object.values(state.bots).map(bot => bot.name).join(', ')}`)
+ const chat = rt.chatOf(target.id)
+ const question = rt.own(state.questions, chat)
+ if (question === undefined) refuse(`${target.name} has no open question.`)
+ delete state.questions[chat]
+ await rt.save()
+ if (target.id === sender.id) return 'Your question is voided.'
+ const why = String(args.reason ?? '').trim()
+ const text = `Your question "${question.question}" is withdrawn, so no answer to it will reach you. Do not act on it.${why ? `
+Reason: ${why}` : ''}`
+ try {
+ await rt.deliver({ fromId: sender.id, toId: target.id, text, role: 'voided', ...callerRoom(exec) })
+ } catch (error) {
+ rt.warn('ds-bot: telling %s its question was voided failed: %s', target.name, error)
+ return `The question of ${target.name} is voided, but ${target.name} could not be told. Tell it with message_bot.`
+ }
+ return `The question of ${target.name} is voided and it has been told.`
+ },
+ }))
+
// Scoped per Bot session, not global: another plugin's global show_view serves
// the sessions ds-bot does not own, while this one shadows it inside them.
rt.teamTools.push(defineTool({
@@ -743,6 +781,10 @@ export function install(rt) {
if (checked.interactive && args.await_reply === false) return 'This view has controls to submit, so it waits for the user\'s answer; call show_view without await_reply: false.'
const awaitReply = args.await_reply ?? checked.interactive
if (!awaitReply) return 'The view is on screen.'
+ // An interactive view is a card like ask_user's, so the same gate decides it.
+ const judged = judgeCard(rt, id, viewLabels(view))
+ logCard(rt, 'show_view', judged, title)
+ if (!judged.allowed) return judged.text
// A hidden Bot-to-Bot turn shows none of its calls, so its card goes to the
// composer dock, which takes a card without a call.
const turn = rt.live.get(id)?.turn
@@ -907,11 +949,12 @@ export function install(rt) {
const dispose = agent.ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
const assembled = await next()
// DSH 0.2.2 adds the tool list after this waterfall (#814), so only an
- // older assembly still carries tools to drop here.
+ // older assembly still carries tools to drop here. Both fields are guarded:
+ // an assembly that arrives without one is passed on as it is, never thrown on.
return {
...assembled,
- ...Array.isArray(assembled.tools) ? { tools: assembled.tools.filter(tool => !HIDDEN_TOOLS.includes(tool.name)) } : {},
- sections: assembled.sections.filter(section => !HIDDEN_SECTIONS.has(section.name)),
+ ...(Array.isArray(assembled?.tools) ? { tools: assembled.tools.filter(tool => !HIDDEN_TOOLS.includes(tool.name)) } : {}),
+ ...(Array.isArray(assembled?.sections) ? { sections: assembled.sections.filter(section => !HIDDEN_SECTIONS.has(section.name)) } : {}),
}
})
held.filtered = true
@@ -1036,6 +1079,13 @@ export function install(rt) {
if (exec.name === BLOCKING_QUESTION_TOOL) return `Bots cannot use ${BLOCKING_QUESTION_TOOL}. Ask with ask_user in your own chat, or ask in your reply.`
const target = exec.arguments?.target
if (SCHEDULE_TARGET_TOOLS.includes(exec.name) && target !== undefined && target !== 'this_session') return SCHEDULE_TARGET_REFUSAL
+ if (exec.name === EXIT_PLAN_MODE) {
+ // A plan for a job another Bot sent is approved through that Bot (card-gate.js).
+ const refused = refusePlan(rt, exec.agent?.id)
+ if (refused === undefined) return undefined
+ void logGate(rt, { bot: refused.bot, manager: refused.manager, tool: EXIT_PLAN_MODE, title: planTitle(exec.arguments?.plan) })
+ return refused.text
+ }
return DELEGATION_TOOLS.includes(exec.name) ? DELEGATION_REFUSAL : undefined
})
// Creation waits for this listener, so the Agent's first step already lacks the tool.
diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js
index 0cfa962f64..9071acffcb 100644
--- a/ds-bot/src/host/turns.js
+++ b/ds-bot/src/host/turns.js
@@ -29,6 +29,9 @@ export function turnFailure(error) {
message,
...(typeof error?.status === 'number' ? { status: error.status } : {}),
...(typeof error?.requestId === 'string' ? { requestId: error.requestId } : {}),
+ // Kept so a turn failure can name its own line in the diagnostics log. A provider
+ // error has no stack worth keeping, and AUTH already dropped its message.
+ ...(code !== 'AUTH' && typeof error?.stack === 'string' ? { stack: error.stack } : {}),
}
}
@@ -145,6 +148,11 @@ export const cutOffText = said => (said === '' ? CUT_OFF_EMPTY_NOTE : `${said}\n
const PROMISED_WORK = /(?:^(?:收到|好的|明白|好|行|没问题|了解)[,,、。.!!:\s]*(?:我(?:现在|这就|先|马上|立刻|去|来)?(?:开始|着手|去|来|准备)?(?:排查|检查|调查|查看|看看|搜索|搜一下|分析|处理|执行|运行|跑一下|修改|修复|实现|编写|整理|验证|测试|读一下|翻一下)(?!过了|过(?:[,,。.!!、;;\s]|$)|完了|完毕|好了)|(?:现在|马上|立刻)?(?:开始|着手)(?:执行|处理|排查|检查|调查|干活|开工)(?!过了|过(?:[,,。.!!、;;\s]|$)|完了|完毕|好了)|开工(?:[。!!,,\s]|$))|^(?:开工(?:[。!!,,\s]|$)|我(?:现在|这就|先|马上|立刻)(?:开始|着手|去)(?:排查|检查|调查|查看|搜索|分析|处理|执行|运行|修改|修复|实现|编写|整理|验证|测试)(?!过了|过(?:[,,。.!!、;;\s]|$)|完了|完毕|好了))|\b(?:(?:i\s+will|i'll|let\s+me|going\s+to)\s+(?:start|begin|check|look\s+into|investigate|search|run|inspect|read|fix|implement|work\s+on)\b|(?:starting|beginning)\s+(?:the\s+)?(?:investigation|check|search|work|execution|analysis)\b|^on\s+it[,.\s!]+(?:i'll|i\s+will|let\s+me|starting|checking)\b))/i
export const promisesWork = text => typeof text === 'string' && text.trim().length <= 240 && PROMISED_WORK.test(text.trim())
+// What a hand-back carries in place of the body. The Bot already read that message in
+// this Session, so sending it again makes the model read one message twice; the pointer
+// is enough to say the work is over and this one is now due an answer.
+export const HANDED_BACK = 'You read its text during that task; it is above in this session. Answer it now.'
+
export function install(rt) {
const { ctx, state } = rt
@@ -353,7 +361,7 @@ export function install(rt) {
/** @type {Record} */
let activity = {}
const activityOf = (tool) => {
- if (/^(message_bot|stop_bot|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(tool)) return 'sending'
+ if (/^(message_bot|stop_bot|void_question|create_bot|update_bot|create_group|update_group|delete_group|post_to_group)$/.test(tool)) return 'sending'
if (tool === 'group_relay') return 'orbit'
if (/search|fetch|browse|browser|read|grep|glob|list/i.test(tool)) return 'searching'
return 'working'
@@ -456,8 +464,23 @@ export function install(rt) {
// A group Session is hidden as a whole, so its turns need no marking. A handoff
// package that only opens a part is acknowledged with a fixed line, also hidden.
- const claimTrigger = (sessionId, entry, info) => {
+ const claimTrigger = (sessionId, entry, info, text) => {
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)
@@ -523,7 +546,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)
@@ -544,6 +578,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)
@@ -604,6 +652,7 @@ export function install(rt) {
code: failure.code,
status: failure.status,
requestId: failure.requestId,
+ stack: failure.stack,
bot: rt.botOf(rt.selfOf(id))?.name ?? (rt.roomOf(id) ? undefined : 'unknown Bot'),
where: placeOf(id),
sessionId: id,
@@ -762,10 +811,11 @@ export function install(rt) {
entry.carried = false
let claimedPending
let claimedPendingText
+ entry.card = state.questions[id]?.id
if (entry.pending !== undefined) {
claimedPending = entry.pending
claimedPendingText = entry.pendingText
- claimTrigger(id, entry, claimedPending)
+ claimTrigger(id, entry, claimedPending, claimedPendingText)
entry.pending = undefined
entry.pendingText = undefined
}
@@ -780,6 +830,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
@@ -815,6 +871,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
@@ -873,7 +940,7 @@ export function install(rt) {
entry.pending = source
entry.pendingText = textOf(event.data.content).replace(/^\[(?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/, '')
}
- else if (!opened) claimTrigger(id, entry, source)
+ else if (!opened) claimTrigger(id, entry, source, textOf(event.data.content).replace(/^\[(?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/, ''))
else if (source.work !== undefined && source.work !== rt.workOf?.(entry.info) && !expectsReply(source)) {
// A result for other work than this turn's informs it, and comes back in a
// turn of its own once this one ends, which goes on with that work.
@@ -955,6 +1022,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': {
@@ -980,9 +1054,10 @@ 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
const joined = entry.joined ?? []
// What the group already saw of the turn is not posted again.
const texts = entry.texts.slice(entry.shown)
@@ -999,6 +1074,14 @@ export function install(rt) {
const watched = entry.turn !== undefined
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
@@ -1015,17 +1098,20 @@ export function install(rt) {
const later = entry.later ?? []
entry.later = []
if (steerCut || suppressedSubagent) break
+ const card = entry.card
+ entry.card = undefined
for (const result of later) {
void rt.deliver({
fromId: result.info.senderSessionId,
toId: rt.selfOf(id),
- text: result.text,
+ text: HANDED_BACK,
role: result.info.role,
exchangeId: result.info.exchangeId,
replyTo: result.info.replyTo,
work: result.info.work,
...(result.info.roomId ? { roomId: result.info.roomId } : {}),
deferred: true,
+ handedBack: true,
}).catch(error => rt.warn('ds-bot: handing back a result failed: %s', error))
}
const reason = event.data?.reason
@@ -1078,6 +1164,16 @@ export function install(rt) {
void retryWrittenCall(id, info).catch(error => rt.warn('ds-bot: asking %s to run its written tool call failed: %s', id, error))
}
}
+ // A finished turn the user could see that asked nothing has moved on, so the card
+ // it left standing is stale. `card` is the card this turn opened on: a turn that
+ // asked has another id, or none here at all. A hidden Bot-to-Bot turn shows the user
+ // nothing, so its card still waits for them. A fresh part's handoff turn carries its
+ // card over; a failed or stopped turn said nothing about it.
+ const hidden = (state.exchangeTurns[id] ?? []).includes(turn)
+ if (card !== undefined && state.questions[id]?.id === card && reason?.kind === 'completed' && !retry && !hidden && info?.handoff !== true) {
+ delete state.questions[id]
+ void rt.save().catch(() => {})
+ }
const replyText = () => {
const reply = (wroteCall ? texts.map(stripWrittenCalls) : texts).join('\n\n').trim()
if (wroteCall && reply === '') return 'Tried to run a tool but wrote the call as text, so it did not run.'
@@ -1151,12 +1247,13 @@ export function install(rt) {
fromId: request.info.senderSessionId,
toId: rt.selfOf(id),
sessionId: id,
- text: request.text,
+ text: HANDED_BACK,
role: request.info.role,
exchangeId: request.info.exchangeId,
...(request.info.role === 'room' ? { roomId: request.info.roomId, askedBy: request.info.askedBy, note: 'you read this call during your last task; answer it now' } : {}),
...(request.info.senderRoomId ? { fromRoomId: request.info.senderRoomId } : {}),
deferred: true,
+ handedBack: true,
}).catch(error => rt.warn('ds-bot: deferred request delivery failed: %s', error))
}
if (rt.groupOwners.has(id)) void rt.goalSettled?.(rt.roomOf(rt.groupOwners.get(id).roomId)).catch(error => rt.warn('ds-bot: goal settle in %s failed: %s', id, error))
@@ -1238,5 +1335,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, stopChat, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents, adoptLiveWork })
+ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, operatorTurnOf, stopRoomTurn, stopChat, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents, adoptLiveWork })
}
diff --git a/ds-bot/test/bot-mark.test.js b/ds-bot/test/bot-mark.test.js
index 87d3ec7573..b30369ae3e 100644
--- a/ds-bot/test/bot-mark.test.js
+++ b/ds-bot/test/bot-mark.test.js
@@ -39,9 +39,14 @@ test('a Bot that waits for work it handed on has a mark of its own, behind a run
})
test('a waiting Bot does not wear the working badge, since no turn of it runs', () => {
- const badges = state => BotAvatar({ bot: { id: 'b', name: 'Writer' }, size: 36, state }).children.slice(1).filter(Boolean).map(child => child.props.className)
- assert.deepEqual(badges('waiting'), [])
+ const badges = (state, extra = {}) => BotAvatar({ bot: { id: 'b', name: 'Writer' }, size: 36, state, ...extra }).children.slice(1).filter(Boolean).map(child => child.props.className)
+ // local: waiting-mark. It wears a clock of its own instead.
+ assert.deepEqual(badges('waiting'), ['bt-badge bt-badge-waiting'])
assert.deepEqual(badges('working'), ['bt-badge bt-badge-working'])
+ // A Main Bot keeps its star and shows the wait opposite it.
+ assert.deepEqual(badges('waiting', { main: true }), ['bt-badge bt-badge-main', 'bt-badge bt-badge-waiting'])
+ assert.deepEqual(badges('waiting', { badge: false }), [])
+ assert.match(SHELL_CSS, /\.bt-badge-waiting\{right:auto;left:0;/)
})
test('a photo that does not load shows the Bot\'s character instead', () => {
diff --git a/ds-bot/test/bot-messages.test.js b/ds-bot/test/bot-messages.test.js
index 16c33dfa4e..be90927d2c 100644
--- a/ds-bot/test/bot-messages.test.js
+++ b/ds-bot/test/bot-messages.test.js
@@ -170,7 +170,9 @@ test('a Bot busy in a group gets the message in its own chat, and the sender is
// A non-Main sender gets no stop_bot hint.
emit('ga', 'turn/start', { turn: 1 })
const back = await tool('message_bot', { to: 'Chief', message: 'done' }, 'b')
- assert.equal(back, 'Delivered to Chief. Its reply will arrive later as a new message; do not wait for it. Chief now: working in group "Ops" for less than a minute. Your message does not reach its work in group "Ops".')
+ // local: waiting-live-only. Chief messaged Writer from its own chat and Writer has not
+ // read it yet, so Chief also waits for that answer.
+ assert.equal(back, 'Delivered to Chief. Its reply will arrive later as a new message; do not wait for it. Chief now: working in group "Ops" for less than a minute; waiting for Writer to answer. Your message does not reach its work in group "Ops".')
})
test('a request steered into a running turn is recorded once and answered in a turn of its own', async (t) => {
@@ -190,7 +192,7 @@ test('a request steered into a running turn is recorded once and answered in a t
assert.equal(agents.get('a')?.calls.length ?? 0, 0)
const [kind, again] = agents.get('b').calls[1]
assert.equal(kind, 'followup')
- assert.equal(textOf(again.content), '[Message from Chief · you read it during your last task; answer it now]\nwhich year is the data?')
+ assert.equal(textOf(again.content), `[Message from Chief · you read it during your last task; answer it now]\n${HANDED_BACK}`)
assert.equal(again.source.deferred, true)
assert.equal(again.source.exchangeId, steered.source.exchangeId)
assert.deepEqual((await exchanges()).map(entry => entry.role), ['request'])
@@ -235,7 +237,7 @@ test('a user message steered into the running steps marks when it landed', async
assert.deepEqual(await steered(), {})
})
-test('a request from a name with brackets keeps its body when replayed after the current work', async (t) => {
+test('a request from a name with brackets is handed back under a well-formed header', async (t) => {
const seed = team()
seed.bots.a.name = 'R]2'
const { agents, emit, tool, stop } = await start(seed)
@@ -253,7 +255,10 @@ test('a request from a name with brackets keeps its body when replayed after the
const [kind, again] = agents.get('b').calls[1]
assert.equal(kind, 'followup')
assert.equal(again.source.exchangeId, steered.source.exchangeId)
- assert.equal(textOf(again.content), `[Message from R]2 · you read it during your last task; answer it now]\n${body}`)
+ // The bracket in the sender's name leaves the header one pair of brackets, and the
+ // hand-back points at the body it already read instead of replaying it.
+ assert.equal(textOf(again.content), `[Message from R]2 · you read it during your last task; answer it now]\n${HANDED_BACK}`)
+ assert.doesNotMatch(textOf(again.content), /Keep this line/)
})
test('a message its recipient has not read yet takes in the next one, however many come', async (t) => {
@@ -374,6 +379,8 @@ function turnsHost() {
const replySource = (role, extra = {}) => ({ kind: SOURCE_KIND, role, senderSessionId: 'a', senderName: 'Chief', exchangeId: 'x1', ...extra })
const textBlock = (content) => [{ type: 'text', text: content }]
const assistantText = text => ({ message: { content: textBlock(text) } })
+// What a hand-back carries instead of the body it already read (turns.js HANDED_BACK).
+const HANDED_BACK = 'You read its text during that task; it is above in this session. Answer it now.'
test('a stopped notice routes the acknowledgement back like a request', () => {
const { rt, emit, delivered } = turnsHost()
@@ -400,7 +407,8 @@ test('a request that joins a user-started turn is handed back, not answered with
emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmake it shorter'), source: replySource('request', { exchangeId: 'e1' }) })
emit('b', 'assistant/message', assistantText('second half'))
emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
- assert.deepEqual(delivered.map(deferredOf), [['a', 'b', 'b', 'request', 'e1', true, 'make it shorter']])
+ assert.deepEqual(delivered.map(deferredOf), [['a', 'b', 'b', 'request', 'e1', true, HANDED_BACK]])
+ assert.equal(delivered[0].handedBack, true)
assert.deepEqual(rt.state.exchangeTurns, {})
// The handed-back request opens a hidden turn whose text is the reply.
@@ -421,7 +429,7 @@ test('a request that joins a Bot-triggered turn is handed back; the trigger gets
emit('b', 'assistant/message', assistantText('second half'))
emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
assert.deepEqual(rt.state.exchangeTurns.b, [1])
- assert.deepEqual(delivered.map(job => [job.role, job.replyTo ?? job.exchangeId, job.text]), [['reply', 'e0', 'first half\n\nsecond half'], ['request', 'e1', 'more']])
+ assert.deepEqual(delivered.map(job => [job.role, job.replyTo ?? job.exchangeId, job.text]), [['reply', 'e0', 'first half\n\nsecond half'], ['request', 'e1', HANDED_BACK]])
})
test('a joined request in a stopped turn tells its sender, and is not handed back', () => {
@@ -473,7 +481,7 @@ test('a schedule-started turn stays visible when a request joins', () => {
emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmore'), source: replySource('request', { exchangeId: 'e1' }) })
emit('b', 'assistant/message', assistantText('after'))
emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
- assert.deepEqual(delivered.map(job => [job.role, job.exchangeId, job.text]), [['request', 'e1', 'more']])
+ assert.deepEqual(delivered.map(job => [job.role, job.exchangeId, job.text]), [['request', 'e1', HANDED_BACK]])
assert.deepEqual(rt.state.exchangeTurns, {})
})
@@ -518,7 +526,7 @@ test('a joined request crosses a part switch and is handed back in the new part'
assert.equal(textOf(replies[0][1].content), '[Reply from Writer]\ndone')
assert.equal(handedBack()[0], 'followup')
assert.equal(handedBack()[1].source.exchangeId, 'e1')
- assert.equal(textOf(handedBack()[1].content), '[Message from Chief · you read it during your last task; answer it now]\nmore')
+ assert.equal(textOf(handedBack()[1].content), `[Message from Chief · you read it during your last task; answer it now]\n${HANDED_BACK}`)
})
// Each Session takes up the newest message it was sent as its next turn.
@@ -575,7 +583,9 @@ test('a Bot\'s answer waits for the work it handed on, and carries what came bac
const { agents, tool, call } = team
const shown = async () => { const { value } = await call('state', {}); return [value.activity.b === 'waiting', value.work.waiting] }
const { take, end, handed } = await handedOn(team)
- assert.deepEqual(await shown(), [false, {}])
+ // local: waiting-live-only. Chief sent the work from outside any work and Writer is on
+ // it, so Chief shows a wait on Writer that holds no one else's work.
+ assert.deepEqual(await shown(), [false, { a: { bots: ['b'], rooms: [], for: [] } }])
assert.match(handed, /When you have handed on everything, end your turn: each reply brings you back to this work, and your answer goes to Chief once all of it is back\.$/)
end('b', 'handed it to Tester')
// Nothing goes up yet; Writer waits, and the team can see it.
@@ -583,19 +593,23 @@ test('a Bot\'s answer waits for the work it handed on, and carries what came bac
assert.deepEqual(Object.values(await worksIn(team)).map(work => [work.from, work.to, work.open.length, work.held]), [['a', 'b', 1, 'handed it to Tester'], ['b', 'c', 0, undefined]])
assert.deepEqual(callsOf(agents, 'a'), [])
// Its mark shows it waits, its row whom for, and the menu names the wait to give up.
- const [, waitingWork] = await shown()
+ // Chief still waits on Writer, which holds the work (local: waiting-live-only).
+ const [waitingMark, waitingWork] = await shown()
+ assert.equal(waitingMark, true)
const waits = waitingWork.b.waits
assert.equal(waits.length, 1)
assert.equal(typeof waits[0].id, 'string')
assert.deepEqual([waits[0].to, waits[0].name], ['c', 'Tester'])
delete waitingWork.b.waits
- assert.deepEqual(waitingWork, { b: { bots: ['c'], rooms: [], for: ['a'] } })
+ delete waitingWork.a.waits
+ assert.deepEqual(waitingWork, { b: { bots: ['c'], rooms: [], for: ['a'] }, a: { bots: ['b'], rooms: [], for: [] } })
take('c')
end('c', 'two things to fix')
await settled(() => callsOf(agents, 'b').length === 2)
const back = take('b')
- assert.deepEqual(await shown(), [false, {}])
+ // Writer is on it again in a turn of its own, so Chief still waits on it (local: waiting-live-only).
+ assert.deepEqual(await shown(), [false, { a: { bots: ['b'], rooms: [], for: [] } }])
assert.equal(textOf(back.content), '[Reply from Tester · for the work Chief asked you for; your answer goes to Chief once everything you handed on is back]\ntwo things to fix')
end('b', 'fixed both')
await settled(() => callsOf(agents, 'a').length === 1)
@@ -672,7 +686,7 @@ test('a result read during other work comes back in a turn of its own and goes o
await settled(() => callsOf(agents, 'b').length === 3)
const [kind, again] = callsOf(agents, 'b')[2]
assert.equal(kind, 'followup')
- assert.equal(textOf(again.content), '[Reply from Tester · you read it during your last task; go on with the work it is for now · for the work Chief [ops] asked you for; your answer goes to Chief [ops] once everything you handed on is back]\nreviewed')
+ assert.equal(textOf(again.content), `[Reply from Tester · you read it during your last task; go on with the work it is for now · for the work Chief [ops] asked you for; your answer goes to Chief [ops] once everything you handed on is back]\n${HANDED_BACK}`)
assert.deepEqual(callsOf(agents, 'a'), [])
take('b')
end('b', 'done after the review')
@@ -1048,7 +1062,7 @@ for (const id of ['b', 'gb']) {
ctx.llm.resolveModelInfo = async () => ({ context: { contextWindow: 192_000 } })
const preStep = async (agent) => {
agent.session.requestHeader = () => ({ config: { provider: 'custom', model: 'model' } })
- return ctx.listeners.get('agent/pre-step').at(-1)({ agent, messages: [], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
+ return ctx.listeners.get('agent/pre-step').find(listener => String(listener).includes('takeOverStep'))({ agent, messages: [], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
}
const overflow = agent => fire('agent/request-error', { agent, failure: { code: 'CONTEXT_WINDOW_EXCEEDED', message: 'Tools exceed the context window' }, signal: AbortSignal.timeout(60_000) })
const waitForHandoff = async (sessionId) => {
@@ -1128,7 +1142,7 @@ for (const id of ['b', 'gb']) {
assert.ok(ctx.get('tokenMeter').measure(agent.session).totalTokens + estimateTokens(textOf(input.content)) > 50_000, 'it overflows together with the handoff')
if (pending) {
- const decision = await ctx.listeners.get('agent/pre-step').at(-1)({ agent, messages: [input], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
+ const decision = await ctx.listeners.get('agent/pre-step').find(listener => String(listener).includes('takeOverStep'))({ agent, messages: [input], step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')
assert.deepEqual(decision, { kind: 'enter', messages: [] })
} else {
record('user/message', input)
diff --git a/ds-bot/test/card-gate.test.js b/ds-bot/test/card-gate.test.js
new file mode 100644
index 0000000000..c2ef3fd088
--- /dev/null
+++ b/ds-bot/test/card-gate.test.js
@@ -0,0 +1,493 @@
+import assert from 'node:assert/strict'
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { createRuntime } from '../index.js'
+import { fakeContext } from './fake-ctx.js'
+
+const TEAM = {
+ version: 1,
+ mainBotIds: ['chief'],
+ bots: {
+ chief: { id: 'chief', name: 'Chief', role: 'Lead', sessionId: 'chief', createdAt: 1 },
+ writer: { id: 'writer', name: 'Writer', role: 'Write', sessionId: 'writer', createdAt: 2 },
+ coder: { id: 'coder', name: 'Coder', role: 'Code', sessionId: 'coder', createdAt: 3 },
+ },
+ rooms: {},
+ agents: {},
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+ prefs: {},
+ revision: 0,
+}
+
+// A plan-mode service that keeps its state per Session, like ctx.planMode.
+function fakePlanMode(active = {}) {
+ const calls = []
+ return {
+ calls,
+ active,
+ get: agent => ({ active: active[agent.session.id] === true }),
+ set(agent, value) {
+ calls.push([agent.session.id, value])
+ if ((active[agent.session.id] === true) === value) return 'noop'
+ active[agent.session.id] = value
+ return 'committed'
+ },
+ }
+}
+
+// `realm: 'preset'` serves plan mode the way DSH does under an agent preset: only
+// through agentPresets.serviceFor, never from a Host-realm ctx.get('planMode').
+// `planDefault: true` keeps the start-off rule on; the relay tests turn it off so
+// they see only the relay.
+async function start({ planMode, team = TEAM, realm = 'host', planDefault = false, keep } = {}) {
+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-card-gate-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(team))
+ if (keep !== undefined) writeFileSync(join(home, 'plan-mode-keep.json'), JSON.stringify(keep))
+ const beforeDefault = process.env.DSH_PLAN_DEFAULT_OFF
+ if (!planDefault) process.env.DSH_PLAN_DEFAULT_OFF = 'off'
+ else delete process.env.DSH_PLAN_DEFAULT_OFF
+ const services = planMode === undefined ? {}
+ : realm === 'preset' ? { agentPresets: { list: async () => [], serviceFor: (_agent, name) => (name === 'planMode' ? planMode : undefined) } }
+ : { planMode }
+ const ctx = fakeContext({ services })
+ const delivered = []
+ Object.assign(ctx, {
+ workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} },
+ sessionController: {
+ create: async () => ({ sessionId: 's1' }),
+ resolveAgent: async sessionId => ({ agent: { session: { id: sessionId }, followup(message) { delivered.push([sessionId, message]) }, steer(message) { delivered.push([sessionId, message]) } } }),
+ selectModel: async () => {},
+ },
+ sessionTitle: { rename: async () => {} },
+ sessions: { flush: async () => {} },
+ })
+ const rt = createRuntime(ctx, { home })
+ let seq = 0
+ const emit = (id, type, data) => {
+ for (const listener of ctx.listeners.get('session/event') ?? []) {
+ if (listener.length >= 2) listener({ id }, { type, seq: ++seq, data })
+ }
+ }
+ const ask = (sessionId, options = [{ label: 'Lookout' }, { label: 'Scout' }]) => rt.teamTools.find(d => d.name === 'ask_user').execute(
+ { question: 'Which name?', options },
+ { agent: { id: sessionId }, callId: 'call-1', concludeTurn() {} },
+ )
+ const guard = (sessionId, name, args) => {
+ for (const each of ctx.guards) {
+ const refusal = each({ name, arguments: args, agent: { id: sessionId } })
+ if (refusal !== undefined) return refusal
+ }
+ return undefined
+ }
+ // A turn a Bot opened with a request (hidden), or one the user typed (visible).
+ const turns = {}
+ const nextTurn = (sessionId) => {
+ if (turns[sessionId] !== undefined) emit(sessionId, 'turn/end', { turn: turns[sessionId], reason: { kind: 'completed' } })
+ turns[sessionId] = (turns[sessionId] ?? 0) + 1
+ emit(sessionId, 'turn/start', { turn: turns[sessionId] })
+ }
+ const fromBot = (sessionId, sender, body, extra = {}) => {
+ nextTurn(sessionId)
+ emit(sessionId, 'user/message', { content: [{ type: 'text', text: `[Message from ${TEAM.bots[sender].name}]\n${body}` }], source: { kind: 'bot', role: 'request', senderSessionId: sender, senderName: TEAM.bots[sender].name, exchangeId: `x-${sessionId}-${turns[sessionId]}`, hop: 0, ...extra } })
+ }
+ const fromUser = (sessionId, body) => {
+ nextTurn(sessionId)
+ emit(sessionId, 'user/message', { content: [{ type: 'text', text: body }], source: { kind: 'user' } })
+ }
+ // Every line, start-up included (`all`), or only the gate's decisions.
+ const log = async ({ all = false } = {}) => {
+ const path = join(home, 'logs', 'card-gate.log')
+ for (let i = 0; i < 50 && !existsSync(path); i++) await new Promise(resolve => setTimeout(resolve, 10))
+ await new Promise(resolve => setTimeout(resolve, 20))
+ const lines = existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)) : []
+ return all ? lines : lines.filter(line => line.tool !== 'gate-loaded')
+ }
+ await rt.teamTools.find(d => d.name === 'list_bots').execute({}, { agent: { id: 'chief' } })
+ const restoreDefault = () => {
+ if (beforeDefault === undefined) delete process.env.DSH_PLAN_DEFAULT_OFF
+ else process.env.DSH_PLAN_DEFAULT_OFF = beforeDefault
+ }
+ return { rt, home, emit, ask, guard, fromBot, fromUser, log, delivered, stop: async () => { await ctx.dispose(); restoreDefault(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) } }
+}
+
+test('ask_user in a job another Bot sent is refused and names the manager', async (t) => {
+ const { rt, ask, fromBot, log, stop } = await start()
+ t.after(stop)
+ fromBot('writer', 'chief', 'Pick a name for the new Bot')
+ const reply = await ask('writer')
+ assert.match(reply, /^This job came from Chief\. Do not card Steve: end your turn with a DECISION block for Chief/)
+ assert.match(reply, /Chief cards Steve and relays his answer\.$/)
+ assert.equal(rt.state.questions.writer, undefined)
+ const [entry] = await anyLines(log)
+ assert.equal(entry.bot, 'Writer')
+ assert.equal(entry.manager, 'Chief')
+ assert.equal(entry.tool, 'ask_user')
+ assert.equal(entry.title, 'Which name?')
+ assert.ok(Date.parse(entry.time) > 0)
+})
+
+test('a Main Bot cards in a job another Bot sent', async (t) => {
+ const { rt, ask, fromBot, stop } = await start()
+ t.after(stop)
+ fromBot('chief', 'writer', 'Ask the user which name they like')
+ assert.match(await ask('chief'), /card is on screen/)
+ assert.equal(rt.state.questions.chief.question, 'Which name?')
+})
+
+test('a turn the user typed cards as before', async (t) => {
+ const { rt, ask, fromUser, stop } = await start()
+ t.after(stop)
+ fromUser('writer', 'Help me name a Bot')
+ assert.match(await ask('writer'), /card is on screen/)
+ assert.equal(rt.state.questions.writer.callId, 'call-1')
+})
+
+test('a request whose audience is the user cards as before', async (t) => {
+ const { rt, ask, fromBot, stop } = await start()
+ t.after(stop)
+ fromBot('writer', 'chief', 'Introduce yourself', { audience: 'user' })
+ assert.match(await ask('writer'), /card is on screen/)
+ assert.equal(rt.state.questions.writer.question, 'Which name?')
+})
+
+test('a production approval card in a job another Bot sent goes back to the manager', async (t) => {
+ const { rt, ask, fromBot, log, stop } = await start()
+ t.after(stop)
+ fromBot('coder', 'chief', 'Merge PR 12 when Steve approves')
+ const reply = await ask('coder', [{ label: 'deploy to production (Recommended)' }, { label: 'Hold' }])
+ assert.match(reply, /^This job came from Chief. A deploy approval never goes to Steve from here: send the deploy DECISION to Chief, naming the repo and the PR as #N./)
+ assert.match(reply, /Chief cards Steve and mints the approval; then run gh pr merge --repo alone\.$/)
+ assert.equal(rt.state.questions.coder, undefined)
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.tool, entry.allowed, entry.because, entry.label, entry.manager], ['ask_user', false, 'production-label', 'deploy to production (Recommended)', 'Chief'])
+ // CARD-IT-YOURSELF opens ordinary cards, never the production one.
+ fromBot('writer', 'chief', 'Ship it. CARD-IT-YOURSELF')
+ assert.match(await ask('writer', [{ label: 'Deploy to production' }, { label: 'Hold' }]), /^This job came from Chief. A deploy approval/)
+ assert.equal(rt.state.questions.writer, undefined)
+ // A look-alike label is an ordinary card: refused with the ordinary text.
+ fromBot('writer', 'chief', 'Ship it again')
+ assert.match(await ask('writer', [{ label: 'deploy to production now' }, { label: 'Hold' }]), /^This job came from Chief. Do not card Steve/)
+})
+
+test('the production approval card in a turn the user typed shows, and the log says why', async (t) => {
+ const { rt, ask, fromUser, log, stop } = await start()
+ t.after(stop)
+ fromUser('coder', 'Merge PR 12 when you are ready')
+ assert.match(await ask('coder', [{ label: 'deploy to production (Recommended)' }, { label: 'Hold' }]), /card is on screen/)
+ assert.ok(rt.state.questions.coder)
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.bot, entry.tool, entry.allowed, entry.because, entry.label], ['Coder', 'ask_user', true, 'not-bot-turn', 'deploy to production (Recommended)'])
+ assert.equal(entry.text, undefined)
+})
+
+test('CARD-IT-YOURSELF in the job lets the Bot card the user, and the log says so', async (t) => {
+ const { rt, ask, fromBot, log, stop } = await start()
+ t.after(stop)
+ fromBot('writer', 'chief', 'Ask the user for the name yourself. CARD-IT-YOURSELF')
+ assert.match(await ask('writer'), /card is on screen/)
+ assert.ok(rt.state.questions.writer)
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.bot, entry.manager, entry.allowed, entry.because, entry.title], ['Writer', 'Chief', true, 'card-it-yourself', 'Which name?'])
+})
+
+test('exit_plan_mode in a job another Bot sent is refused', async (t) => {
+ const { guard, fromBot, fromUser, log, stop } = await start()
+ t.after(stop)
+ fromBot('coder', 'chief', 'Build the card gate')
+ const refusal = guard('coder', 'exit_plan_mode', { plan: '# Card gate\n\nSteps' })
+ assert.match(refusal, /^This job came from Chief\. Do not open a plan review for Steve here: send the full plan to Chief as a DECISION \(Approve plan \(Recommended\) \/ Change it \/ Hold\)\./)
+ assert.match(refusal, /When Chief relays approval with PLAN-APPROVED, plan mode turns off for you\.$/)
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.title], ['Coder', 'Chief', 'exit_plan_mode', 'Card gate'])
+ // In the user's own turn, and in a Main Bot's, the review goes ahead.
+ fromUser('coder', 'Plan the card gate')
+ assert.equal(guard('coder', 'exit_plan_mode', { plan: '# Card gate' }), undefined)
+ fromBot('chief', 'coder', 'Plan it')
+ assert.equal(guard('chief', 'exit_plan_mode', { plan: '# Card gate' }), undefined)
+})
+
+test('PLAN-APPROVED from a Main Bot turns plan mode off', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, log, delivered, stop } = await start({ planMode })
+ t.after(stop)
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'Steve approved. PLAN-APPROVED. Go ahead.', role: 'request' })
+ assert.deepEqual(planMode.calls, [['coder', false]])
+ assert.equal(planMode.active.coder, false)
+ assert.equal(delivered.length, 1)
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome, entry.authority], ['Coder', 'Chief', 'plan-approved', 'committed', 'main'])
+})
+
+test('PLAN-APPROVED from a Bot that is not a Main Bot changes nothing', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, stop } = await start({ planMode })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'PLAN-APPROVED', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+ assert.equal(planMode.active.coder, true)
+ // Nor does a Main Bot message without the token, or one to a Bot not in plan mode.
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'Plan looks fine', role: 'request' })
+ await rt.deliver({ fromId: 'chief', toId: 'writer', text: 'PLAN-APPROVED', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+})
+
+test('PLAN-APPROVED from a Main Bot turns plan mode off for another Main Bot', async (t) => {
+ const planMode = fakePlanMode({ chief: true })
+ const team = { ...TEAM, mainBotIds: ['chief', 'writer'] }
+ const { rt, stop } = await start({ planMode, team })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'chief', text: 'PLAN-APPROVED job-1: go', role: 'request' })
+ assert.deepEqual(planMode.calls, [['chief', false]])
+})
+
+test('an ORDER from a Main Bot turns plan mode off', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, log, stop } = await start({ planMode })
+ t.after(stop)
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'ORDER from Chief · job j-1 · decisions come back to me\nBuild it.', role: 'request' })
+ assert.deepEqual(planMode.calls, [['coder', false]])
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome], ['Coder', 'Chief', 'order', 'committed'])
+})
+
+test('an ORDER from a Bot that is not a Main Bot changes nothing and says why', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, log, stop } = await start({ planMode })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'ORDER from Writer · job j-2 · decisions come back to me', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.tool, entry.outcome], ['order', 'sender-not-manager'])
+})
+
+test('ORDER mid-text is not an order', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, stop } = await start({ planMode })
+ t.after(stop)
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'Note the ORDER from Chief · job j-3 line below', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+})
+
+test('DSH_ORDER_RELEASE=off leaves PLAN-APPROVED working and ORDER inert', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, stop } = await start({ planMode })
+ const before = process.env.DSH_ORDER_RELEASE
+ process.env.DSH_ORDER_RELEASE = 'off'
+ t.after(async () => {
+ if (before === undefined) delete process.env.DSH_ORDER_RELEASE
+ else process.env.DSH_ORDER_RELEASE = before
+ await stop()
+ })
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'ORDER from Chief · job j-4 · decisions come back to me', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED j-4: go', role: 'request' })
+ assert.deepEqual(planMode.calls, [['coder', false]])
+})
+
+test('a release on a Bot not in plan mode is logged as not-in-plan-mode', async (t) => {
+ const planMode = fakePlanMode({})
+ const { rt, log, stop } = await start({ planMode })
+ t.after(stop)
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED j-5: go', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.tool, entry.outcome], ['plan-approved', 'not-in-plan-mode'])
+})
+
+test('the gate says it is loaded at start-up', async (t) => {
+ const { log, stop } = await start()
+ t.after(stop)
+ const lines = await log({ all: true })
+ const loaded = lines.find(line => line.tool === 'gate-loaded')
+ assert.ok(loaded, 'gate-loaded line written')
+ assert.equal(loaded.release, 'plan-approved+order')
+})
+
+test('PLAN-APPROVED does nothing when plan mode is not composed', async (t) => {
+ const { rt, delivered, stop } = await start()
+ t.after(stop)
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED', role: 'request' })
+ assert.equal(delivered.length, 1)
+})
+
+test('DSH_CARD_GATE=off turns the gate off', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, ask, guard, fromBot, stop } = await start({ planMode })
+ const before = process.env.DSH_CARD_GATE
+ process.env.DSH_CARD_GATE = 'off'
+ t.after(async () => {
+ if (before === undefined) delete process.env.DSH_CARD_GATE
+ else process.env.DSH_CARD_GATE = before
+ await stop()
+ })
+ fromBot('writer', 'chief', 'Pick a name')
+ assert.match(await ask('writer'), /card is on screen/)
+ fromBot('coder', 'chief', 'Build it')
+ assert.equal(guard('coder', 'exit_plan_mode', { plan: '# Plan' }), undefined)
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+})
+
+// --- 2026-11-03: plan mode under an agent preset, and Bots that start with it off ---
+
+// The log is written asynchronously: read it until a line appears.
+async function anyLines(log) {
+ for (let i = 0; i < 50; i++) {
+ const lines = await log()
+ if (lines.length > 0) return lines
+ }
+ return []
+}
+
+// The same, for one tool's lines.
+async function linesFor(log, tool) {
+ for (let i = 0; i < 50; i++) {
+ const lines = (await log()).filter(line => line.tool === tool)
+ if (lines.length > 0) return lines
+ }
+ return []
+}
+
+test('PLAN-APPROVED reaches plan mode inside an agent preset (no Host-realm service)', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, log, stop } = await start({ planMode, realm: 'preset' })
+ t.after(stop)
+ await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED j-6: deploy to production', role: 'request' })
+ assert.deepEqual(planMode.calls, [['coder', false]])
+ const entry = (await linesFor(log, 'plan-approved'))[0]
+ assert.equal(entry.outcome, 'committed')
+})
+
+test('a Bot Session in plan mode is switched off once on its first delivery', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' })
+ assert.deepEqual(planMode.calls, [['coder', false]])
+ // The user turns plan mode back on in that chat: it is his choice and stays.
+ planMode.active.coder = true
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'again', role: 'request' })
+ assert.deepEqual(planMode.calls, [['coder', false]])
+ assert.equal(planMode.active.coder, true)
+ const entries = (await linesFor(log, 'plan-default-off'))
+ assert.equal(entries.length, 1)
+ assert.deepEqual([entries[0].bot, entries[0].why, entries[0].outcome], ['Coder', 'delivery', 'committed'])
+ assert.equal(rt.state.planDefaultOff.coder, 'committed')
+})
+
+test('a Bot named in plan-mode-keep.json keeps plan mode', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true, keep: ['coder'] })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+ const entry = (await linesFor(log, 'plan-default-off'))[0]
+ assert.equal(entry.outcome, 'kept-bot-opt-in')
+})
+
+test('a Bot with planMode on keeps plan mode', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const team = { ...TEAM, bots: { ...TEAM.bots, coder: { ...TEAM.bots.coder, planMode: 'on' } } }
+ const { rt, stop } = await start({ planMode, team, realm: 'preset', planDefault: true })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+})
+
+test('a Session already out of plan mode is left as it is', async (t) => {
+ const planMode = fakePlanMode({})
+ const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+ const entry = (await linesFor(log, 'plan-default-off'))[0]
+ assert.equal(entry.outcome, 'already-off')
+})
+
+test('a new Bot Session DS Bot makes starts out of plan mode', async (t) => {
+ const planMode = fakePlanMode({ s1: true })
+ const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true })
+ t.after(stop)
+ const id = await rt.createSession('Fresh part')
+ assert.equal(id, 's1')
+ assert.deepEqual(planMode.calls, [['s1', false]])
+ const entry = (await linesFor(log, 'plan-default-off'))[0]
+ assert.deepEqual([entry.why, entry.outcome], ['new-session', 'committed'])
+})
+
+test('DSH_PLAN_DEFAULT_OFF=off leaves plan mode alone', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, stop } = await start({ planMode, realm: 'preset' })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+})
+
+// --- 2026-11-03: card routing to the manager (dsbot-card-routing-overlord) ---
+
+const PICK = { type: 'options', id: 'pick', options: [{ label: 'A' }, { label: 'B' }] }
+const DEPLOY = { type: 'confirm', id: 'go', confirmLabel: 'deploy to production' }
+
+const showView = (rt, sessionId, args) => rt.teamTools.find(d => d.name === 'show_view').execute(args, { agent: { id: sessionId }, callId: 'view-1', concludeTurn() {} })
+
+test('an interactive show_view in a job another Bot sent is refused like ask_user', async (t) => {
+ const { rt, fromBot, log, stop } = await start()
+ t.after(stop)
+ fromBot('writer', 'chief', 'Pick a layout')
+ assert.match(await showView(rt, 'writer', { title: 'Layout', view: PICK }), /^This job came from Chief. Do not card Steve/)
+ assert.equal(rt.state.views?.writer, undefined)
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.allowed, entry.because, entry.title], ['Writer', 'Chief', 'show_view', false, 'gated', 'Layout'])
+ // A display-only view is no card and is not gated.
+ fromBot('writer', 'chief', 'Show the numbers')
+ assert.equal(await showView(rt, 'writer', { title: 'Meter', view: { type: 'metric', label: 'Done', value: '70%' } }), 'The view is on screen.')
+})
+
+test('a show_view whose confirm is the production approval is refused even with CARD-IT-YOURSELF', async (t) => {
+ const { rt, fromBot, stop } = await start()
+ t.after(stop)
+ fromBot('coder', 'chief', 'Ask Steve yourself. CARD-IT-YOURSELF')
+ assert.match(await showView(rt, 'coder', { title: 'Ship', view: DEPLOY }), /^This job came from Chief. A deploy approval never goes to Steve from here/)
+ assert.equal(rt.state.views?.coder, undefined)
+ // An ordinary interactive view is opened by the token.
+ assert.match(await showView(rt, 'coder', { title: 'Layout', view: PICK }), /view is on screen; the user's answer/)
+ assert.ok(rt.state.views.coder)
+})
+
+test('an interactive show_view in a turn the user typed shows as before', async (t) => {
+ const { rt, fromUser, stop } = await start()
+ t.after(stop)
+ fromUser('writer', 'Show me the layouts')
+ assert.match(await showView(rt, 'writer', { title: 'Layout', view: PICK }), /view is on screen; the user's answer/)
+ assert.ok(rt.state.views.writer)
+})
+
+const ADMIN_TEAM = { ...TEAM, rooms: { seo: { id: 'seo', name: 'SEO', members: ['writer', 'coder'], mode: 'admin', admin: 'writer', named: true, sessions: {} } } }
+
+test('PLAN-APPROVED from the admin of a group the Bot is in turns plan mode off', async (t) => {
+ const planMode = fakePlanMode({ coder: true })
+ const { rt, log, stop } = await start({ planMode, team: ADMIN_TEAM })
+ t.after(stop)
+ await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'PLAN-APPROVED seo-1: go', role: 'request' })
+ assert.deepEqual(planMode.calls, [['coder', false]])
+ const [entry] = await anyLines(log)
+ assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome, entry.authority], ['Coder', 'Writer', 'plan-approved', 'committed', 'group-admin'])
+})
+
+test('a group admin cannot release a Bot outside its group, nor a plain member', async (t) => {
+ const planMode = fakePlanMode({ chief: true, writer: true })
+ const team = { ...ADMIN_TEAM, mainBotIds: ['chief'] }
+ const { rt, log, stop } = await start({ planMode, team })
+ t.after(stop)
+ // Chief is not in the SEO group: its admin is not Chief's manager.
+ await rt.deliver({ fromId: 'writer', toId: 'chief', text: 'PLAN-APPROVED x-1: go', role: 'request' })
+ // Coder is a member, not the admin: it cannot release the admin.
+ await rt.deliver({ fromId: 'coder', toId: 'writer', text: 'PLAN-APPROVED x-2: go', role: 'request' })
+ assert.deepEqual(planMode.calls, [])
+ const lines = await anyLines(log)
+ assert.deepEqual(lines.map(line => line.outcome), ['sender-not-manager', 'sender-not-manager'])
+})
diff --git a/ds-bot/test/composer-brainstorm.test.js b/ds-bot/test/composer-brainstorm.test.js
new file mode 100644
index 0000000000..5ee6138ef2
--- /dev/null
+++ b/ds-bot/test/composer-brainstorm.test.js
@@ -0,0 +1,20 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { BRAINSTORM_TEXT, canBrainstorm, insertBrainstorm } from '../src/client/brainstorm.js'
+
+test('the Brainstorm row types "brainstorm " once, at the captured caret', () => {
+ const calls = []
+ const caret = { at: 7 }
+ const inputActions = { insertText: (...args) => calls.push(args), captureInsertion: () => caret }
+ assert.equal(canBrainstorm(inputActions), true)
+ assert.equal(insertBrainstorm(inputActions), true)
+ assert.equal(BRAINSTORM_TEXT, 'brainstorm ')
+ assert.deepEqual(calls, [['brainstorm ', caret]])
+})
+
+test('a composer without insertText shows no row and nothing happens', () => {
+ assert.equal(canBrainstorm(undefined), false)
+ assert.equal(canBrainstorm({ captureInsertion: () => ({}) }), false)
+ assert.equal(insertBrainstorm(undefined), false)
+ assert.equal(insertBrainstorm({ captureInsertion: () => { throw new Error('must not be called') } }), false)
+})
diff --git a/ds-bot/test/credit-guard.test.js b/ds-bot/test/credit-guard.test.js
new file mode 100644
index 0000000000..060d305732
--- /dev/null
+++ b/ds-bot/test/credit-guard.test.js
@@ -0,0 +1,183 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { adminKeyProblem, decide, install, periodStart, settingsOf, spendOf, usageCost } from '../src/host/credit-guard.js'
+
+const MINUTE = 60_000
+const at = iso => Date.parse(iso)
+
+test('the grant period starts on the reset day, UTC', () => {
+ assert.equal(new Date(periodStart(at('2026-11-04T15:00:00Z'), 20)).toISOString(), '2026-10-20T00:00:00.000Z')
+ assert.equal(new Date(periodStart(at('2026-11-20T00:00:00Z'), 20)).toISOString(), '2026-11-20T00:00:00.000Z')
+ assert.equal(new Date(periodStart(at('2026-01-05T00:00:00Z'), 20)).toISOString(), '2025-12-20T00:00:00.000Z')
+ assert.equal(new Date(periodStart(at('2026-03-01T00:00:00Z'), 1)).toISOString(), '2026-03-01T00:00:00.000Z')
+})
+
+test('settings need a route and a fallback; the reset day defaults to 20', () => {
+ assert.equal(settingsOf({}), undefined)
+ assert.equal(settingsOf({ creditGuard: { route: 'anthropic-credit' } }), undefined)
+ const settings = settingsOf({ creditGuard: { route: 'anthropic-credit', fallback: 'kimi-coding/k3', bots: ['Igor'] } })
+ assert.equal(settings.resetDay, 20)
+ assert.equal(settings.cutAt, 190)
+ assert.equal(settingsOf({ creditGuard: { route: 'r', fallback: 'f', resetDay: 31 } }).resetDay, 20)
+})
+
+test('spend adds past cost days and the higher of today cost or priced usage', () => {
+ const now = at('2026-11-04T15:00:00Z')
+ const costPages = [{ data: [
+ { starting_at: '2026-11-02T00:00:00Z', results: [{ amount: '10000' }] },
+ { starting_at: '2026-11-03T00:00:00Z', results: [{ amount: '5000' }, { amount: '50' }] },
+ { starting_at: '2026-11-04T00:00:00Z', results: [{ amount: '100' }] },
+ ] }]
+ const usagePages = [{ data: [{ starting_at: '2026-11-04T14:00:00Z', results: [{ model: 'claude-opus-5-5', uncached_input_tokens: 1_000_000, output_tokens: 100_000 }] }] }]
+ const prices = { 'claude-opus-5-5': { input: 15, output: 75 } }
+ assert.equal(usageCost(usagePages, prices), 22.5)
+ assert.equal(spendOf({ costPages, usagePages, prices, now }), 100 + 50.5 + 22.5)
+ assert.equal(spendOf({ costPages, usagePages: [], prices, now }), 100 + 50.5 + 1)
+})
+
+test('an unknown model is priced at the dearest known rate', () => {
+ const prices = { cheap: { input: 1, output: 5 }, dear: { input: 15, output: 75 } }
+ assert.equal(usageCost([{ data: [{ results: [{ model: 'mystery', output_tokens: 1_000_000 }] }] }], prices), 75)
+})
+
+test('thresholds: warn, wait for a running turn, cut, hard, and blind', () => {
+ const settings = settingsOf({ creditGuard: { route: 'r', fallback: 'f' } })
+ const base = { blindFor: 0, settings, running: false, waitedFor: 0 }
+ assert.equal(decide({ ...base, spent: 100 }).act, 'none')
+ assert.equal(decide({ ...base, spent: 150 }).act, 'warn')
+ assert.deepEqual(decide({ ...base, spent: 190 }), { act: 'switch', reason: 'cut' })
+ assert.equal(decide({ ...base, spent: 190, running: true }).act, 'wait')
+ assert.deepEqual(decide({ ...base, spent: 190, running: true, waitedFor: 10 * MINUTE }), { act: 'switch', reason: 'cut' })
+ assert.deepEqual(decide({ ...base, spent: 195, running: true }), { act: 'switch', reason: 'hard' })
+ assert.equal(decide({ ...base, spent: undefined, blindFor: 119 * MINUTE }).act, 'none')
+ assert.deepEqual(decide({ ...base, spent: undefined, blindFor: 120 * MINUTE }), { act: 'switch', reason: 'blind' })
+})
+
+test('a missing Admin key and a wrong one are told apart', () => {
+ assert.equal(adminKeyProblem(undefined), 'no-key')
+ assert.equal(adminKeyProblem(''), 'no-key')
+ assert.equal(adminKeyProblem('x'.repeat(63)), 'bad-key')
+ assert.equal(adminKeyProblem('sk-ant-admin01-abc'), undefined)
+})
+
+// A runtime with only what the guard calls, and an Admin API that answers `cents`.
+function harness({ cents, key = 'sk-ant-admin01-test', status = 200, running = false, clock }) {
+ const home = mkdtempSync(join(tmpdir(), 'credit-guard-'))
+ const bot = { id: 'b1', name: 'Pilot', model: 'anthropic-credit/claude-opus-5-5' }
+ const delivered = []
+ const listeners = []
+ const effects = []
+ const requests = []
+ const rt = {
+ home,
+ config: {
+ creditGuard: {
+ route: 'anthropic-credit', fallback: 'kimi-coding/k3', bots: ['Pilot'], adminKey: 'TEST_ADMIN_KEY', baseUrl: 'http://admin.test',
+ now: () => clock.now,
+ fetch: async (url, init) => {
+ requests.push({ url: String(url), key: init.headers['x-api-key'] })
+ if (status !== 200) return { ok: false, status, json: async () => ({}) }
+ const isCost = String(url).includes('cost_report')
+ return { ok: true, status: 200, json: async () => ({ data: isCost ? [{ starting_at: '2026-11-01T00:00:00Z', results: [{ amount: String(cents.value) }] }] : [], has_more: false }) }
+ },
+ },
+ },
+ ctx: { on: (name, fn) => listeners.push([name, fn]), effect: fn => effects.push(fn) },
+ secretValue: name => (name === 'TEST_ADMIN_KEY' ? key : undefined),
+ findBot: ref => (ref === 'Pilot' || ref === 'b1' ? bot : undefined),
+ botOf: id => (id === 'b1' ? bot : undefined),
+ chatOf: () => 's1',
+ groupSessionsOf: () => [],
+ chatOwners: new Map([['s1', 'b1']]),
+ groupOwners: new Map(),
+ live: new Map(running ? [['s1', { turn: {} }]] : []),
+ updateBot: async (id, patch) => { bot.model = patch.model; return bot },
+ deliver: async message => { delivered.push(message) },
+ warn: () => {},
+ }
+ install(rt)
+ return { rt, bot, delivered, listeners, requests, home, log: () => readFileSync(join(home, 'logs', 'credit-guard.log'), 'utf8'), done: () => rmSync(home, { recursive: true, force: true }) }
+}
+
+test('at the cutoff the Bot moves to the fallback and is told', async () => {
+ const clock = { now: at('2026-11-04T15:00:00Z') }
+ const h = harness({ cents: { value: 19_050 }, clock })
+ try {
+ await h.rt.creditGuardCheck()
+ assert.equal(h.bot.model, 'kimi-coding/k3')
+ assert.equal(h.delivered.length, 1)
+ assert.match(h.delivered[0].text, /^\[Credit guard\] I moved you from anthropic-credit\/claude-opus-5-5 to kimi-coding\/k3 because \$190\.50 of the \$200\.00/)
+ assert.ok(h.requests.every(request => request.url.startsWith('http://admin.test/v1/organizations/')))
+ assert.ok(h.requests[0].url.includes('starting_at=2026-10-20T00%3A00%3A00.000Z'))
+ assert.ok(!h.log().includes('sk-ant-admin'))
+ assert.match(h.log(), /"event":"switch".*"ok":true/)
+ } finally { h.done() }
+})
+
+test('a warning goes out once per period', async () => {
+ const clock = { now: at('2026-11-04T15:00:00Z') }
+ const h = harness({ cents: { value: 15_500 }, clock })
+ try {
+ await h.rt.creditGuardCheck()
+ await h.rt.creditGuardCheck()
+ assert.equal(h.bot.model, 'anthropic-credit/claude-opus-5-5')
+ assert.equal(h.delivered.length, 1)
+ assert.match(h.delivered[0].text, /\$155\.00 of the \$200\.00 credit/)
+ } finally { h.done() }
+})
+
+test('a running turn holds the cutoff for up to 10 minutes, the hard line does not wait', async () => {
+ const clock = { now: at('2026-11-04T15:00:00Z') }
+ const cents = { value: 19_100 }
+ const h = harness({ cents, running: true, clock })
+ try {
+ await h.rt.creditGuardCheck()
+ assert.equal(h.bot.model, 'anthropic-credit/claude-opus-5-5')
+ clock.now += 10 * MINUTE
+ await h.rt.creditGuardCheck()
+ assert.equal(h.bot.model, 'kimi-coding/k3')
+ } finally { h.done() }
+ const clock2 = { now: at('2026-11-04T15:00:00Z') }
+ const h2 = harness({ cents: { value: 19_600 }, running: true, clock: clock2 })
+ try {
+ await h2.rt.creditGuardCheck()
+ assert.equal(h2.bot.model, 'kimi-coding/k3')
+ } finally { h2.done() }
+})
+
+test('a missing or rejected Admin key is logged as such, and fails closed after 2 hours', async () => {
+ for (const [options, problem] of [[{ key: null }, 'no-key'], [{ key: 'x'.repeat(63) }, 'bad-key'], [{ status: 401 }, 'bad-key'], [{ status: 503 }, 'error']]) {
+ const clock = { now: at('2026-11-04T15:00:00Z') }
+ const h = harness({ cents: { value: 0 }, clock, ...options })
+ try {
+ await h.rt.creditGuardCheck()
+ assert.equal(h.bot.model, 'anthropic-credit/claude-opus-5-5')
+ assert.match(h.log(), new RegExp(`"event":"blind","problem":"${problem}"`))
+ clock.now += 2 * 60 * MINUTE
+ await h.rt.creditGuardCheck()
+ assert.equal(h.bot.model, 'kimi-coding/k3', problem)
+ assert.match(h.delivered.at(-1).text, /no reading for over 2 hours/)
+ } finally { h.done() }
+ }
+})
+
+test('a low-credit refusal switches the Bot at once', async () => {
+ const clock = { now: at('2026-11-04T15:00:00Z') }
+ const h = harness({ cents: { value: 0 }, clock })
+ try {
+ const [, onEvent] = h.listeners.find(([name]) => name === 'session/event')
+ onEvent({ id: 's1' }, { type: 'turn/end', data: { reason: { kind: 'error', error: { message: 'Your credit balance is too low to access the Anthropic API.' } } } })
+ await h.rt.creditGuardCheck()
+ assert.equal(h.bot.model, 'kimi-coding/k3')
+ assert.match(h.delivered[0].text, /refused a request for low credit/)
+ } finally { h.done() }
+})
+
+test('without config the guard stays off', () => {
+ const rt = { config: {}, ctx: {} }
+ install(rt)
+ assert.deepEqual(rt.creditGuardView(), { enabled: false })
+})
diff --git a/ds-bot/test/group-work.test.js b/ds-bot/test/group-work.test.js
index 12c885f7b9..a77351b93f 100644
--- a/ds-bot/test/group-work.test.js
+++ b/ds-bot/test/group-work.test.js
@@ -353,7 +353,10 @@ test('replies a post waits for are work handed on: the answer to the Bot that as
host.finish('a', '已经让 Writer 去看了。')
const waiting = (await host.call('state', {})).value
assert.equal(waiting.activity.a, 'waiting')
+ // local: waiting-live-only. Tester sent Chief the request from its own chat, so Tester
+ // waits on Chief while Chief waits on the group.
assert.deepEqual([waiting.work.waiting.a.bots, waiting.work.waiting.a.rooms, waiting.work.waiting.a.for], [[], ['r1'], ['c']])
+ assert.deepEqual([waiting.work.waiting.c.bots, waiting.work.waiting.c.rooms, waiting.work.waiting.c.for], [['a'], [], []])
// The menu gives up the wait by its group's name.
assert.deepEqual(waiting.work.waiting.a.waits.map(item => [item.room, item.name, typeof item.id]), [['r1', 'Ops', 'string']])
const done = host.round('c1', host.takePost())
@@ -465,7 +468,10 @@ test('a steered group call keeps the later caller when the earlier work ends', a
assert.equal(deferred.source.role, 'room')
assert.equal(deferred.source.askedBy, 'a')
assert.equal(deferred.source.roomId, 'r1')
- assert.match(text(deferred), /改用新模板/)
+ // The later call is the one handed back, and it points at what the member already read.
+ assert.equal(deferred.source.exchangeId, correction.source.exchangeId)
+ assert.match(text(deferred), /you read this call during your last task; answer it now/)
+ assert.doesNotMatch(text(deferred), /改用新模板/)
host.finish('gb', '已换成新模板。')
await settle(() => host.agentOf('r1').calls.some(message => message.source.askedBy === 'a'))
const report = host.agentOf('r1').calls.find(message => message.source.askedBy === 'a')
diff --git a/ds-bot/test/handback.test.js b/ds-bot/test/handback.test.js
new file mode 100644
index 0000000000..b147f9b2a1
--- /dev/null
+++ b/ds-bot/test/handback.test.js
@@ -0,0 +1,230 @@
+// A message a Bot already read mid-turn is handed back to answer in a turn of its
+// own. The body is already in that Session above, so the hand-back carries a pointer
+// to it instead of the whole text again; otherwise the model reads one message twice.
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+import { test } from 'node:test'
+import { createRuntime } from '../index.js'
+import { fakeContext } from './fake-ctx.js'
+import { install as installTurns } from '../src/host/turns.js'
+import { SOURCE_KIND } from '../src/host/constants.js'
+
+// The line a hand-back carries in place of the body, which is above it in the same Session.
+const HANDED_BACK = 'You read its text during that task; it is above in this session. Answer it now.'
+
+// A turn host that records what turns.js asks delivery to do, without delivering it.
+function turnHost({ workOf } = {}) {
+ let listener
+ const delivered = []
+ const rt = {
+ ctx: { on: (name, fn) => { if (name === 'session/event') listener = fn } },
+ state: { exchangeTurns: {}, questions: {} },
+ bots: { a: { id: 'a', name: 'Chief' }, b: { id: 'b', name: 'Writer' } },
+ isBotSession: () => true,
+ roomOf: () => undefined,
+ groupOwners: new Map(),
+ chatOwners: new Map(),
+ botOf: id => rt.bots[id],
+ selfOf: id => id,
+ save: async () => {},
+ deliver: async (args) => { delivered.push(args) },
+ noteFailure() {},
+ warn() {},
+ switchJobs: () => [],
+ dropKickoff() {},
+ ...(workOf === undefined ? {} : { workOf }),
+ }
+ installTurns(rt)
+ let seq = 0
+ const emit = (id, type, data) => listener({ id }, { type, seq: ++seq, data })
+ return { rt, emit, delivered }
+}
+
+const relaySource = (role, extra = {}) => ({
+ kind: SOURCE_KIND, form: 'relay', role, senderSessionId: 'a', senderName: 'Chief', exchangeId: 'x1', ...extra,
+})
+const textBlock = content => [{ type: 'text', text: content }]
+const assistantText = text => ({ message: { content: textBlock(text) } })
+const textOf = content => content.map(block => block.text ?? '').join('\n')
+// The deferred deliveries: the hand-backs this change is about.
+const handBacks = delivered => delivered.filter(job => job.deferred === true)
+
+test('a joined request is handed back as a pointer, not the body again', () => {
+ const { emit, delivered } = turnHost()
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('write the letter'), source: { kind: 'user' } })
+ emit('b', 'assistant/message', assistantText('first half'))
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\nmake it shorter'), source: relaySource('request', { exchangeId: 'e1' }) })
+ emit('b', 'assistant/message', assistantText('second half'))
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+
+ const [handBack] = handBacks(delivered)
+ assert.equal(handBacks(delivered).length, 1)
+ // Everything about the hand-back is as it was; only the text is not the body.
+ assert.equal(handBack.fromId, 'a')
+ assert.equal(handBack.toId, 'b')
+ assert.equal(handBack.sessionId, 'b')
+ assert.equal(handBack.role, 'request')
+ assert.equal(handBack.exchangeId, 'e1')
+ assert.equal(handBack.text, HANDED_BACK)
+ assert.equal(handBack.handedBack, true)
+ assert.doesNotMatch(handBack.text, /make it shorter/)
+})
+
+test('a reply handed back for other work is a pointer too', () => {
+ const { emit, delivered } = turnHost({ workOf: source => source?.work })
+ // The turn answers the work Chief asked for under w1; the reply below belongs to w2.
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('[Message from Chief]\ntask'), source: relaySource('request', { exchangeId: 'e0', work: 'w1' }) })
+ emit('b', 'assistant/message', assistantText('worked on w1'))
+ emit('b', 'user/message', { content: textBlock('[Reply from Chief]\nreviewed'), source: relaySource('reply', { exchangeId: 'e1', work: 'w2', replyTo: 'r0' }) })
+ emit('b', 'assistant/message', assistantText('still on w1'))
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+
+ const [handBack] = handBacks(delivered)
+ assert.equal(handBack.role, 'reply')
+ assert.equal(handBack.exchangeId, 'e1')
+ assert.equal(handBack.replyTo, 'r0')
+ assert.equal(handBack.work, 'w2')
+ assert.equal(handBack.text, HANDED_BACK)
+ assert.equal(handBack.handedBack, true)
+ assert.doesNotMatch(handBack.text, /reviewed/)
+})
+
+// The rest runs the real relay, so the assertions are on the message the model is given.
+
+// A two-Bot team: a is Chief, b is Writer.
+function team() {
+ return {
+ version: 1,
+ mainBotIds: ['a'],
+ bots: {
+ a: { id: 'a', name: 'Chief', role: 'Boss', sessionId: 'a', createdAt: 1 },
+ b: { id: 'b', name: 'Writer', role: 'Write', sessionId: 'b', createdAt: 2 },
+ },
+ rooms: {},
+ agents: {},
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+ prefs: {},
+ revision: 0,
+ }
+}
+
+// Services for a full apply(): resolveAgent returns a per-Session agent that records
+// followup/steer calls, so the test sees what the model is actually handed.
+async function start(seed) {
+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-handback-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(seed))
+ const ctx = fakeContext()
+ const agents = new Map()
+ const agentOf = (sessionId) => {
+ if (!agents.has(sessionId)) {
+ const calls = []
+ agents.set(sessionId, {
+ session: { id: sessionId, requestHeader: () => undefined },
+ id: sessionId,
+ calls,
+ status: 'idle',
+ followup(message) { calls.push(['followup', message]) },
+ steer(message) { calls.push(['steer', message]) },
+ inject(message) { calls.push(['inject', message]) },
+ cancel(cause) { calls.push(['cancel', cause]) },
+ async whenIdle() {},
+ async runMaintenance(fn) { return fn(AbortSignal.timeout(60_000)) },
+ inbox: {
+ nextStep: [],
+ nextTurn: [],
+ remove(id) {
+ for (const list of [this.nextStep, this.nextTurn]) {
+ const at = list.findIndex(message => message.id === id)
+ if (at !== -1) return list.splice(at, 1).length === 1
+ }
+ return false
+ },
+ },
+ })
+ }
+ return agents.get(sessionId)
+ }
+ Object.assign(ctx, {
+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },
+ workspaceRegistry: {
+ get: () => undefined,
+ resolveByPath: async () => undefined,
+ create: async path => ({ id: 'w1', path }),
+ archiveSession: async () => {},
+ },
+ sessionController: {
+ create: async () => ({ sessionId: 's1' }),
+ resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }),
+ selectModel: async () => {},
+ page: async () => ({ records: [], hasMore: false }),
+ },
+ sessionTitle: { rename: async () => {} },
+ sessions: { flush: async () => {} },
+ })
+ // 0.2.7 scopes the team tools to Bot Sessions, so they are read off the runtime.
+ const rt = createRuntime(ctx, { home })
+ let seq = 0
+ const emit = (id, type, data, extra) => {
+ for (const listener of ctx.listeners.get('session/event') ?? []) {
+ if (listener.length >= 2) listener({ id }, { type, seq: ++seq, data, ...extra })
+ }
+ }
+ const tool = (name, args, sessionId) => rt.teamTools.find(definition => definition.name === name).execute(args, { agent: { id: sessionId } })
+ const stop = async () => {
+ await ctx.dispose()
+ rmSync(home, { recursive: true, force: true, maxRetries: 5 })
+ }
+ // Loading once fills the Session-owner indexes turns.js filters events by.
+ await tool('list_bots', {}, 'a')
+ return { ctx, agents, emit, tool, home, stop }
+}
+
+test('one message reaches the model once: steered with its body, then handed back as a pointer', async (t) => {
+ const { agents, emit, tool, stop } = await start(team())
+ t.after(stop)
+
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('write the letter'), source: { kind: 'user' } })
+ await tool('message_bot', { to: 'Writer', message: 'which year is the data?' }, 'a')
+
+ // What the running turn was shown, cut in at its next step.
+ const steered = agents.get('b').calls[0][1]
+ assert.ok(steered, 'the running turn was steered')
+ assert.match(textOf(steered.content), /which year is the data\?/)
+ emit('b', 'user/message', { content: steered.content, source: steered.source })
+ emit('b', 'assistant/message', assistantText('the letter, for the user'))
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+ for (let count = 0; count < 200 && agents.get('b').calls.length < 2; count += 1) await delay(5)
+
+ // It is still handed back, so the sender still gets its answer.
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer', 'followup'])
+ const [, handBack] = agents.get('b').calls[1]
+ assert.equal(handBack.source.exchangeId, steered.source.exchangeId)
+ assert.equal(handBack.source.deferred, true)
+ assert.equal(handBack.source.handedBack, true)
+ // The body is in the steer and not in the hand-back: the model reads it once.
+ assert.doesNotMatch(textOf(handBack.content), /which year is the data\?/)
+ assert.match(textOf(handBack.content), /it is above in this session/)
+ const shown = [steered, handBack].filter(message => textOf(message.content).includes('which year is the data?'))
+ assert.equal(shown.length, 1)
+})
+
+test('a message that arrives while the Bot is idle keeps its whole body', async (t) => {
+ const { agents, tool, stop } = await start(team())
+ t.after(stop)
+
+ await tool('message_bot', { to: 'Writer', message: 'how are you' }, 'a')
+ assert.deepEqual(agents.get('b').calls.map(([kind]) => kind), ['steer'])
+ const [, only] = agents.get('b').calls[0]
+ // Nothing was read before it, so nothing is handed back: no pointer, no flag.
+ assert.equal(textOf(only.content), '[Message from Chief]\nhow are you')
+ assert.equal(only.source.handedBack, undefined)
+ assert.equal(only.source.deferred, undefined)
+})
diff --git a/ds-bot/test/handoff-results.test.js b/ds-bot/test/handoff-results.test.js
index 9ec4072a1a..e0cce62c96 100644
--- a/ds-bot/test/handoff-results.test.js
+++ b/ds-bot/test/handoff-results.test.js
@@ -583,3 +583,83 @@ test('a continued subagent hands up each run\'s own result', async (t) => {
assert.ok(answer.includes('SCHEDULE: Monday'), `the second run's result goes up: ${answer}`)
assert.ok(answer.indexOf('COST: 42') < answer.indexOf('SCHEDULE: Monday'), `in run order: ${answer}`)
})
+
+// The label a Bot shows other Bots, over a hand-off it is done with. A work whose reply
+// came back another way kept its open id, so the asker looked loaded for days.
+function statusBench(t) {
+ const { home } = bench(t)
+ const names = { a: { name: 'Chief' }, b: { name: 'Writer' }, c: { name: 'Tester' } }
+ const rt = {
+ home,
+ state: { works: {} },
+ botOf: id => names[id],
+ readOnly: () => undefined,
+ warn() {},
+ save: async () => {},
+ chatOf: id => id,
+ groupSessionsOf: () => [],
+ roomOf: () => undefined,
+ groupOwners: new Map(),
+ live: new Map(),
+ approvalsView: () => [],
+ switchJobs: () => [],
+ unreadOf: () => [],
+ }
+ installHandoffs(rt)
+ return rt
+}
+
+test('a work whose reply already arrived does not show as waiting', async (t) => {
+ const rt = statusBench(t)
+ rt.openWork('parent', { from: 'a', to: 'b' })
+ rt.openWork('child', { from: 'b', to: 'c', parent: 'parent' })
+ // The reply is on the work, but its open id was never taken.
+ rt.state.works.parent.results = [{ id: 'child', name: 'Tester', text: 'done', length: 4 }]
+ // The Bot it went to is running a turn, so nothing else hides the wait.
+ rt.live.set('c', { turn: {} })
+ const line = rt.statusOf('b')
+ assert.doesNotMatch(line, /to hand back work/, `an answered work is not waited on: ${line}`)
+ assert.match(line, /whose results came back/, `it says the results are back: ${line}`)
+})
+
+test('a work past the ceiling with no result stops showing as waiting', async (t) => {
+ const rt = statusBench(t)
+ rt.openWork('parent', { from: 'a', to: 'b' })
+ rt.openWork('child', { from: 'b', to: 'c', parent: 'parent' })
+ rt.state.works.parent.at = Date.now() - 25 * 60 * 60 * 1000
+ rt.live.set('c', { turn: {} })
+ const line = rt.statusOf('b')
+ assert.doesNotMatch(line, /to hand back work/, `a work past the ceiling is not waited on: ${line}`)
+})
+
+test('a fresh work with no reply still shows as waiting', async (t) => {
+ const rt = statusBench(t)
+ rt.openWork('parent', { from: 'a', to: 'b' })
+ rt.openWork('child', { from: 'b', to: 'c', parent: 'parent' })
+ rt.live.set('c', { turn: {} })
+ const line = rt.statusOf('b')
+ assert.match(line, /waiting for Tester to hand back work/, `a real wait is still named: ${line}`)
+})
+
+test('a handoff reads closed as soon as its reply arrives', async (t) => {
+ const rt = statusBench(t)
+ rt.openWork('parent', { from: 'a', to: 'b' })
+ rt.openWork('child', { from: 'b', to: 'c', parent: 'parent' })
+ assert.deepEqual(rt.state.works.parent.open, ['child'], 'the hand-off starts open')
+ // Writing the reply is what tells the work it is answered.
+ rt.closeWork('child', 'Tester', 'done')
+ const parent = rt.state.works.parent
+ assert.deepEqual(parent.open, [], 'the work reads closed when the reply arrives')
+ assert.equal(parent.results.length, 1, 'the reply is attached to the work')
+ assert.equal(parent.results[0].id, 'child', 'the attached reply is the one that answered')
+})
+
+test('an old ask with no answer stops labelling its sender as waiting', async (t) => {
+ const rt = statusBench(t)
+ // Asked on its own, with no work above it: the case the status line showed.
+ rt.openWork('ask', { from: 'a', to: 'b' })
+ rt.live.set('b', { turn: {} })
+ assert.ok(rt.waitingView().a !== undefined, 'a fresh ask marks its sender waiting')
+ rt.state.works.ask.at = Date.now() - 25 * 60 * 60 * 1000
+ assert.equal(rt.waitingView().a, undefined, 'an old ask stops marking its sender waiting')
+})
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index 9b7815b30d..baf83d8311 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -79,6 +79,9 @@ test('apply registers listeners and effects in a fixed order', (t) => {
'on agent/created',
'effect ds-bot: wake parts that wait for their run mode',
'on agent/pre-step (prepend)',
+ // local: the step-failure recorder (parts.js, 2026-11-05) wraps the chain, so
+ // it registers after the parts listener and prepends ahead of it.
+ 'on agent/pre-step (prepend)',
'on system-prompt/assemble (prepend)',
'on agent/request-error (prepend)',
'on agent/request-error (prepend)',
diff --git a/ds-bot/test/local-agents.test.js b/ds-bot/test/local-agents.test.js
index fd73bd9194..ee17fe4cad 100644
--- a/ds-bot/test/local-agents.test.js
+++ b/ds-bot/test/local-agents.test.js
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'
-import { mkdirSync, mkdtempSync, readFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -591,6 +591,45 @@ test('claude: print mode asks DS Bot for permission and lets team tools through'
assert.equal(args[args.indexOf('--allowedTools') + 1], 'mcp__dsbot')
})
+// Windows allows 32,767 characters for a whole command line. Under the inline
+// flag a Bot with a large instruction set never starts, so the prompt travels in
+// a file and only its path may be an argument.
+test('claude: a system prompt larger than the Windows command-line limit starts the session', async (t) => {
+ const adapter = makeAdapter()
+ t.after(() => adapter.dispose())
+ const big = 'x'.repeat(40_000)
+ const out = await collect(adapter.stream(options('s1', [system('m1', big), user('m2', 'hello')], { provider: 'local-claude-code' })))
+ assert.equal(out.finish.kind, 'stop')
+ const args = adapter.engines.get('local-claude-code').sessions.get('s1').child.spawnargs
+ assert.ok(args.includes('--append-system-prompt-file'))
+ assert.ok(!args.includes('--append-system-prompt'))
+ assert.equal(readFileSync(args[args.indexOf('--append-system-prompt-file') + 1], 'utf8'), big)
+})
+
+// The file outlives the turn but not the session: a killed process must leave
+// nothing behind in the temp folder.
+test('claude: the temp system-prompt file is gone once the session is killed', async (t) => {
+ const adapter = makeAdapter()
+ t.after(() => adapter.dispose())
+ await collect(adapter.stream(options('s1', [system('m1', 'a short prompt'), user('m2', 'hello')], { provider: 'local-claude-code' })))
+ const session = adapter.engines.get('local-claude-code').sessions.get('s1')
+ const file = session.child.spawnargs[session.child.spawnargs.indexOf('--append-system-prompt-file') + 1]
+ assert.equal(existsSync(file), true)
+ session.kill()
+ assert.equal(existsSync(file), false)
+})
+
+// An argument that grows the same way fails with a message naming the flag,
+// instead of Windows' bare "spawn ENAMETOOLONG" which names nothing.
+test('claude: an over-cap command line fails with a typed error naming the flag', async (t) => {
+ const adapter = makeAdapter({ claudeArgs: ['--oversized', 'x'.repeat(40_000)] })
+ t.after(() => adapter.dispose())
+ await assert.rejects(
+ collect(adapter.stream(options('s1', [user('m1', 'hello')], { provider: 'local-claude-code' }))),
+ error => error.code === 'LOCAL_AGENT_EXIT' && /command line is \d+ characters and Windows allows 30000/u.test(error.message) && /--oversized/u.test(error.message),
+ )
+})
+
// A CLI that exits before init leaves a dead bridge: the retry must start a
// new process instead of writing into the one that is gone.
test('claude: a retry after a pre-init exit starts a new CLI', async (t) => {
diff --git a/ds-bot/test/operator-tasks.test.js b/ds-bot/test/operator-tasks.test.js
new file mode 100644
index 0000000000..ea0d61ac72
--- /dev/null
+++ b/ds-bot/test/operator-tasks.test.js
@@ -0,0 +1,387 @@
+import { test } from 'node:test'
+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 { install as installHandoffs } from '../src/host/handoffs.js'
+import { SOURCE_KIND } from '../src/host/constants.js'
+
+const line = record => JSON.stringify(record)
+
+test('openDecisions keeps the newest record per id and only open decisions', () => {
+ const text = [
+ line({ id: 'LE-1', ts: '2026-11-01T09:00:00', owner: 'Igor', kind: 'decision', text: 'Pick a vendor', state: 'open' }),
+ line({ id: 'LE-1', ts: '2026-11-02T09:00:00', owner: 'Igor', kind: 'decision', text: 'Pick a vendor', state: 'open', carded_at: '2026-11-02T09:00:00', due: '2026-11-10' }),
+ line({ id: 'LE-2', ts: '2026-11-01T09:00:00', owner: 'Igor', kind: 'decision', text: 'Done already', state: 'open' }),
+ line({ id: 'LE-2', ts: '2026-11-03T09:00:00', owner: 'Igor', kind: 'decision', text: 'Done already', state: 'closed' }),
+ line({ id: 'LE-3', ts: '2026-11-01T09:00:00', owner: 'Igor', kind: 'handed', text: 'Not the operator\'s', state: 'open' }),
+ line({ id: 'LE-4', ts: '2026-11-01T09:00:00', owner: 'Igor', kind: 'decision', text: 'Decided, not yet run', state: 'decided' }),
+ 'not json',
+ '',
+ ].join('\n')
+ const decisions = openDecisions(text)
+ assert.equal(decisions.length, 1)
+ assert.equal(decisions[0].id, 'LE-1')
+ assert.equal(decisions[0].carded, true)
+ assert.equal(decisions[0].due, '2026-11-10')
+ // Opened when the first record was written, not when it was last touched.
+ assert.equal(decisions[0].at, Date.parse('2026-11-01T09:00:00'))
+})
+
+function fakeRuntime({ looseEnds, state = {}, work = {}, waiting = {}, approvals = [] }) {
+ const rt = {
+ config: { looseEnds },
+ state: {
+ bots: { chief: { id: 'chief', name: 'Igor' }, coder: { id: 'coder', name: 'Harness Code' } },
+ questions: {}, views: {}, secretRequests: {}, works: {}, ...state,
+ },
+ chatOwners: new Map([['chief-chat', 'chief'], ['coder-chat', 'coder']]),
+ groupOwners: new Map([['coder-in-room', { botId: 'coder', roomId: 'room-1' }]]),
+ workView: () => work,
+ waitingView: () => waiting,
+ approvalsView: () => approvals,
+ }
+ install(rt)
+ return rt
+}
+
+test('operatorTasksView sorts each source onto the right Bot and list', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ds-bot-optasks-'))
+ try {
+ const register = join(dir, 'register.jsonl')
+ writeFileSync(register, [
+ line({ id: 'LE-9', ts: '2026-11-01T09:00:00', owner: 'Igor', kind: 'decision', text: 'Approve the plan', state: 'open' }),
+ line({ id: 'LE-10', ts: '2026-11-01T09:00:00', owner: 'Nobody Here', kind: 'decision', text: 'No such Bot', state: 'open' }),
+ ].join('\n'))
+ const rt = fakeRuntime({
+ looseEnds: register,
+ state: {
+ questions: { 'chief-chat': { id: 'q1', question: 'Which option?', askedAt: 10 }, 'coder-in-room': { id: 'q2', question: 'Merge now?', askedAt: 20 } },
+ views: { 'coder-chat': { id: 'v1', title: 'Pick a theme', askedAt: 30 } },
+ secretRequests: { coder: [{ id: 's1', name: 'GITHUB_TOKEN', purpose: 'push', status: 'pending', askedAt: 5 }, { id: 's2', name: 'OLD', status: 'saved', askedAt: 1 }] },
+ works: {
+ w1: { from: 'chief', to: 'coder', open: [], results: [], at: 100 },
+ w2: { from: 'coder', room: 'room-1', open: [], results: [], at: 110 },
+ w3: { from: 'coder', to: 'coder', open: [], results: [], at: 120 },
+ },
+ },
+ work: { coder: { since: 200, tool: 'pwsh', target: 'index.js' } },
+ waiting: { chief: { bots: ['coder'], rooms: [], for: [] } },
+ approvals: [{ id: 'a1', botId: 'chief', sessionId: 'chief-chat', tool: 'Write', reason: 'outside the grant', at: 40 }],
+ })
+ const view = rt.operatorTasksView()
+
+ assert.deepEqual(view.chief.unresolved.map(item => item.kind), ['question', 'approval', 'decision'])
+ assert.equal(view.chief.unresolved.find(item => item.kind === 'decision').id, 'LE-9')
+ assert.deepEqual(view.coder.unresolved.map(item => item.key), ['key:s1', 'question:q2', 'view:v1'])
+ 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'])
+
+ // A decision owned by a name no Bot has shows on no Bot.
+ const all = Object.values(view).flatMap(entry => entry.unresolved)
+ assert.equal(all.some(item => item.id === 'LE-10'), false)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+})
+
+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 },
+ home: mkdtempSync(join(tmpdir(), 'ds-bot-optasks-host-')),
+ 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)
+ installHandoffs(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')
+ // The card shows the message body: the relay header line is not part of the ask.
+ assert.equal(rt.operatorTasksView().b.operator[0].text, 'run the checks')
+ 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')
+})
+
+// A job handed on carries the operator's ask on its work record, outliving the turn that
+// took it, so the Bot that picks it up shows what the operator actually asked for.
+test('a job handed on keeps the operator ask, and the turn taking it shows that ask', () => {
+ const { rt, emit } = turnHost()
+ emit('b', 'turn/start', { turn: 1 })
+ emit('b', 'user/message', { content: textBlock('Fix the sidebar card'), source: { kind: 'user' } })
+ rt.openWork('w1', { from: 'b', to: 'chief' })
+ assert.equal(rt.state.works.w1.origin, 'operator')
+ assert.equal(rt.state.works.w1.ask, 'Fix the sidebar card')
+ emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+
+ // The next turn works on that job: the card keeps the ask, not the hand-on message.
+ emit('b', 'turn/start', { turn: 2 })
+ emit('b', 'user/message', {
+ content: textBlock('[Message from Igor]\nplease pick this up'),
+ source: { kind: SOURCE_KIND, form: 'relay', role: 'reply', senderName: 'Igor', exchangeId: 'e9', work: 'w1' },
+ })
+ assert.equal(rt.workView().b.origin, 'operator')
+ assert.equal(rt.operatorTasksView().b.operator[0].text, 'Fix the sidebar card')
+})
+
+// The card keeps the operator's first line; a step the Bot took is not the ask.
+test('the ask is the first line of the operator text, and the Bot\'s own words are not it', () => {
+ const rt = fakeRuntime({
+ looseEnds: false,
+ work: {
+ coder: { since: 100, tool: 'read', target: 'design_fidelity.py', origin: 'operator', ask: 'Fix the sidebar card\nand show the step below it' },
+ chief: { since: 110, tool: 'read', target: 'notes.md', origin: 'operator', said: 'Reading the notes' },
+ },
+ })
+ const view = rt.operatorTasksView()
+ assert.equal(view.coder.operator[0].text, 'Fix the sidebar card')
+ assert.equal(view.coder.operator[0].tool, 'read')
+ // Nothing of the Bot's own step stands in for an ask that was not recorded.
+ assert.equal(view.chief.operator[0].text, undefined)
+})
+
+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()
+ assert.deepEqual(view.chief.unresolved.map(item => item.kind), ['question'])
+ assert.equal(view.coder, undefined)
+})
+
+test('looseEnds false reads no register at all', () => {
+ const rt = fakeRuntime({ looseEnds: false })
+ assert.deepEqual(rt.operatorTasksView(), {})
+})
+
+test('an answered card leaves the count at once', () => {
+ const rt = fakeRuntime({ looseEnds: false, state: { questions: { 'chief-chat': { id: 'q1', question: 'Go?', askedAt: 1 } } } })
+ assert.equal(rt.operatorTasksView().chief.unresolved.length, 1)
+ delete rt.state.questions['chief-chat']
+ assert.equal(rt.operatorTasksView().chief, undefined)
+})
+
+test('the state answer carries operator tasks live, and a closed decision leaves at the next poll', async (t) => {
+ const { createRuntime } = await import('../index.js')
+ const { fakeContext } = await import('./fake-ctx.js')
+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-optasks-home-'))
+ const register = join(home, 'register.jsonl')
+ writeFileSync(register, line({ id: 'LE-1', ts: '2026-11-01T09:00:00', owner: 'Chief', kind: 'decision', text: 'Approve the plan', state: 'open' }))
+ const ctx = fakeContext({ services: {} })
+ let sessions = 0
+ Object.assign(ctx, {
+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },
+ workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} },
+ sessionController: { create: async () => ({ sessionId: `s${++sessions}` }), resolveAgent: async sessionId => ({ agent: { session: { id: sessionId }, followup: () => {} } }), selectModel: async () => {} },
+ sessionTitle: { rename: async () => {} },
+ sessions: { flush: async () => {} },
+ })
+ let route
+ const registerRoute = ctx.connection.fetch.register
+ ctx.connection.fetch.register = (options) => { route = options; return registerRoute(options) }
+ createRuntime(ctx, { home, looseEnds: register })
+ t.after(async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) })
+ const call = async (endpoint, payload) => (await (await route.fetch(new Request('http://localhost/api/bot', { method: 'POST', body: JSON.stringify({ endpoint, payload }) }))).json()).value
+
+ const first = await call('state', {})
+ const main = first.bots.find(bot => bot.id === first.mainBotId)
+ assert.equal(main.name, 'Chief')
+ assert.deepEqual(first.operatorTasks[main.id].unresolved.map(item => item.id), ['LE-1'])
+
+ writeFileSync(register, [
+ line({ id: 'LE-1', ts: '2026-11-01T09:00:00', owner: 'Chief', kind: 'decision', text: 'Approve the plan', state: 'open' }),
+ line({ id: 'LE-1', ts: '2026-11-02T09:00:00', owner: 'Chief', kind: 'decision', text: 'Approve the plan', state: 'closed' }),
+ ].join('\n'))
+ // The register is looked at again after its stat interval.
+ await new Promise(resolve => setTimeout(resolve, 2100))
+ 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')
+})
+
+const askPanel = items => tree(OperatorTasks({
+ bot: { id: 'coder' },
+ roster: { byId: {}, roomsById: {}, operatorTasks: { coder: { operator: items, active: [], unresolved: [] } } },
+}))
+const linesOf = (panel, className) => JSON.parse(JSON.stringify(findAll(panel, node => node.props?.className === className).map(textOf)))
+
+test('a running step sits below the ask and never replaces it', () => {
+ const panel = askPanel([{ kind: 'ask', key: 'turn', at: 10, text: 'Fix the sidebar card\nand show the step below it', tool: 'read', target: 'design_fidelity.py' }])
+ assert.deepEqual(linesOf(panel, 'bt-ops-text'), ['Fix the sidebar card'])
+ assert.deepEqual(linesOf(panel, 'bt-ops-note'), ['Running read on design_fidelity.py'])
+})
+
+test('work whose ask was not recorded says so, with the step as its note', () => {
+ const panel = askPanel([{ kind: 'ask', key: 'turn', at: 10, tool: 'read', target: 'design_fidelity.py' }])
+ assert.deepEqual(linesOf(panel, 'bt-ops-text'), ['The ask is not recorded'])
+ assert.deepEqual(linesOf(panel, 'bt-ops-note'), ['Running read on design_fidelity.py'])
+})
+
+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)
+})
diff --git a/ds-bot/test/owned-sessions.test.js b/ds-bot/test/owned-sessions.test.js
new file mode 100644
index 0000000000..3cf79bc1a3
--- /dev/null
+++ b/ds-bot/test/owned-sessions.test.js
@@ -0,0 +1,34 @@
+// local: sidebar-coexistence. The Bot list sits in the shell's own sidebar, so the shell
+// must know which Sessions the team owns to keep them out of its own sections. The
+// client publishes them on window.__dshBotSessions and fires the sessions event.
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { runInNewContext } from 'node:vm'
+import { dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { build } from 'esbuild'
+
+const bundle = await build({
+ stdin: { contents: "export { indexRoster, ownedSessionIds } from './src/client/sources.js'", resolveDir: dirname(dirname(fileURLToPath(import.meta.url))) },
+ bundle: true, format: 'cjs', platform: 'node', write: false, logLevel: 'silent',
+})
+const module = { exports: {} }
+runInNewContext(bundle.outputFiles[0].text, { module, exports: module.exports, require: () => ({}) })
+const { indexRoster } = module.exports
+// The bundle runs in its own realm; copy its arrays into this one before comparing.
+const ownedSessionIds = roster => [...module.exports.ownedSessionIds(roster)]
+
+test('the owned Sessions are every Bot part, every group Session and every Agent Session', () => {
+ const roster = indexRoster({
+ bots: [{ id: 'chief', sessionId: 'chief-2', parts: ['chief', 'chief-2'] }, { id: 'writer' }],
+ rooms: [{ id: 'ops', sessionId: 'ops-2', ownParts: ['ops', 'ops-2'], sessions: { chief: 'ops-chief', writer: 'ops-writer' } }],
+ agents: [{ id: 'agent', sessions: ['plain-1'] }],
+ })
+ assert.deepEqual(ownedSessionIds(roster).sort(), ['chief', 'chief-2', 'ops', 'ops-2', 'ops-chief', 'ops-writer', 'plain-1', 'writer'])
+ // A Session the shell opened on its own is not the team's.
+ assert.equal(ownedSessionIds(roster).includes('shell-session'), false)
+})
+
+test('an empty roster owns nothing', () => {
+ assert.deepEqual(ownedSessionIds(indexRoster({ bots: [], rooms: [] })), [])
+})
\ No newline at end of file
diff --git a/ds-bot/test/plugin-reload.test.js b/ds-bot/test/plugin-reload.test.js
index 7821458d74..89d6d844c3 100644
--- a/ds-bot/test/plugin-reload.test.js
+++ b/ds-bot/test/plugin-reload.test.js
@@ -300,7 +300,10 @@ test('a new request joins a recovered turn and is answered in its own turn', asy
assert.equal(delivered.some(item => item.replyTo === request.exchangeId), false, 'old work must not answer a new request')
assert.equal(delivered[0].deferred, true)
assert.equal(delivered[0].exchangeId, request.exchangeId)
- assert.equal(delivered[0].text, 'A separate new request')
+ // local: hand-back pointer. The Bot read the request in this Session during the
+ // recovered turn, so the deferred delivery points at it instead of repeating it.
+ assert.equal(delivered[0].text, 'You read its text during that task; it is above in this session. Answer it now.')
+ assert.equal(delivered[0].handedBack, true)
// A fresh turn still lets its first input claim it, rather than deferring forever.
emit(ctx, 'b', 'turn/start', { turn: 2 })
emit(ctx, 'b', 'user/message', message)
diff --git a/ds-bot/test/questions.test.js b/ds-bot/test/questions.test.js
index ed9a473a82..7697a1e3cb 100644
--- a/ds-bot/test/questions.test.js
+++ b/ds-bot/test/questions.test.js
@@ -65,7 +65,7 @@ test('a card asked in a hidden Bot-to-Bot turn goes to the dock, without its cal
const { emit, ask, questions, stop } = await start()
t.after(stop)
emit('writer', 'turn/start', { turn: 1 })
- emit('writer', 'user/message', { content: text('[Message from Chief]\nThe user wants a new Bot; ask them for its name'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } })
+ emit('writer', 'user/message', { content: text('[Message from Chief]\nThe user wants a new Bot; ask them for its name. CARD-IT-YOURSELF'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } })
await ask('writer', 'call-1')
const asked = (await questions()).writer
assert.equal(asked.question, 'Which name?')
@@ -87,3 +87,41 @@ test('a card asked in a visible turn stays at its call', async (t) => {
await ask('writer', 'call-3')
assert.equal((await questions()).writer.callId, 'call-3')
})
+
+// local: question-lifecycle. A card closes once the Bot finishes a later turn the user
+// could see that asked nothing; a hidden Bot-to-Bot turn in between leaves it open.
+test('a later visible turn that asks nothing closes the card; a hidden one leaves it', async (t) => {
+ const { emit, ask, questions, stop } = await start()
+ t.after(stop)
+ emit('writer', 'turn/start', { turn: 1 })
+ emit('writer', 'user/message', { content: text('Help me name a Bot'), source: { kind: 'user' } })
+ await ask('writer', 'call-1')
+ emit('writer', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
+ assert.equal((await questions()).writer.question, 'Which name?')
+
+ emit('writer', 'turn/start', { turn: 2 })
+ emit('writer', 'user/message', { content: text('[Message from Chief]\nstatus? CARD-IT-YOURSELF'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x9', hop: 0 } })
+ emit('writer', 'turn/end', { turn: 2, reason: { kind: 'completed' } })
+ assert.equal((await questions()).writer?.question, 'Which name?')
+
+ emit('writer', 'turn/start', { turn: 3 })
+ emit('writer', 'user/message', { content: text('never mind, call it Scout'), source: { kind: 'user' } })
+ emit('writer', 'turn/end', { turn: 3, reason: { kind: 'completed' } })
+ for (let count = 0; count < 50 && (await questions()).writer !== undefined; count += 1) await new Promise(resolve => setTimeout(resolve, 5))
+ assert.equal((await questions()).writer, undefined)
+})
+
+test('only a Main Bot voids another Bot\'s open question, and the card leaves', async (t) => {
+ const { emit, ask, questions, stop } = await start()
+ t.after(stop)
+ const voidQuestion = (args, sessionId) => rt.teamTools.find(d => d.name === 'void_question').execute(args, { agent: { id: sessionId } })
+ await assert.rejects(voidQuestion({ bot: 'Writer' }, 'chief'), /Writer has no open question/)
+ emit('writer', 'turn/start', { turn: 1 })
+ emit('writer', 'user/message', { content: text('Help me name a Bot'), source: { kind: 'user' } })
+ await ask('writer', 'call-1')
+ await assert.rejects(voidQuestion({ bot: 'Chief' }, 'writer'), /Only a Main Bot can void a question/)
+ assert.equal((await questions()).writer.question, 'Which name?')
+ const out = await voidQuestion({ bot: 'Writer', reason: 'the job moved' }, 'chief')
+ assert.match(out, /^The question of Writer is voided/)
+ assert.equal((await questions()).writer, undefined)
+})
\ No newline at end of file
diff --git a/ds-bot/test/run-mode.test.js b/ds-bot/test/run-mode.test.js
index 21454a7f18..bff9d9e23d 100644
--- a/ds-bot/test/run-mode.test.js
+++ b/ds-bot/test/run-mode.test.js
@@ -182,7 +182,9 @@ async function start(t, { saved = team() } = {}) {
}))).json()
const tool = (name, args, sessionId) => rt.teamTools.find(def => def.name === name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1' })
// `modelSelection`: where the step is about to go, as DSH captured it for the step.
- const preStep = (sessionId, messages = [], step = 1, modelSelection) => ctx.listeners.get('agent/pre-step').at(-1)(
+ // The part switch's listener, found by name as the other part tests do: the local
+ // step failure reporter (parts.js) is registered after it to wrap it.
+ const preStep = (sessionId, messages = [], step = 1, modelSelection) => ctx.listeners.get('agent/pre-step').find(listener => String(listener).includes('takeOverStep'))(
{ agent: agentOf(sessionId), messages, step, signal: AbortSignal.timeout(60_000), ...(modelSelection === undefined ? {} : { modelSelection }) }, async () => 'next')
const state = () => JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))
const handoffOf = sessionId => agentOf(sessionId).calls.filter(([kind, message]) => kind === 'followup' && message.source?.role === 'handoff').map(([, message]) => textOf(message)).at(-1)
diff --git a/ds-bot/test/scoped-tools-creation.test.js b/ds-bot/test/scoped-tools-creation.test.js
index 29b0dec3a0..a2c199ff60 100644
--- a/ds-bot/test/scoped-tools-creation.test.js
+++ b/ds-bot/test/scoped-tools-creation.test.js
@@ -277,7 +277,7 @@ test('a fresh part Session has the scoped tools before its first step', async (t
const moved = await host.tool('update_bot', { work_dir: project }, 'b')
assert.equal(String(moved).includes('From your next step on'), true)
// The next step sees the folder change and switches to a fresh part.
- const preStep = host.ctx.listeners.get('agent/pre-step').at(-1)
+ const preStep = host.ctx.listeners.get('agent/pre-step').find(listener => String(listener).includes('takeOverStep'))
const answer = await preStep(
{ agent: host.agentOf('b'), messages: [{ role: 'user', content: [{ type: 'text', text: 'go on' }], source: { kind: 'user' } }], step: 2, signal: AbortSignal.timeout(60_000) },
async () => 'next',
diff --git a/ds-bot/test/sidebar-switch.test.js b/ds-bot/test/sidebar-switch.test.js
index b0e6c425e1..a823219114 100644
--- a/ds-bot/test/sidebar-switch.test.js
+++ b/ds-bot/test/sidebar-switch.test.js
@@ -334,34 +334,46 @@ test('what the team view replaces in the shell sidebar stays out of sight', () =
}
})
-function collapsedGridRules() {
- const { document } = new JSDOM('').window
- document.querySelector('style').textContent = `${SHELL_CSS}\n${SIDEBAR_CSS}`
- const frames = []
- const visit = (rules, media = []) => {
- for (const rule of rules) {
- if (rule.selectorText?.includes('[data-sidebar-collapsed][data-rightbar-collapsed]'))
- frames.push({ grid: rule.style.getPropertyValue('grid-template-columns'), media })
- if (rule.cssRules?.length)
- visit(rule.cssRules, rule.media ? [...media, rule.media.mediaText] : media)
- }
- }
- visit(document.styleSheets[0].cssRules)
- return frames
-}
-
-test('the wide shell\'s collapsed sidebar keeps no track while its right column is closed', () => {
- const frames = collapsedGridRules()
- assert.equal(frames.length, 1)
- assert.match(frames[0].grid, /^0px\s+minmax\(0,\s*1fr\)\s+0px$/)
+// local: sidebar-coexistence. The Bot list sits inside the shell's own sidebar column,
+// so the shell keeps its own tracks: nothing zeroes them, the column is not drawn over
+// the page, and its edge grip gives way to the shell's own resizer.
+test('the Bot list sits in the shell\'s sidebar and leaves the shell its own tracks', () => {
+ const all = [...rulesOf(SHELL_CSS), ...rulesOf(SIDEBAR_CSS)]
+ assert.equal(all.some(rule => rule.selector.includes('[data-sidebar-collapsed][data-rightbar-collapsed]') && /grid-template-columns/.test(rule.body)), false)
+ const last = selector => all.filter(rule => rule.selector === selector).map(rule => rule.body).pop() ?? ''
+ assert.match(last('.bt-leftcol'), /(^|;)position:relative/)
+ assert.match(last('.bt-leftcol'), /(^|;)animation:none/)
+ assert.match(last('.bt-leftcol>.bt-leftcol-grip'), /(^|;)display:none/)
})
-// A narrow host may place the conversation in its first track instead of its second.
-test('the collapsed shell grid override leaves layouts below 1024px to the host', () => {
- const frames = collapsedGridRules()
- assert.equal(frames.length, 1)
- assert.ok(frames[0].media.some(query => /^\(min-width:\s*1024px\)$/.test(query)),
- 'the zero-width first track must not override a narrow host layout')
+test('every Main Bot tiles at the top of the list, and a seated account is not drawn twice', () => {
+ viewport.innerWidth = 1280
+ const chief = { id: 'chief', name: 'Chief', createdAt: 1 }
+ const igor = { id: 'igor', name: 'Igor', createdAt: 2 }
+ const writer = { id: 'writer', name: 'Writer', createdAt: 3 }
+ const roster = { bots: [chief, igor, writer], rooms: [], agents: [], byId: { chief, igor, writer }, mainBotId: 'chief', mainBotIds: ['chief', 'igor'], ready: true }
+ const find = (node, match, out = []) => {
+ if (Array.isArray(node)) { node.forEach(child => find(child, match, out)); return out }
+ if (!node || typeof node !== 'object') return out
+ if (match(node)) out.push(node)
+ find(node.props?.children, match, out)
+ return out
+ }
+ const render = seated => TeamSidebar({
+ wide: true, actions: { toggleSidebar() {} },
+ useRoster: pick => pick(roster), useUi: pick => pick({ unread: {}, accountSeated: seated }), useRegistry: pick => pick({}),
+ useSessions: pick => pick({ ids: [], byId: {} }), useUpdate: () => ({}),
+ })
+ const tree = render(false)
+ const [grid] = find(tree, node => node.props?.className === 'bt-tile-grid')
+ assert.deepEqual(find(grid, node => node.type?.name === 'BotRow').map(row => row.props.bot.id), ['chief', 'igor'])
+ // The other Main Bot is not listed a second time among the rows below.
+ assert.deepEqual(find(tree, node => node.type?.name === 'BotRow').map(row => row.props.bot.id), ['chief', 'igor', 'writer'])
+ assert.equal(find(tree, node => node.type?.name === 'AccountLauncher').length, 1)
+ assert.equal(find(render(true), node => node.type?.name === 'AccountLauncher').length, 0)
+ // The column renders in place, not portalled onto .
+ const [column] = find(tree, node => node.type?.name === 'LeftColumn')
+ assert.equal(column.props.width, undefined)
})
test('the column\'s top row hides it, on the rail too, and its edge is a drag grip', () => {
@@ -373,7 +385,8 @@ test('the column\'s top row hides it, on the rail too, and its edge is a drag gr
useRoster: pick => pick(roster), useUi: pick => pick({ unread: {} }), useRegistry: pick => pick({}),
useSessions: pick => pick({ ids: [], byId: {} }), useUpdate: () => ({}),
useSidebarPref: pick => pick(pref),
- actions: { toggleLeftHidden: () => calls.push('toggle'), toggleSidebar: () => {} },
+ // local: sidebar-coexistence. The shell's own switch hides the column that holds the list.
+ actions: { toggleLeftHidden: () => calls.push('own'), toggleSidebar: () => calls.push('toggle') },
})
const find = (node, match) => {
if (Array.isArray(node)) return node.map(child => find(child, match)).find(Boolean)
@@ -533,7 +546,8 @@ test('a drag that ends on the rail leaves the column at the rail width', async (
release(100)
await settle(800)
assert.equal(leftColumn().mode, 'rail')
- assert.equal(leftColumn().width, 88)
+ // local: sidebar-coexistence. The shell's column owns the width; none is passed in.
+ assert.equal(leftColumn().width, undefined)
assert.equal(column.style.width, '88px')
assert.equal(column.hasAttribute('data-folding'), false)
})
@@ -545,7 +559,7 @@ test('a reduced-motion drag that unfolds the rail lands at the dragged width', a
for (const x of [120, 160, 200, 260, 330]) move(x)
release(330)
assert.equal(leftColumn().mode, 'open')
- assert.equal(leftColumn().width, 330)
+ assert.equal(leftColumn().width, undefined)
assert.equal(column.style.width, '330px')
assert.equal(column.hasAttribute('data-folding'), false)
})
@@ -567,7 +581,7 @@ test('after a snap the spring stops and the drag follows the cursor', async () =
}
release(330)
await settle(800)
- assert.equal(leftColumn().width, 330)
+ assert.equal(leftColumn().width, undefined)
assert.equal(column.style.width, '330px')
})
})
diff --git a/ds-bot/test/switch-keeps-input.test.js b/ds-bot/test/switch-keeps-input.test.js
index 0b760f5fa9..ac3d311a0c 100644
--- a/ds-bot/test/switch-keeps-input.test.js
+++ b/ds-bot/test/switch-keeps-input.test.js
@@ -156,7 +156,7 @@ async function start({ fail = {}, services = {}, home: reuse, state: seed = TEAM
method: 'POST', body: JSON.stringify({ endpoint, payload }),
}))).json()
const tool = (name, args, sessionId) => rt.teamTools.find(d => d.name === name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1' })
- const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(-1)(
+ const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').find(listener => String(listener).includes('takeOverStep'))(
{ agent: agentOf(sessionId), messages, step, signal: AbortSignal.timeout(60_000) }, async () => 'next')
// A Session event as DSH emits it, on the Session the test's Agent holds.
let seq = 0
diff --git a/ds-bot/test/view-reply.test.js b/ds-bot/test/view-reply.test.js
index 64cf57d5dc..561f0d3e43 100644
--- a/ds-bot/test/view-reply.test.js
+++ b/ds-bot/test/view-reply.test.js
@@ -133,10 +133,11 @@ test('show_view registers an interactive card, refuses a group and a display-onl
assert.equal(typeof open.views['writer-now'].askedAt, 'number')
assert.deepEqual(open.views['writer-now'].view, CHOICES)
- // A hidden Bot-to-Bot turn keeps the card but not the call.
+ // A hidden Bot-to-Bot turn keeps the card but not the call (the job opts in to
+ // carding the user; without it the card gate sends the card to Chief).
emit('writer-now', 'turn/end', { turn: 1, reason: { kind: 'completed' } })
emit('writer-now', 'turn/start', { turn: 2 })
- emit('writer-now', 'user/message', { content: text('[Message from Chief]\nAsk them'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } })
+ emit('writer-now', 'user/message', { content: text('[Message from Chief]\nAsk them. CARD-IT-YOURSELF'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } })
const hidden = await show('writer-now', { title: 'Pick', view: CHOICES }, 'call-hidden')
assert.equal(hidden.concluded, true)
assert.equal((await team()).views['writer-now'].callId, undefined)
@@ -209,7 +210,7 @@ test('view-reply claims the card, refuses a stale or invalid answer, and restore
assert.equal(again.error.message, 'This view is no longer open')
})
-test('dismiss-view drops the open view, keeps it as a closed card, and leaves a question card alone', async (t) => {
+test('dismiss-view drops the open view and leaves a question card alone', async (t) => {
const { show, call, team, stop } = await start()
t.after(stop)
await rt.teamTools.find(d => d.name === 'list_bots').execute({}, { agent: { id: 'chief' } })
@@ -222,20 +223,7 @@ test('dismiss-view drops the open view, keeps it as a closed card, and leaves a
const open = await team()
assert.equal(open.views['writer-now'], undefined)
assert.equal(open.questions['writer-now'].question, 'Keep me')
- assert.deepEqual(open.closedCards, { 'writer-now': { 'call-1': 'dismissed' } })
assert.equal((await call('dismiss-view', { sessionId: 'writer-now' })).ok, true)
- assert.equal((await call('dismiss-question', { sessionId: 'writer-now' })).ok, true)
- assert.deepEqual((await team()).closedCards, { 'writer-now': { 'call-1': 'dismissed', 'q-call': 'dismissed' } })
-})
-
-test('an answered view is not kept as a closed card: its reply message carries it', async (t) => {
- const { show, call, team, stop } = await start()
- t.after(stop)
- await rt.teamTools.find(d => d.name === 'list_bots').execute({}, { agent: { id: 'chief' } })
- await show('writer-now', { title: 'Pick', view: CHOICES })
- const pending = (await team()).views['writer-now']
- assert.equal((await call('view-reply', { sessionId: 'writer-now', viewId: pending.id, action: 'pick', values: { selected: ['A'] } })).ok, true)
- assert.deepEqual((await team()).closedCards, {})
})
test('a user message drops the open question and the open view together', async (t) => {
@@ -253,8 +241,6 @@ test('a user message drops the open question and the open view together', async
const open = await team()
assert.equal(open.questions['writer-now'], undefined)
assert.equal(open.views['writer-now'], undefined)
- // Both cards stay in the chat as answered by that message.
- assert.deepEqual(open.closedCards, { 'writer-now': { 'q-call': 'replied', 'call-1': 'replied' } })
// A card with a call row does not also leave a dock record.
assert.deepEqual(open.closedViews, {})
})
diff --git a/ds-bot/test/work-dir.test.js b/ds-bot/test/work-dir.test.js
index 3a6e71ff40..281502d47a 100644
--- a/ds-bot/test/work-dir.test.js
+++ b/ds-bot/test/work-dir.test.js
@@ -114,7 +114,7 @@ async function start({ services = {}, workspaces = [], llm, team: saved = TEAM,
}))).json()
const tool = (name, args, sessionId) => rt.teamTools.find(d => d.name === name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1' })
// Runs the parts check, registered last; 'next' means the step goes on.
- const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(-1)(
+ const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').find(listener => String(listener).includes('takeOverStep'))(
{ agent: agentOf(sessionId), messages, step, signal: AbortSignal.timeout(60_000) }, async () => 'next')
const state = () => JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))
// Waits until the Bot's own chat runs in `dir` and its move has finished.